path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
day-08/src/main/kotlin/SevenSegmentSearch.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") } private const val DELIMITER = " | " private const val SPACE = " " private fun partOne(): Int { return readInputLines() .flatMap { it.split(DELIMITER)[1].split(SPACE) } .count { val length = it.length length == 2 || length == 3 || length == 4 || length == 7 } } private fun partTwo(): Int { return readInputLines().sumOf { val (left, right) = it.split(DELIMITER) val patterns = left.split(SPACE) val one = patterns.find { p -> p.length == 2 }!! val six = patterns.find { p -> p.length == 6 && !getIntersection(p, one).equalsIgnoreOrder(one) }!! val rightBottomSegment = getIntersection(one, six) val three = patterns.find { p -> p.length == 5 && getIntersection(p, one).equalsIgnoreOrder(one) }!! val five = patterns.find { p -> p.length == 5 && p != three && getIntersection(p, rightBottomSegment) == rightBottomSegment }!! val two = patterns.find { p -> p.length == 5 && p != three && p != five }!! val rightTopSegment = getIntersection(two, one) val eight = patterns.find { p -> p.length == 7 }!! val nine = patterns.find { p -> p.length == 6 && getIntersection(p, three).equalsIgnoreOrder(three) }!! val bottomLeftSegment = getNonIntersecting(eight, nine) val displays = right.split(SPACE) displays.map { display -> getDigit( display = display, rightTop = rightTopSegment, rightBottom = rightBottomSegment, bottomLeft = bottomLeftSegment ) }.joinToString("").toInt() } } fun getDigit(display: String, rightTop: String, rightBottom: String, bottomLeft: String): Int { return when (display.length) { 2 -> 1 3 -> 7 4 -> 4 5 -> if (!display.contains(rightBottom)) 2 else if (display.contains(rightTop)) 3 else 5 6 -> if (!display.contains(rightTop)) 6 else if (display.contains(bottomLeft)) 0 else 9 7 -> 8 else -> throw RuntimeException("Impossible state") } } fun String.equalsIgnoreOrder(other: String): Boolean { return this.toSortedSet() == other.toSortedSet() } fun getIntersection(first: String, second: String): String { return first.toSortedSet() .intersect(second.toSortedSet()) .joinToString("") } fun getNonIntersecting(first: String, second: String): String { val intersection = getIntersection(first, second) val toReturn = (first + second).toSortedSet().toMutableList() toReturn.removeAll(intersection.toSortedSet()) return toReturn.joinToString("") } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
2,991
aoc-2021
MIT License
src/Day04.kt
marciprete
574,547,125
false
{"Kotlin": 13734}
fun main() { fun part1(input: List<String>): Int { return input .map { val split = it.trim().split(",") Pair(split.get(0).toRange(), split.get(1).toRange()) .inEachOther() }.count { it } } fun part2(input: List<String>): Int { return input .map { val split = it.trim().split(",") Pair(split.get(0).split("-").map { it.toInt() }, split.get(1).split("-").map { it.toInt() }) } .map { when { it.first.get(0) == it.second.get(0) -> true it.first.get(0) > it.second.get(0) -> it.first.get(0) <= it.second.get(1) it.first.get(0) < it.second.get(0) -> it.first.get(1) >= it.second.get(0) else -> false } }.count{it} } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun <A, B> Pair<List<A>, List<B>>.inEachOther(): Boolean { val pair = (this.toList().sortedBy { it.size }) return pair.get(1).containsAll(pair.get(0)) } private fun String.toRange(): List<Int> { val edges = this.split("-") return IntRange(edges.get(0).toInt(), edges.get(1).toInt()).toList() }
0
Kotlin
0
0
6345abc8f2c90d9bd1f5f82072af678e3f80e486
1,530
Kotlin-AoC-2022
Apache License 2.0
src/Day08.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Int { val trees = input.map { line -> line.split("").filter(String::isNotBlank).map(String::toInt) } val visibleTrees = mutableListOf<Int>() for (y in trees.indices) { val row = trees[y] for (x in row.indices) { if (x == 0 || x == row.lastIndex || y == 0 || y == trees.lastIndex || isVisible(trees, x, y)) { visibleTrees.add(row[x]) } } } return visibleTrees.count() } fun part2(input: List<String>): Int { val trees = input.map { line -> line.split("").filter(String::isNotBlank).map(String::toInt) } var max = 0 for (y in trees.indices) { val row = trees[y] for (x in row.indices) { max = calculateScore(trees, x, y).takeIf { it > max } ?: max } } return max } val input = readInput("Day08") println(part1(input)) println(part2(input)) } private fun isVisible(trees: List<List<Int>>, x: Int, y: Int): Boolean { val row = trees[y] val height = row[x] val above = (0 until y).all { trees[it][x] < height } val below = (y + 1 until trees.size).all { trees[it][x] < height } val left = (0 until x).all { trees[y][it] < height } val right = (x + 1 until row.size).all { trees[y][it] < height } return above || below || left || right } private fun calculateScore(trees: List<List<Int>>, x: Int, y: Int): Int { if (x == 0 || x == trees[y].lastIndex || y == 0 || y == trees.lastIndex) return 0 val row = trees[y] val height = row[x] val above = (y - 1 downTo 0).takeWhile { it > 0 && trees[it][x] < height }.count() + 1 val below = (y + 1 until trees.size).takeWhile { it < trees.lastIndex && trees[it][x] < height }.count() + 1 val left = (x - 1 downTo 0).takeWhile { it > 0 && trees[y][it] < height }.count() + 1 val right = (x + 1 until row.size).takeWhile { it < row.lastIndex && trees[y][it] < height }.count() + 1 return above * below * left * right }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
2,121
aoc-2022
Apache License 2.0
src/Day15.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { fun IntRange.intersects(other: IntRange) = (first <= other.first && last in other.first..other.last) || (last <= other.last && first in other.last..other.first) || (first <= other.first && last >= other.last) || (last <= other.last && first >= other.first) fun IntRange.removePoint(point: Int): Sequence<IntRange> = when { point !in first..last -> sequenceOf(this) first == last -> sequenceOf() first == point -> sequenceOf(first + 1..last) last == point -> sequenceOf(first until last) else -> sequenceOf(first until point, point + 1..last) } fun freeRanges( row: Int, read: List<Pair<Point15, Point15>>, ): Sequence<IntRange> { return read .asSequence() .map { (beacon, sensor) -> val dist = sensor.manhattanDistanceTo(beacon) val rowDiff = abs(row - sensor.y) val onTheLine = dist * 2 + 1 - 2 * rowDiff Pair(sensor.x, onTheLine) } .filterNot { it.second <= 0 } .map { (center, size) -> val dx = size / 2 (center - dx)..(center + dx) } .sortedBy { it.first } .fold(sequenceOf()) { curList: Sequence<IntRange>, nextRange -> val candidates = curList.toHashSet() val result = curList.toHashSet() if (result.none { it.intersects(nextRange) }) return@fold curList + listOf(nextRange) var next = candidates.find { it.intersects(nextRange) } while (next!=null) { candidates.remove(next) result.remove(next) result.add(min(next.first, nextRange.first)..max(next.last, nextRange.last)) next = candidates.find { it.intersects(nextRange) } } return@fold result.asSequence() } } fun inputToData(input: List<String>) = input .asSequence() .map { Regex("-?\\d+").findAll(it).map { it.value.toInt() }.toList() } .filterNot { it.isEmpty() } .map { (a, b, c, d) -> Point15(c, d) to Point15(a, b) } .toList() fun part1(input: List<String>, row: Int): Int { val beaconsToSensors = inputToData(input) val freeRanges = freeRanges(row, beaconsToSensors) return freeRanges .flatMap { range -> beaconsToSensors .asSequence() .map(Pair<Point15, Point15>::first) .distinct() .filter { it.y == row } .map(Point15::x) .flatMap(range::removePoint) .takeIf(Sequence<IntRange>::any) ?: sequenceOf(range) } .map { it.also(::println) } .sumOf { it.last - it.first + 1 } } fun part2(input: List<String>, row: Int): Long { val read = inputToData(input) return (0..row) .asSequence() .map { curRow -> val rangeList = freeRanges(curRow, read).toList() if (rangeList.size > 1) { val x = rangeList[0].last + 1 return@map x.toLong() * 4000000 + curRow } else return@map 0 } .first { it != 0L } } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) println() val input = readInput("Day15") println(part1(input, 2000000)) println() println(part2(input, 4000000)) } data class Point15(val x: Int, val y: Int) { fun manhattanDistanceTo(other: Point15) = abs(x - other.x) + abs(y - other.y) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
3,888
aoc-2022
Apache License 2.0
src/com/ncorti/aoc2023/Day23.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 fun main() { fun parseInput(): Array<CharArray> { return getInputAsText("23") { split("\n").filter(String::isNotBlank).map { it.toCharArray() } }.toTypedArray() } val neighbours = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) fun computeMaxPath(map: Array<CharArray>, x: Int, y: Int, fromX: Int, fromY: Int, count: Int, seen: String): Int { if (x == map.size - 1 && y == map[0].size - 2) { return count } val next = neighbours.map { (dx, dy) -> x + dx to y + dy }.filter { it -> it.first in map.indices && it.second in map[0].indices && (it != fromX to fromY) && map[it.first][it.second] != '#' }.filter { "#${it.first}-${it.second}#" !in seen }.filter { (nx, ny) -> if (nx == x + 1 && map[nx][ny] == '^') { false } else if (nx == x - 1 && map[nx][ny] == 'v') { false } else if (ny == y + 1 && map[nx][ny] == '<') { false } else if (ny == y - 1 && map[nx][ny] == '>') { false } else { true } } return if (next.isEmpty()) { 0 } else { next.maxOf { (nx, ny) -> computeMaxPath(map, nx, ny, x, y, count + 1, "$seen,#$nx-$ny#") } } } fun findConjunctions(map: Array<CharArray>): MutableMap<Pair<Int, Int>, MutableList<Triple<Int, Int, Int>>> { val result = mutableMapOf<Pair<Int, Int>, MutableList<Triple<Int, Int, Int>>>() for (i in 1..<map.lastIndex) { for (j in 1..<map[i].lastIndex) { val hashCount = neighbours.count { (di, dj) -> map[i + di][j + dj] == '#' } if (map[i][j] == '.' && (hashCount == 1 || hashCount == 0)) { result[i to j] = mutableListOf() } } } return result } fun computeConjunctionGraph( map: Array<CharArray>, conjunctions: MutableMap<Pair<Int, Int>, MutableList<Triple<Int, Int, Int>>> ) { conjunctions.forEach { (start, list) -> val seen = mutableSetOf<Pair<Int, Int>>() val queue = mutableListOf<Triple<Int, Int, Int>>() neighbours.forEach { (dx, dy) -> if (start.first + dx in map.indices && start.second + dy in map[0].indices && map[start.first + dx][start.second + dy] != '#') { queue.add(Triple(start.first + dx, start.second + dy, 1)) } } while (queue.isNotEmpty()) { val (x, y, dist) = queue.removeAt(0) seen.add(x to y) if (x to y in conjunctions && x to y != start) { list.add(Triple(x, y, dist)) } else { neighbours.forEach { (dx, dy) -> if (map[x + dx][y + dy] != '#' && x + dx to x + dy != start && (x + dx to y + dy !in seen)) { queue.add(Triple(x + dx, y + dy, dist + 1)) } } } } } } class Status(val point: Pair<Int, Int>, val dist: Int, val seen: Set<Pair<Int, Int>>) fun computeLongestPath( conjunctions: MutableMap<Pair<Int, Int>, MutableList<Triple<Int, Int, Int>>>, start: Pair<Int, Int>, end: Pair<Int, Int> ): Int { var max = 0 val queue = mutableListOf(Status(start, 0, setOf(start))) while (queue.isNotEmpty()) { val current = queue.removeLast() val (x, y) = current.point val dist = current.dist val seen = current.seen.toMutableSet().toSet() val next = conjunctions[x to y]!! next.forEach { (nx, ny, ndist) -> if (nx to ny == end) { if (dist + ndist > max) { max = dist + ndist } } else if (nx to ny !in seen) { queue.add(Status(nx to ny, dist + ndist, seen + (nx to ny))) } } } return max } fun part1(): Int { val map = parseInput() return computeMaxPath(map, 0, 1, 0, 0, 0, "#0-1#") } fun part2(): Int { val map = parseInput() val conjunctions = findConjunctions(map) conjunctions[0 to 1] = mutableListOf() conjunctions[map.size - 1 to map[0].size - 2] = mutableListOf() computeConjunctionGraph(map, conjunctions) return computeLongestPath(conjunctions, 0 to 1, map.size - 1 to map[0].size - 2) } println(part1()) println(part2()) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
4,825
adventofcode-2023
MIT License
src/Day03.kt
martintomac
726,272,603
false
{"Kotlin": 19489}
fun main() { fun extractSymbols(line: String) = "([^0-9.])".toRegex() .findAll(line) .map { match -> match.value to match.range.first } .toList() fun extractNumbers(line: String) = "(\\d+)".toRegex().findAll(line) .map { match -> match.value.toInt() to match.range } .toList() fun Int.toRange() = this..this fun IntRange.expand(left: Int, right: Int) = (first - left)..(last + right) fun Map<Int, List<Pair<Int, IntRange>>>.findNeighborNumbers( symPoint: Pair<Int, Int> ): List<Pair<Int, IntRange>> { val lineNum = symPoint.first val symLocation = symPoint.second return symLocation.toRange().expand(1, 1) .flatMap { neighborLocation -> lineNum.toRange().expand(1, 1) .flatMap { this[it]?.filter { (_, range) -> neighborLocation in range }.orEmpty() } } .distinct() } fun sumOfSerialNumbers(lines: List<String>): Int { val lineToNumbers = lines.mapIndexed { lineNum, line -> lineNum to extractNumbers(line) } .toMap() return lines .mapIndexed { lineNum, line -> val symbols = extractSymbols(line) symbols.flatMap { (_, symLocation) -> lineToNumbers.findNeighborNumbers(lineNum to symLocation) } } .flatten() .sumOf { it.first } } fun sumOfGearRatios(lines: List<String>): Int { val lineToNumbers = lines.mapIndexed { lineNum, line -> lineNum to extractNumbers(line) } .toMap() return lines .mapIndexed { lineNum, line -> val multiplySymbols = extractSymbols(line).filter { (value, _) -> value == "*" } multiplySymbols.mapNotNull { (_, mulLocation) -> val operands = lineToNumbers.findNeighborNumbers(lineNum to mulLocation) when { operands.size < 2 -> null operands.size == 2 -> operands[0].first * operands[1].first else -> throw UnsupportedOperationException("Cartesian product not supported") } } } .flatten() .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") sumOfSerialNumbers(testInput).println() sumOfGearRatios(testInput).println() val input = readInput("Day03") sumOfSerialNumbers(input).println() sumOfGearRatios(input).println() }
0
Kotlin
0
0
dc97b23f8461ceb9eb5a53d33986fb1e26469964
2,638
advent-of-code-2023
Apache License 2.0
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day08/Day08.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2021.day08 import nl.sanderp.aoc.common.measureDuration import nl.sanderp.aoc.common.prettyPrint import nl.sanderp.aoc.common.readResource data class Entry(val pattern: List<String>, val values: List<String>) fun main() { val input = readResource("Day08.txt").lines().map { line -> val (patterns, values) = line.split(" | ").map { it.split(" ") } Entry(patterns, values) } val (answer1, duration1) = measureDuration<Int> { partOne(input) } println("Part one: $answer1 (took ${duration1.prettyPrint()})") val (answer2, duration2) = measureDuration<Int> { partTwo(input) } println("Part two: $answer2 (took ${duration2.prettyPrint()})") } private fun solve(entry: Entry): Int { val mapping = mutableMapOf( 1 to entry.pattern.first { it.length == 2 }, 4 to entry.pattern.first { it.length == 4 }, 7 to entry.pattern.first { it.length == 3 }, 8 to entry.pattern.first { it.length == 7 }, ) mapping[9] = entry.pattern.first { it.length == 6 && it.containsCharsOf(mapping[4]!!) } mapping[6] = entry.pattern.first { it.length == 6 && !it.containsCharsOf(mapping[1]!!) } mapping[0] = entry.pattern.first { it.length == 6 && !mapping.containsValue(it) } mapping[3] = entry.pattern.first { it.length == 5 && it.containsCharsOf(mapping[1]!!) } mapping[5] = entry.pattern.first { it.length == 5 && (it + mapping[1]!!).hasSameCharsAs(mapping[9]!!) } mapping[2] = entry.pattern.first { !mapping.containsValue(it) } return entry.values.map { x -> mapping.filterValues { it.hasSameCharsAs(x) }.keys.first() }.joinToString("").toInt() } private fun partOne(entries: List<Entry>) = entries.sumOf { entry -> entry.values.count { it.length == 2 || it.length == 3 || it.length == 4 || it.length == 7 } } private fun partTwo(entries: List<Entry>) = entries.sumOf { solve(it) } private fun String.hasSameCharsAs(other: String) = this.containsCharsOf(other) && other.containsCharsOf(this) private fun String.containsCharsOf(other: String) = other.all { this.contains(it) }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,098
advent-of-code
MIT License
src/Day08.kt
romainbsl
572,718,344
false
{"Kotlin": 17019}
fun main() { fun initForest(input: List<String>): Forest { val width = input.first().count() val height = input.count() val grid = input.foldIndexed(Array(height) { Tree.emptyArray(width) }) { rowId, forest, row -> forest.apply { this[rowId] = row.foldIndexed(Tree.emptyArray(width)) { colId, treeLine, tree -> treeLine.apply { this[colId] = Tree(tree.digitToInt(), colId == 1 || rowId == 1) } } } } return Forest(width, height, grid) } fun part1(input: List<String>): Int { val (width, height, grid) = initForest(input) return grid.mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, tree -> val colValues = grid.map { it[colIndex] } val isOnEdge = rowIndex == 0 || colIndex == 0 || rowIndex == height - 1 || colIndex == width - 1 val isVisibleFromTop = colValues.take(rowIndex).all { it < tree } val isVisibleFromRight = row.drop(colIndex + 1).all { it < tree } val isVisibleFromBottom = colValues.drop(rowIndex + 1).all { it < tree } val isVisibleFromLeft = row.take(colIndex).all { it < tree } tree.copy( isVisible = isOnEdge || isVisibleFromTop || isVisibleFromRight || isVisibleFromBottom || isVisibleFromLeft ) } }.sumOf { row -> row.count { it.isVisible } } } fun part2(input: List<String>): Int { val (_, _, grid) = initForest(input) return grid.mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, tree -> val colValues = grid.map { it[colIndex] } fun List<Tree>.takeVisible() = takeUntil { it >= tree } val topVisibleTrees = colValues .take(rowIndex).reversed().takeVisible() val rightVisibleTrees = row .drop(colIndex + 1).takeVisible() val bottomVisibleTrees = colValues .drop(rowIndex + 1).takeVisible() val leftVisibleTrees = row .take(colIndex).reversed().takeVisible() topVisibleTrees.size * rightVisibleTrees.size * bottomVisibleTrees.size * leftVisibleTrees.size } }.flatten().max() } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") check(part1(input) == 1779) check(part2(input) == 172224) } data class Forest(val width: Int, val height: Int, val grid: Array<Array<Tree>>) data class Tree(val height: Int, val isVisible: Boolean = false) : Comparable<Tree> { override fun compareTo(other: Tree) = this.height.compareTo(other.height) companion object { fun emptyArray(size: Int) = Array<Tree>(size) { Tree(-1) } } }
0
Kotlin
0
0
b72036968769fc67c222a66b97a11abfd610f6ce
3,282
advent-of-code-kotlin-2022
Apache License 2.0
y2022/src/main/kotlin/adventofcode/y2022/Day16.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2022 import adventofcode.io.AdventSolution object Day16 : AdventSolution(2022, 16, "Proboscidea Volcanium") { override fun solvePartOne(input: String): Int { val valves = parse(input) val interestingValves = valves.filter { it.rate > 0 || it.name == "AA" }.associate { it.name to it.rate } val distances = distances(interestingValves.keys, valves.associate { it.name to it.neighbors }) return solvePartial(interestingValves, distances, 30) } override fun solvePartTwo(input: String): Int { val valves = parse(input) val interestingValves = valves.filter { it.rate > 0 || it.name == "AA" }.associate { it.name to it.rate } val distances = distances(interestingValves.keys, valves.associate { it.name to it.neighbors }) val excluded = setOf(interestingValves.keys.first { it != "AA" }, "AA") val ps = interestingValves.keys.filter { it !in excluded }.powerset() return ps.maxOf { toInclude -> val humanSet = interestingValves.filterKeys { it in toInclude + "AA" } val elephantSet = interestingValves.filterKeys { it !in toInclude } solvePartial(humanSet, distances, 26) + solvePartial(elephantSet, distances, 26) } } private fun solvePartial( interestingValves: Map<String, Int>, distances: Map<String, Map<String, Int>>, bound: Int ): Int { val partials = List(bound) { mutableSetOf<Partial>() } partials[0] += Partial(setOf("AA"), "AA", 0) for (t in partials.indices) { val scoreToBeat = partials.drop(t).maxOfOrNull { it.maxOfOrNull { it.score } ?: 0 } ?: 0 for (old in partials[t]) { //prune if we can never catch up //heuristic: we open the best valve every 2 minutes (minimum distance is 2) val maximalRate = interestingValves .filterKeys { it !in old.opened } .values .sortedDescending() .scan(0, Int::plus) .take((bound - t) / 2) .sum() if (old.score + maximalRate <= scoreToBeat) continue for ((goal, rate) in interestingValves) { if (goal in old.opened) continue val time = distances.getValue(old.position).getValue(goal) + 1 if (t + time >= bound) continue partials[t + time] += Partial( opened = old.opened + goal, position = goal, score = old.score + (bound - (t + time)) * rate ) } } } return partials.flatten().maxOf { it.score } } } data class Partial(val opened: Set<String>, val position: String, val score: Int) private fun parse(input: String): List<Valve> = input.lines().map { line -> Valve( name = line.substringAfter("Valve ").substringBefore(" "), rate = line.substringAfter("rate=").substringBefore(";").toInt(), neighbors = line.substringAfter(" to valve").substringAfter(" ").split(", ") ) } private fun distances( interestingValves: Set<String>, links: Map<String, List<String>> ): Map<String, Map<String, Int>> { fun bfs(start: String, reachableNeighbors: (String) -> Iterable<String>): List<Set<String>> = generateSequence(Pair(setOf(start), setOf(start))) { (frontier, visited) -> val unexploredNeighbors = frontier.flatMap(reachableNeighbors).toSet() - visited Pair(unexploredNeighbors, visited + unexploredNeighbors) } .takeWhile { (frontier, _) -> frontier.isNotEmpty() } .map { it.first } .toList() return interestingValves.associateWith { start -> bfs(start) { str -> links[str].orEmpty() }.map { it.filter { it in interestingValves } } .flatMapIndexed { index, ends -> ends.filter { it != start && it != "AA" }.map { it to index } }.toMap() } } private data class Valve(val name: String, val rate: Int, val neighbors: List<String>) private fun List<String>.powerset(): List<List<String>> { return if (this.isEmpty()) listOf(listOf()) else listOf(listOf(), take(1)).flatMap { strings: List<String> -> drop(1).powerset().map { it + strings } } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
4,470
advent-of-code
MIT License
src/Day08.kt
palex65
572,937,600
false
{"Kotlin": 68582}
fun <R> List<String>.mapEachCharIndexed(transform: (row: Int, col: Int, char: Char)->R ): List<R> { val res = mutableListOf<R>() for(row in indices) { val line = get(row) for (col in line.indices) res.add(transform(row, col, line[col])) } return res } private fun part1(grid: List<String>) = grid.mapEachCharIndexed { row, col, tree -> row == 0 || col == 0 || row == grid.lastIndex || col == grid.first().lastIndex || // around (col + 1..grid[row].lastIndex).all { grid[row][it] < tree } || // right (col - 1 downTo 0).all { grid[row][it] < tree } || // left (row + 1..grid.lastIndex).all { grid[it][col] < tree } || // down (row - 1 downTo 0).all { grid[it][col] < tree } // up }.count { it } private fun List<String>.scenicScore(l: Int, c: Int, height: Char): Int { if (l==0 || c==0 || l==lastIndex || c==first().lastIndex) return 0 fun IntProgression.countWhile( getter: (Int)->Char ): Int { var counter = 0 for (i in this) if (getter(i)<height) counter++ else { counter++; break } return counter } val right = (c + 1..this[l].lastIndex).countWhile { this[l][it] } val left = (c - 1 downTo 0).countWhile { this[l][it] } val down = (l + 1..lastIndex).countWhile { this[it][c] } val up = (l - 1 downTo 0).countWhile { this[it][c] } return right * left * down * up } private fun part2(grid: List<String>) = grid.mapEachCharIndexed { row, col, tree -> grid.scenicScore(row,col,tree) }.max() fun main() { val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) // 1820 println(part2(input)) // 385112 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
1,930
aoc2022
Apache License 2.0
src/Day08.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
fun main() { fun forest(input: List<String>) = input.map { r -> r.map { it.digitToInt() } } fun trees(forest: List<List<Int>>) = forest.flatMapIndexed { y, r -> r.mapIndexed { x, h -> Triple(x, y, h) } } // the 4 top-level sequences the 4 directions we can travel (left, right, up, down), the inner sequence is the // height of each tree in that direction from the current point to the edge fun lineOfSight(forest: List<List<Int>>, x: Int, y: Int) = listOf( listOf((x - 1 downTo 0), (x + 1 until forest[y].size)).map { it.map { x -> x to y } }, listOf((y - 1 downTo 0), (y + 1 until forest.size)).map { it.map { y -> x to y } } ).flatten().map { it.map { (x, y) -> forest[y][x] } } fun viewingDistance(los: List<Int>, height: Int) = los.indexOfFirst { it >= height }.let { if (it == -1) los.size else it + 1 // -1 means we hit the edge, otherwise add 1 to index for the distance } fun part1(input: List<String>): Int { val forest = forest(input) return trees(forest).count { (x, y, h) -> lineOfSight(forest, x, y).any { it.all { th -> th < h } } } } fun part2(input: List<String>): Int { val forest = forest(input) return trees(forest).maxOf { (x, y, h) -> lineOfSight(forest, x, y).map { viewingDistance(it, h)}.reduce(Int::times) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
1,659
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-05.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import kotlin.math.max import kotlin.math.min fun main() { val input1 = readInputText(2023, "05-input") val test1 = readInputText(2023, "05-test1") println("Part1:") part1(test1).println() part1(input1).println() println() println("Part2:") part2(test1).println() part2(input1).println() } private fun part1(input: String): Long { val blocks = input.split("\n\n") val seeds = blocks[0].substring("seeds: ".length).split(" ").map { it.toLong() } val maps = blocks.drop(1).map { it.parseMapping() } val locations = seeds.map { seed -> maps.fold(seed) { acc: Long, mappings: List<Mapping> -> transform(acc, mappings) } } return locations.min() } private fun part2(input: String): Long { val blocks = input.split("\n\n") val seedsRanges = blocks[0].substring("seeds: ".length).split(" ").chunked(2).map { val start = it[0].toLong() val length = it[1].toLong() start..< start + length } val maps = blocks.drop(1).map { it.parseMapping() } val ranges = maps.fold(seedsRanges) { ranges, mappings -> ranges.flatMap { transform(it, mappings) }.sortedBy { it.first }.consolidate() } return ranges.minOf { it.first } } private fun String.parseMapping() = lines() .drop(1) .map { val values = it.split(" ").map(String::toLong) Mapping(values[0], values[1]..<values[1] + values[2]) } .sortedBy { it.sourceRange.first } private fun transform(value: Long, mappings: List<Mapping>): Long { val mapping = mappings.find { value in it.sourceRange } ?: return value return mapping.destination + value - mapping.sourceRange.first } private fun transform(range: LongRange, mappings: List<Mapping>): List<LongRange> = buildList { var mapIndex = mappings.indexOfFirst { !it.sourceRange.intersect(range).isEmpty() } if (mapIndex == -1) { this += range return@buildList } var pos = range.first while (mapIndex < mappings.size && pos <= range.last) { val intersect = (pos ..range.last).intersect(mappings[mapIndex].sourceRange) if (!intersect.isEmpty()) { if (pos < intersect.first) { this += pos ..< intersect.first } val diff = mappings[mapIndex].destination - mappings[mapIndex].sourceRange.first this += intersect.first + diff .. intersect.last + diff pos = intersect.last + 1 mapIndex++ } else { this += pos ..range.last pos = range.last + 1 } } } private fun LongRange.intersect(other: LongRange) = max(first, other.first) .. min(last, other.last) private fun List<LongRange>.consolidate() = buildList<LongRange> { [email protected] { range -> val prev = lastOrNull() this += if (prev == null || prev.last + 1 != range.first) { range } else { removeLast() prev.first..range.last } } } private data class Mapping(val destination: Long, val sourceRange: LongRange)
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,252
advent-of-code
MIT License
src/year2021/day13/Day13.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2021.day01.day13 import util.assertTrue import util.model.Counter import util.read2021DayInput import java.awt.Point fun main() { fun task1(input: List<String>): Int { val foldInstructions = input.filter { it.contains("fold along") } val board = foldRecursively(Cave(input).board, foldInstructions, Counter(), 1) return board.sumOf { it.count { it == "#" } } } fun task2(input: List<String>): Int { val foldInstructions = input.filter { it.contains("fold along") } val board = foldRecursively(Cave(input).board, foldInstructions, Counter(), foldInstructions.size) board.forEach { println(it) } return board.sumOf { it.count { it == "#" } } } val input = read2021DayInput("Day13") assertTrue(task1(input) == 720) assertTrue(task2(input) == 104) } class Cave(val input: List<String>) { private val points = input.filter { it.contains(",") }.map { it.split(",") }.map { Point(it[0].toInt(), it[1].toInt()) } val board = MutableList(points.maxByOrNull { it.y }!!.y + 1) { MutableList(points.maxByOrNull { it.x }!!.x + 1) { "." } } init { points.forEach { board[it.y][it.x] = "#" } } } fun combineBoards(boards: Pair<List<List<String>>, List<List<String>>>): List<List<String>> { val combinedList = mutableListOf<MutableList<String>>() combinedList.addAll(boards.first.toMutableList().map { it.toMutableList() }) for (y in boards.second.indices) { for (x in boards.second[y].indices) { if (boards.second[y][x] == "#") combinedList[y][x] = "#" } } return combinedList } fun foldRecursively( board: List<List<String>>, foldInstructions: List<String>, counter: Counter, foldLimit: Int ): List<List<String>> { if (foldInstructions.isEmpty() || counter.i > foldLimit - 1) return board val newFoldInstructions = foldInstructions.takeLast(foldInstructions.size - 1) counter.i++ return foldRecursively(fold(board, foldInstructions.first()), newFoldInstructions, counter, foldLimit) } fun fold(board: List<List<String>>, foldInstruction: String): List<List<String>> { val foldLine = foldInstruction.split("=")[1].toInt() return if (foldInstruction.contains("y")) foldY(board, foldLine) else foldX(board, foldLine) } fun foldY(board: List<List<String>>, foldLine: Int): List<List<String>> { return combineBoards(Pair(board.take(foldLine), board.takeLast(foldLine).reversed())) } fun foldX(board: List<List<String>>, foldLine: Int): List<List<String>> { return combineBoards(Pair(board.map { it.take(foldLine) }, board.map { it.takeLast(foldLine).reversed() })) } fun filterFold(input: List<String>, searchString: String): Int { return input.first { it.contains(searchString) }.split("=")[1].toInt() }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
2,887
advent-of-code-kotlin-template
Apache License 2.0
src/Day15.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
import kotlin.math.abs import kotlin.math.max fun main() { fun manhattanDistance(a: Pair<Long, Long>, b: Pair<Long, Long>): Long { return abs(a.first - b.first) + abs(a.second - b.second) } class Station(val pos: Pair<Long, Long>, val closestRadio: Pair<Long, Long>) { val distance = manhattanDistance(this.pos, this.closestRadio) } fun parseInput(input: List<String>): List<Station> { val regex = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") return input.map { line -> val (x0, y0, x1, y1) = regex.matchEntire(line)!!.destructured Station(Pair(x0.toLong(), y0.toLong()), Pair(x1.toLong(), y1.toLong())) }.sortedBy { it.pos.first } } fun coveredInLine(stations: List<Station>, y: Long): List<LongProgression> { var covered = mutableListOf<LongProgression>() stations .forEach { station -> val closestDistanceToLine = manhattanDistance(station.pos, Pair(station.pos.first, y)) val distanceToClosestRadio = station.distance if (closestDistanceToLine > distanceToClosestRadio) { return@forEach } val radius = abs(closestDistanceToLine - station.distance) covered.add(station.pos.first - radius..station.pos.first + radius) } covered = covered.sortedBy { it.first }.toMutableList() var i = 0 while (i < covered.size - 1) { if (covered[i].last >= covered[i + 1].first) { covered[i] = covered[i].first..max(covered[i].last, covered[i + 1].last) covered.removeAt(i + 1) } else { i++ } } return covered.toList() } fun part1(input: List<String>, targetY: Long): Long { val stations = parseInput(input) val covered = coveredInLine(stations, targetY) val containsRadioCnt = stations .map { it.closestRadio.second } .distinct() .filter { it == targetY } .size return covered.sumOf { it.count().toLong() } - containsRadioCnt } fun part2(input: List<String>, size: Long): Long { val stations = parseInput(input) val blocked = stations.map(Station::closestRadio).toSet() for (y in 0..size) { val covered = coveredInLine(stations, y) .filter { it.last >= 0 && it.first <= size } for ((a, b) in covered.windowed(2)) { for (x in a.last + 1 until b.first) { if (Pair(x, y) !in blocked) { return x * 4000000 + y } } } } throw Exception("No solution found") } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26L) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
3,089
aoc-2022
Apache License 2.0
src/year2023/day25/Day25.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day25 import check import readInput import util.aStar fun main() { val testInput = readInput("2023", "Day25_test") check(part1(testInput), 54) val input = readInput("2023", "Day25") part1(input) } private fun part1(input: List<String>): Int { val graph = input.parseGraph() val vertices = graph.distinctVertices() fun String.getNeighboursWithCostIgnoring(ignore: Set<Pair<String, String>>) = graph.getValue(this) .filter { it to this !in ignore && this to it !in ignore } .mapTo(mutableSetOf()) { it to 1 } fun Pair<String, String>.findPathAroundIgnoring(ignore: Set<Pair<String, String>>) = aStar( from = first, goal = { it == second }, neighboursWithCost = { getNeighboursWithCostIgnoring(ignore) }, )?.path() for (vertexA in vertices) { val ignoreA = setOf(vertexA) val verticesOnPathA = vertexA.findPathAroundIgnoring(ignoreA)?.zipWithNext() ?: continue for (vertexB in verticesOnPathA) { val ignoreAB = setOf(vertexA, vertexB) val verticesOnPathB = vertexB.findPathAroundIgnoring(ignoreAB)?.zipWithNext() ?: continue for (vertexC in verticesOnPathB) { val ignoreABC = setOf(vertexA, vertexB, vertexC) val foundPath = vertexC.findPathAroundIgnoring(ignoreABC) != null if (!foundPath) { val part1 = graph.fill(vertexA.first, ignoreABC) val part2 = graph.fill(vertexA.second, ignoreABC) if (part1.intersect(part2).isEmpty() && (part1 + part2) == graph.keys) { println("${part1.size} * ${part2.size} = ${part1.size * part2.size}") return part1.size * part2.size } } } } } error("unable to find solution") } private fun List<String>.parseGraph(): Map<String, Set<String>> { val vertices = flatMap { line -> val nodes = line.split(": ", " ") val from = nodes.first() val destinations = nodes.drop(1) destinations.map { from to it } } val graph = mutableMapOf<String, MutableSet<String>>() for (vertex in vertices) { graph.getOrPut(vertex.first) { mutableSetOf() } += vertex.second graph.getOrPut(vertex.second) { mutableSetOf() } += vertex.first } return graph } private fun Map<String, Set<String>>.distinctVertices(): List<Pair<String, String>> { val vertices = mutableSetOf<Pair<String, String>>() forEach { (from, destinations) -> destinations.forEach { to -> vertices += from to to } } return vertices.distinctBy { setOf(it.first, it.second) } } private fun Map<String, Set<String>>.fill(from: String, ignoring: Set<Pair<String, String>>): Set<String> { val visited = mutableSetOf(from) val stack = ArrayDeque<String>() stack += from while (stack.isNotEmpty()) { val current = stack.removeFirst() val adjacent = getValue(current) .filter { current to it !in ignoring && it to current !in ignoring && it !in visited } visited += adjacent stack += adjacent } return visited }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,249
AdventOfCode
Apache License 2.0
2015/15/kotlin/a.kt
shrivatsas
583,681,989
false
{"Kotlin": 17998, "Python": 9402, "Racket": 4669, "Clojure": 2953}
import java.io.File import kotlin.math.max data class Ingredient(val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int) fun main() { val lines: List<String> = File("../15.input").useLines { it.toList() } // Sugar: capacity 3, durability 0, flavor 0, texture -3, calories 2 val regex = Regex("""(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""") val ingredients = lines.map { line -> val (name, capacity, durability, flavor, texture, calories) = regex.matchEntire(line)!!.destructured Ingredient(name, capacity.toInt(), durability.toInt(), flavor.toInt(), texture.toInt(), calories.toInt()) } var max_score = 0 for (i in 0..100) { for (j in 0..100 - i) { for (k in 0..100 - i - j) { val l = 100 - i - j - k max_score = max(mapCalculateScore(ingredients, listOf(i, j, k, l)), max_score) // max_score = max(itCalculateScore(ingredients, i, j, k, l), max_score) } } } println(max_score) } // a solution that uses a loop to make it more fun itCalculateScore(ingredients: List<Ingredient>, i: Int, j: Int, k: Int, l: Int): Int { val capacity = i * ingredients[0].capacity + j * ingredients[1].capacity + k * ingredients[2].capacity + l * ingredients[3].capacity val durability = i * ingredients[0].durability + j * ingredients[1].durability + k * ingredients[2].durability + l * ingredients[3].durability val flavor = i * ingredients[0].flavor + j * ingredients[1].flavor + k * ingredients[2].flavor + l * ingredients[3].flavor val texture = i * ingredients[0].texture + j * ingredients[1].texture + k * ingredients[2].texture + l * ingredients[3].texture if (capacity > 0 && durability > 0 && flavor > 0 && texture > 0) { return capacity * durability * flavor * texture } return 0 } // an alternative solution that uses a more functional style fun mapCalculateScore(ingredients: List<Ingredient>, amounts: List<Int>): Int { val capacity = amounts.zip(ingredients).map { (amount, ingredient) -> amount * ingredient.capacity }.sum() val durability = amounts.zip(ingredients).map { (amount, ingredient) -> amount * ingredient.durability }.sum() val flavor = amounts.zip(ingredients).map { (amount, ingredient) -> amount * ingredient.flavor }.sum() val texture = amounts.zip(ingredients).map { (amount, ingredient) -> amount * ingredient.texture }.sum() return max(0, capacity) * max(0, durability) * max(0, flavor) * max(0, texture) }
0
Kotlin
0
1
529a72ff55f1d90af97f8e83b6c93a05afccb44c
2,538
AoC
MIT License
src/Day15.kt
buczebar
572,864,830
false
{"Kotlin": 39213}
import kotlin.math.abs private fun parseInput(name: String) = readInput(name).map { line -> line.split(":").map { it.getAllInts().pair() } }.map { (sensorXY, beaconXY) -> Sensor(sensorXY, beaconXY) } fun main() { fun Position.tuningFrequency() = 4000000L * x + y fun coverageRangesForY(y: Int, sensors: List<Sensor>, valueRange: IntRange): List<IntRange> { val ranges = mutableListOf<IntRange>() sensors.forEach { sensor -> val distanceToY = abs(sensor.y - y) val radiusForY = (sensor.distanceToClosestBeacon - distanceToY).coerceAtLeast(0) if (radiusForY > 0) { ranges.add(((sensor.x - radiusForY)..(sensor.x + radiusForY)).limitValuesInRange(valueRange)) } } return ranges } fun part1(sensors: List<Sensor>, y: Int): Int { val xPositionsWithSensorsOrBeacons = sensors .flatMap { listOf(it.position, it.closestBeacon) } .filter { it.y == y } .map { it.x } .toSet() val valueRange = sensors.map { it.closestBeacon.x }.valueRange() val xPositionsWithoutBeacon = coverageRangesForY(y, sensors, valueRange) .flatMap { it.toList() } .toSet() .minus(xPositionsWithSensorsOrBeacons) return xPositionsWithoutBeacon.size } fun part2(sensors: List<Sensor>, valueRange: IntRange): Long { valueRange.forEach { y -> val coverageRanges = coverageRangesForY(y, sensors, valueRange).sortedBy { it.first } var rightBoundary = coverageRanges.first().last for (i in 1 until coverageRanges.size) { val range = coverageRanges[i] if (rightBoundary < range.first) { return Position(rightBoundary + 1, y).tuningFrequency() } rightBoundary = range.last.coerceAtLeast(rightBoundary) } } return 0L } val testInput = parseInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 0..20) == 56000011L) val input = parseInput("Day15") println(part1(input, 2000000)) println(part2(input, 0..4000000)) } private data class Sensor(val position: Position, val closestBeacon: Position) { val x: Int get() = position.x val y: Int get() = position.y val distanceToClosestBeacon: Int get() = position.manhattanDistanceTo(closestBeacon) }
0
Kotlin
0
0
cdb6fe3996ab8216e7a005e766490a2181cd4101
2,504
advent-of-code
Apache License 2.0
src/Day03.kt
AlexeyVD
575,495,640
false
{"Kotlin": 11056}
fun main() { fun part1(input: List<String>): Int { return input.sumOf { getPrioritiesSum(it) } } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { getBadgeItemPriority(it) } } initPriorities() val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } val priorities: HashMap<String, Int> = HashMap() private fun initPriorities() { var current = 'a' var priority = 1 while (current <= 'z') { priorities[current.toString()] = priority priorities[current.uppercase()] = priority + 26 current++ priority++ } } private fun getPriority(value: Char): Int { return priorities[value.toString()] ?: 0 } fun getPrioritiesSum(value: String): Int { if (value.isBlank()) return 0 val res = HashMap<Char, Int>() val mid = value.length / 2 var num = 0 value.toCharArray().forEach { when { num < mid -> res[it] = 1 else -> if (res.contains(it)) res[it] = 2 } num++ } return res.sumByPriority { it == 2 } } fun getBadgeItemPriority(values: List<String>): Int { val res = HashMap<Char, Int>() values.map { it.toCharArray().toSet() } .forEach { chars -> chars.forEach { res[it] = (res[it] ?: 0) + 1 } } return res.sumByPriority { it == values.size } } fun Map<Char, Int>.sumByPriority(valuesPredicate: (Int) -> Boolean): Int { return filterValues { valuesPredicate.invoke(it) }.keys.sumOf { getPriority(it) } }
0
Kotlin
0
0
ec217d9771baaef76fa75c4ce7cbb67c728014c0
1,704
advent-kotlin
Apache License 2.0
src/Day08.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
fun main() { fun part1(input: List<String>): Int { val forestHeights = input.map { it.map { tree -> tree.digitToInt() } } return forestHeights.withIndex().drop(1).dropLast(1).sumOf { (row, rowTreesHeights) -> rowTreesHeights.withIndex().drop(1).dropLast(1).count { (column, treeHeight) -> val columnTreesHeights = forestHeights.map { it[column] } listOf( rowTreesHeights.take(column), rowTreesHeights.drop(column + 1), columnTreesHeights.take(row), columnTreesHeights.drop(row + 1), ).any { treeHeights -> treeHeights.all { it < treeHeight } } } } + ((forestHeights.size + forestHeights.size - 2) * 2) } fun part2(input: List<String>): Int { val forrestHeights = input.map { it.map { tree -> tree.digitToInt() } } return forrestHeights.withIndex().drop(1).dropLast(1).maxOf { (row, rowTreesHeights) -> rowTreesHeights.withIndex().drop(1).dropLast(1).maxOf { (column, treeHeight) -> val columnTreesHeights = forrestHeights.map { it[column] } listOf( rowTreesHeights.take(column).reversed(), rowTreesHeights.drop(column + 1), columnTreesHeights.take(row).reversed(), columnTreesHeights.drop(row + 1), ).map { treeHeights -> treeHeights .takeWhile { it < treeHeight } .size .let { if (it < treeHeights.size) it + 1 else it } }.reduce(Int::times) } } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readLines("Day08") check(part1(input) == 1825) println(part1(input)) check(part2(input) == 235200) println(part2(input)) }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
2,067
advent-of-code-kotlin-2022
Apache License 2.0
src/day08/Day08.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day08 import readInput import readTestInput private data class Tree( val x: Int, val y: Int, val height: Int, ) private fun List<String>.parse(): List<List<Tree>> { return this.mapIndexed { y, row -> row.mapIndexed { x, cell -> Tree(x = x, y = y, height = cell.digitToInt()) } } } private fun List<Tree>.filterIsVisible(): List<Tree> { var maxHeight = -1 return this.filter { tree -> if (tree.height > maxHeight) { maxHeight = tree.height true } else false } } private fun List<Tree>.countVisibleFrom(baseTree: Tree): Int = (indexOfFirst { tree -> tree.height >= baseTree.height }.takeUnless { it < 0 } ?: lastIndex) + 1 private fun part1(input: List<String>): Int { val treeRows = input.parse() val treeColumns = List(treeRows.size) { column -> treeRows[column].indices.map { row -> treeRows[row][column] } } val visibleRowTrees = treeRows.flatMap { treeRow -> treeRow.filterIsVisible() + treeRow.asReversed().filterIsVisible() } val visibleColumnTrees = treeColumns.flatMap { column -> column.filterIsVisible() + column.asReversed().filterIsVisible() } val visibleTrees = (visibleRowTrees + visibleColumnTrees).toSet() return visibleTrees.size } private fun part2(input: List<String>): Int { val treeRows = input.parse() val treeColumns = List(treeRows.size) { column -> treeRows[column].indices.map { row -> treeRows[row][column] } } val highestScenicScore = treeRows.indices.maxOf { x -> treeColumns.indices.maxOf { y -> val baseTree = treeColumns[x][y] val treesToTheLeft = treeRows[y].take(x).asReversed() val treesToTheRight = treeRows[y].drop(x + 1) val treesAbove = treeColumns[x].take(y).asReversed() val treesBelow = treeColumns[x].drop(y + 1) val viewLeft = treesToTheLeft.countVisibleFrom(baseTree) val viewRight = treesToTheRight.countVisibleFrom(baseTree) val viewAbove = treesAbove.countVisibleFrom(baseTree) val viewBelow = treesBelow.countVisibleFrom(baseTree) viewLeft * viewRight * viewAbove * viewBelow } } return highestScenicScore } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day08") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
2,632
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
iProdigy
572,297,795
false
{"Kotlin": 33616}
fun main() { fun part1(input: List<String>): Int { val (start, end, map) = parse(input) return findShortest(start, end, map, heuristic = Point2D::manhattanDist)!!.size - 1 } fun part2(input: List<String>): Int { val grid = input.map { it.toCharArray() }.toTypedArray() val end = grid.map { it.indexOf('E') }.withIndex().first { it.value >= 0 }.let { it.index to it.value } return breadthFirstSearch(end, { normalize(grid[it.first][it.second]) == 'a' }) { it.neighbors(maxX = grid.size, maxY = grid[0].size) .filter { from -> isConnected(from, it, grid) } }!!.size - 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) // 394 println(part2(input)) // 388 } private fun parse(input: List<String>): Triple<Point2D, Point2D, Map<Point2D, Collection<Point2D>>> { val grid: Array<CharArray> = input.map { it.toCharArray() }.toTypedArray() val map: MutableMap<Point2D, Collection<Point2D>> = hashMapOf() var start: Point2D? = null var end: Point2D? = null for (i in grid.indices) { val row = grid[i] for (j in row.indices) { val value = row[j] val max = normalize(value) + 1 val point = i to j if (start == null && value == 'S') { start = point } else if (end == null && value == 'E') { end = point } val candidates = point.neighbors(maxX = grid.size, maxY = row.size).filter { isConnected(point, it, grid, max) } map[point] = candidates } } return Triple(start!!, end!!, map) } private fun isConnected(from: Point2D, to: Point2D, grid: Array<CharArray>, max: Char = normalize(grid[from.first][from.second]) + 1) = normalize(grid[to.first][to.second]) <= max private fun normalize(it: Char) = if (it == 'S') 'a' else if (it == 'E') 'z' else it
0
Kotlin
0
1
784fc926735fc01f4cf18d2ec105956c50a0d663
2,125
advent-of-code-2022
Apache License 2.0
src/main/kotlin/y2023/Day7.kt
juschmitt
725,529,913
false
{"Kotlin": 18866}
package y2023 import utils.Day class Day7 : Day(7, 2023, false) { override fun partOne(): Any { return inputList .map { val (hand, bid) = it.split(" ") hand to bid }.sortedWith(RegularCardComparator()) .mapIndexed { index, (_, bid) -> (index + 1) * bid.toInt() } .sum() } override fun partTwo(): Any { return inputList .map { val (hand, bid) = it.split(" ") hand to bid }.sortedWith(JokerRuleCardComparator()) .mapIndexed { index, (_, bid) -> (index + 1) * bid.toInt() } .sum() } } private class JokerRuleCardComparator : CardComparator() { override fun Map<Char, Int>.mapOccurrencesToStrength(): Int { val j = getOrDefault('J', 0) if (j == 5) return 6 val max = filterNot { it.key == 'J' }.values.max() val min = filterNot { it.key == 'J' }.values.min() val count = values.count { it == 2 } return when { max + j == 5 -> 6 max + j == 4 -> 5 max + j == 3 && min == 2 -> 4 max == 3 && min + j == 2 -> 4 max + j == 3 -> 3 max + j == 2 && count == 2 -> 2 max == 2 && count + j == 2 -> 2 max + j == 2 -> 1 max + j == 1 -> 0 else -> -1 } } override fun Char.cardToValue(): Int = when { this == 'A' -> 14 this == 'K' -> 13 this == 'Q' -> 12 this == 'J' -> 0 this == 'T' -> 10 isDigit() -> digitToInt() else -> -1 } } private class RegularCardComparator : CardComparator() { override fun Map<Char, Int>.mapOccurrencesToStrength(): Int = when { values.max() == 5 -> 6 values.max() == 4 -> 5 values.max() == 3 && values.min() == 2 -> 4 values.max() == 3 -> 3 values.max() == 2 && values.count { it == 2 } == 2 -> 2 values.max() == 2 -> 1 values.max() == 1 -> 0 else -> -1 } override fun Char.cardToValue(): Int = when { this == 'A' -> 14 this == 'K' -> 13 this == 'Q' -> 12 this == 'J' -> 11 this == 'T' -> 10 isDigit() -> digitToInt() else -> -1 } } private abstract class CardComparator : Comparator<Pair<String, String>> { override fun compare(o1: Pair<String, String>?, o2: Pair<String, String>?): Int { return when { o1 == null -> -1 o2 == null -> 1 else -> compare(o1.first, o2.first) } } private fun compare(o1: String, o2: String): Int { val strengthHand1 = mapCharOccurrences(o1).mapOccurrencesToStrength() val strengthHand2 = mapCharOccurrences(o2).mapOccurrencesToStrength() val strengthByType = strengthHand1 - strengthHand2 if (strengthByType != 0) return strengthByType o1.zip(o2) .forEach { (a, b) -> val comparison = a.cardToValue() - b.cardToValue() if (comparison != 0) return comparison } return 0 } private fun mapCharOccurrences(s: String): Map<Char, Int> = s.fold(mutableMapOf()) { map, char -> map.merge(char, 1, Int::plus) map } abstract fun Map<Char, Int>.mapOccurrencesToStrength(): Int abstract fun Char.cardToValue(): Int }
0
Kotlin
0
0
b1db7b8e9f1037d4c16e6b733145da7ad807b40a
3,440
adventofcode
MIT License
2k23/aoc2k23/src/main/kotlin/22.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d22 import input.read import kotlin.math.max import kotlin.math.min fun main() { println("Part 1: ${part1(read("22.txt"))}") println("Part 2: ${part2(read("22.txt"))}") } fun part1(input: List<String>): Int { val bricks = input.map { Brick(it) }.toMutableList() val (supports, supportedBy) = stabilize(bricks) return bricks.filterIndexed { index, _ -> supports[index]!!.all { supportedBy[it]!!.size > 1 } }.size } fun part2(input: List<String>): Int { val bricks = input.map { Brick(it) }.toMutableList() val (supports, supportedBy) = stabilize(bricks) return bricks.foldIndexed(0) { index, acc, _ -> val queue = ArrayDeque(supports[index]!!.filter { supportedBy[it]!!.size == 1 }) val falling = mutableSetOf<Int>() queue.forEach { falling.add(it) } falling.add(index) while (queue.isNotEmpty()) { val current = queue.removeFirst() supports[current]!!.minus(falling).filter { supportedBy[it]!!.all { element -> element in falling } } .forEach { queue.add(it) falling.add(it) } } acc + falling.size - 1 } } fun stabilize(bricks: MutableList<Brick>): Pair<Map<Int, MutableSet<Int>>, Map<Int, MutableSet<Int>>> { bricks.sortBy { it.start.z } bricks.forEachIndexed { index, brick -> var max = 1 bricks.subList(0, index).forEach { lowerBricks -> if (brick.overlaps(lowerBricks)) { max = max(max, lowerBricks.end.z + 1) } } brick.end.z -= brick.start.z - max brick.start.z = max } bricks.sortBy { it.start.z } val supports = (0..<bricks.size).associateWith { mutableSetOf<Int>() } val supportedBy = (0..<bricks.size).associateWith { mutableSetOf<Int>() } bricks.forEachIndexed { upperIndex, upperBrick -> bricks.forEachIndexed { lowerIndex, lowerBrick -> if (upperBrick.overlaps(lowerBrick) && upperBrick.start.z == lowerBrick.end.z + 1) { supports[lowerIndex]!!.add(upperIndex) supportedBy[upperIndex]!!.add(lowerIndex) } } } return supports to supportedBy } class Brick(input: String) { val start: Point val end: Point init { val (rawStart, rawEnd) = input.split("~") val startCoord = rawStart.split(",").map { it.toInt() } start = Point(startCoord[0], startCoord[1], startCoord[2]) val endCoord = rawEnd.split(",").map { it.toInt() } end = Point(endCoord[0], endCoord[1], endCoord[2]) } fun overlaps(other: Brick): Boolean = max(start.x, other.start.x) <= min(end.x, other.end.x) && max(start.y, other.start.y) <= min(end.y, other.end.y) } data class Point(val x: Int, val y: Int, var z: Int)
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
2,868
aoc
The Unlicense
src/Day15.kt
anisch
573,147,806
false
{"Kotlin": 38951}
import kotlin.math.abs private fun getPositions(input: List<String>) = input .map { line -> val (s, b) = line.split(": ") val (xs, ys) = s.removeRange(0..9).split(",") val (xb, yb) = b.removeRange(0..20).split(",") val vecS = Vec( xs.substringAfter("=").toInt(), ys.substringAfter("=").toInt(), ) val vecB = Vec( xb.substringAfter("=").toInt(), yb.substringAfter("=").toInt(), ) Pair(vecS, vecB) } private fun getRanges(positions: List<Pair<Vec, Vec>>, row: Int): List<IntRange> = positions .mapNotNull { (s, b) -> val distance = abs(s.x - b.x) + abs(s.y - b.y) val yRange = s.y - distance..s.y + distance if (row in yRange) { val yd = abs(s.y - row) val range = (distance - yd) s.x - range..s.x + range } else null } .sortedBy { it.first } fun main() { fun part1(input: List<String>, row: Int): Int { val positions = getPositions(input) val ranges = getRanges(positions, row) .reduce { acc, intRange -> val start = if (intRange.first < acc.first) intRange.first else acc.first val end = if (intRange.last > acc.last) intRange.last else acc.last start..end } val nothing = ranges.count() val beacons = positions .filter { (_, b) -> b.y == row && b.x in ranges } .map { it.second } .toSet() .size return nothing - beacons } fun part2(input: List<String>, rows: Int): Long { val positions = getPositions(input) var vec = Vec(0, 0) for (row in 0..rows) { val ranges = getRanges(positions, row) var col: Int? = null var lastX = ranges.first().last for (idx in 1 until ranges.size) { if (lastX + 1 < ranges[idx].first) { col = lastX + 1 } else { lastX = if (lastX >= ranges[idx].last) lastX else ranges[idx].last } } if (col != null) { vec = Vec(col, row) break } } return vec.x.toLong() * 4_000_000L + vec.y.toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") val input = readInput("Day15") check(part1(testInput, 10) == 26) println(part1(input, 2_000_000)) check(part2(testInput, 20) == 56_000_011L) println(part2(input, 4_000_000)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
2,883
Advent-of-Code-2022
Apache License 2.0
src/day14/Day14.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day14 import println import readInput fun String.parseInput() = readInput(this).let { lines -> Pair( lines[0], lines.slice(2 until lines.size).associate { line -> line.split(" -> ").let { Pair(it[0], it[1]) } } ) } fun Map<String, String>.step(initial: String): String { var formula = initial.take(1) for (i in 1 until initial.length) { val next = initial[i] formula += this["${formula.last()}$next"]!! + next } return formula } fun part1(initial: String, rules: Map<String, String>): Int { val formula = (1..10).fold(initial) { acc, _ -> rules.step(acc) } val counts = formula.groupingBy { it }.eachCount() return counts.values.max() - counts.values.min() } fun part2(initial: String, rules: Map<String, String>): Long { val initialPairs = rules.mapValues { e -> initial.windowed(2).filter { it == e.key }.size.toLong() } val pairsAfterSteps = (1..40).fold(initialPairs) { pairs, _ -> pairs.entries.fold(mutableMapOf()) { transformed, it -> val inserted = rules[it.key]!! transformed.compute(it.key.first() + inserted) { _, value -> (value ?: 0) + it.value } transformed.compute(inserted + it.key.last()) { _, value -> (value ?: 0) + it.value } transformed } } val counts = pairsAfterSteps.entries.flatMap { e -> listOf(Pair(e.key.first(), e.value), Pair(e.key.last(), e.value)) } .groupingBy { it.first }.aggregate { _, acc: Long?, element, _ -> (acc ?: 0) + element.second } .mapValues { if (it.key == initial.first() || it.key == initial.last()) it.value + 1 else it.value } .mapValues { it.value / 2 } return counts.values.max() - counts.values.min() } fun main() { val testInput = "day14/input_test".parseInput() check(part1(testInput.first, testInput.second) == 1588) check(part2(testInput.first, testInput.second) == 2188189693529L) val input = "day14/input".parseInput() part1(input.first, input.second).println() part2(input.first, input.second).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
2,127
advent-of-code-2021
Apache License 2.0
src/day08/Day08.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day08 import utils.* data class Tree(val height: Int, var score: Int = 0) fun readMap(input: List<String>): List<List<Tree>> = input.map { line -> line.map { c -> Tree(c.digitToInt()) } } fun <T> getClockwiseRotation(mtx: List<List<T>>): List<List<T>> = mtx[0].indices.map { x -> mtx.indices.map { y -> mtx[mtx.lastIndex - y][x] } } fun setTreeVisibilityScores(map: List<List<Tree>>) { val rotations = (0..2).scan(map) { mtx, _ -> getClockwiseRotation(mtx) } rotations.forEach { rows -> rows.forEach { row -> row.fold(-1) { max, tree -> if (tree.height > max) tree.score++ maxOf(max, tree.height) } } } } fun part1(input: List<String>): Int = readMap(input) .also { setTreeVisibilityScores(it) } .flatten() .count { tree -> tree.score > 0 } fun getTreeScenicScore(map: List<List<Tree>>, x: Int, y: Int): Int { val currentHeight = map[y][x].height val directions = listOf( (x + 1..map[0].lastIndex).map { map[y][it].height }, (x - 1 downTo 0).map { map[y][it].height }, (y + 1..map.lastIndex).map { map[it][x].height }, (y - 1 downTo 0).map { map[it][x].height } ) return directions .map { dir -> (dir.indexOfFirst { it >= currentHeight } + 1) .takeIf { it != 0 } ?: dir.size } .reduce(Int::times) } fun setTreeScenicScores(map: List<List<Tree>>) = map.forEachIndexed { y, row -> row.forEachIndexed { x, tree -> tree.score = getTreeScenicScore(map, x, y) } } fun part2(input: List<String>): Int = readMap(input) .also { setTreeScenicScores(it) } .flatten() .maxOf { it.score } fun main() { val testInput = readInput("Day08_test") expect(part1(testInput), 21) expect(part2(testInput), 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
2,093
AOC-2022-Kotlin
Apache License 2.0
src/day15/d15_1.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val ingredients = input.lines().map { parseIngredient(it) }.associateBy { it.name } println(forAllCombinations(ingredients, 100) { it.map { (k, v) -> listOf( ingredients[k]!!.capacity * v, ingredients[k]!!.durability * v, ingredients[k]!!.flavor * v, ingredients[k]!!.texture * v) }.fold(listOf(0, 0, 0, 0)) { acc, list -> acc.zip(list) { a, b -> a + b } } .map { if (it < 0) 0 else it } .reduce(Int::times) }.max()) } data class Ingredient(val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int) fun parseIngredient(s: String): Ingredient = s.split(" ").let { Ingredient(it[0].dropLast(1), it[2].dropLast(1).toInt(), it[4].dropLast(1).toInt(), it[6].dropLast(1).toInt(), it[8].dropLast(1).toInt()) } fun <T> forAllCombinations(ingredients: Map<String, Ingredient>, n: Int, f: (Map<String, Int>) -> T): Sequence<T> { val names = ingredients.keys.toList() val arr = Array(names.size) { 0 } return forAllCombinationsRec(0, n, 0, arr, names, f) } fun <T> forAllCombinationsRec(step: Int, stepCount: Int, currIdx: Int, arr: Array<Int>, names: List<String>, f: (Map<String, Int>) -> T): Sequence<T> = sequence { if (step == stepCount) { yield(f(arr.mapIndexed {i, cnt -> names[i] to cnt }.toMap())) } else { if (currIdx < arr.size - 1) { arr[currIdx + 1]++ yieldAll(forAllCombinationsRec(step + 1, stepCount, currIdx + 1, arr, names, f)) arr[currIdx + 1]-- } arr[currIdx]++ yieldAll(forAllCombinationsRec(step + 1, stepCount, currIdx, arr, names, f)) arr[currIdx]-- } }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,836
aoc2015
MIT License
src/Day15.kt
fercarcedo
573,142,185
false
{"Kotlin": 60181}
import kotlin.math.abs private val LINE_REGEX = "Sensor\\s+at\\s+x=(?<sensorX>-?\\d+),\\s+y=(?<sensorY>-?\\d+):\\s+closest\\s+beacon\\s+is\\s+at\\s+x=(?<beaconX>-?\\d+),\\s+y=(?<beaconY>-?\\d+)".toRegex() private const val TUNING_FACTOR_X = 4000000L data class Sensor( val position: Pair<Int, Int>, val closestBeacon: Pair<Int, Int> ) data class Range( val start: Int, val end: Int ) fun main() { fun parseSensors(input: List<String>) = input.map { val matchResult = LINE_REGEX.matchEntire(it)!! Sensor( matchResult.groups["sensorX"]!!.value.toInt() to matchResult.groups["sensorY"]!!.value.toInt(), matchResult.groups["beaconX"]!!.value.toInt() to matchResult.groups["beaconY"]!!.value.toInt() ) } fun combineRanges(ranges: Set<Range>): Set<Range> { if (ranges.isEmpty() || ranges.size == 1) { return ranges } val sortedRanges = ranges.sortedBy { it.start } var currentStart = sortedRanges[0].start var currentEnd = sortedRanges[0].end val result = mutableSetOf<Range>() for (i in 1 until sortedRanges.size) { val range = sortedRanges[i] if (range.start <= currentEnd + 1) { if (range.end > currentEnd) { currentEnd = range.end } } else { result.add(Range(currentStart, currentEnd)) currentStart = range.start currentEnd = range.end } } result.add(Range(currentStart, currentEnd)) return result } fun manhattanDistance(first: Pair<Int, Int>, second: Pair<Int, Int>): Int = abs(first.first - second.first) + abs(first.second - second.second) fun getCoverageRanges(y: Int, sensors: List<Sensor>, maxPos: Int? = null): Set<Range> { val ranges = mutableSetOf<Range>() for (sensor in sensors) { val distance = manhattanDistance(sensor.position, sensor.closestBeacon) val leftPoint = sensor.position.first - distance to sensor.position.second val rightPoint = sensor.position.first + distance to sensor.position.second val topPoint = sensor.position.first to sensor.position.second - distance val bottomPoint = sensor.position.first to sensor.position.second + distance if ((y >= topPoint.second && y <= sensor.position.second) || (y >= sensor.position.second && y <= bottomPoint.second)) { val difference = abs(sensor.position.second - y) maxPos?.let { ranges.add(Range(maxOf(leftPoint.first + difference, 0), minOf(rightPoint.first - difference, it))) } ?: ranges.add(Range(leftPoint.first + difference, rightPoint.first - difference)) } } return combineRanges(ranges) } fun part1(input: List<String>, y: Int): Int { val sensors = parseSensors(input) val combinedRanges = getCoverageRanges(y, sensors) val sensorsAndBeaconsInY = sensors.flatMap { listOf(it.position, it.closestBeacon) } .filter { it.second == y } val sumRangesSize = combinedRanges.sumOf { it.end - it.start + 1 } val numSensorsAndBeaconsInRanges = combinedRanges.count { range -> sensorsAndBeaconsInY.any { point -> point.first >= range.start && point.first <= range.end } } return sumRangesSize - numSensorsAndBeaconsInRanges } fun part2(input: List<String>, maxPos: Int): Long { val sensors = parseSensors(input) for (y in 0..maxPos) { val combinedRanges = getCoverageRanges(y, sensors, maxPos) if (combinedRanges.size > 1) { val rangeX = combinedRanges.windowed(2).first { it[1].start > it[0].end + 1 }[0].end + 1 return rangeX * TUNING_FACTOR_X + y } } return -1L } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) // 5838453 println(part2(input, 4000000)) // 12413999391794 }
0
Kotlin
0
0
e34bc66389cd8f261ef4f1e2b7f7b664fa13f778
4,269
Advent-of-Code-2022-Kotlin
Apache License 2.0
src/main/kotlin/Day8.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
fun puzzleDayEightPartOne() { val inputs = readInput(8) val structured = structureInputs(inputs) val count = structured.countOneFourSevenEight() println("Count of 1,4,7,8 -> $count") } fun puzzleDayEightPartTwo() { val inputs = readInput(8) val structured = structureInputs(inputs) val sum = structured.sumOf { pairsList -> val codes = decode(pairsList.first) pairsList.second.map { codes[it.toSet()] ?: throw IllegalArgumentException("Could not find: $it in decoded set. ") }.joinToString(separator = "").toInt() } println("Sum of all outputs -> $sum") } fun List<Pair<List<String>, List<String>>>.countOneFourSevenEight() = flatMap { it.second }.count { ONE_FOUR_SEVEN_EIGHT_LENGTHS.contains(it.length) } fun structureInputs(inputs: List<String>): List<Pair<List<String>, List<String>>> = inputs.map { input -> val split = input.split(" | ") split[0].trim().split(" ") to split[1].trim().split(" ") } fun decode(codes: List<String>): Map<Set<Char>, Int> { val sortedSets = codes.sortedBy { it.length }.map { it.toSet() } val codeOne = sortedSets[0] val codeSeven = sortedSets[1] val codeFour = sortedSets[2] val codeEight = sortedSets.last() val charsByCount = sortedSets.joinToString().toList().groupingBy { it }.eachCount() val segmentF = charsByCount.filter { it.value == 9 }.map { it.key }.first() val codeTwo = sortedSets.first { !it.contains(segmentF) } val segmentC = codeOne.toSet().intersect(codeTwo.toSet()).first() val fiveAndSix = sortedSets.filter { !it.contains(segmentC) }.sortedBy { it.size } val codeFive = fiveAndSix.first() val codeSix = fiveAndSix.last() val segmentE = (codeSix.toSet() - codeFive.toSet()).first() val codeNine = codeEight - segmentE val codeZero = sortedSets.first { it.size == 6 && it != codeNine && it != codeSix } val codeThree = sortedSets.first { it.size == 5 && it != codeTwo && it != codeFive } return mapOf( codeZero.toSet() to 0, codeOne.toSet() to 1, codeTwo.toSet() to 2, codeThree.toSet() to 3, codeFour.toSet() to 4, codeFive.toSet() to 5, codeSix.toSet() to 6, codeSeven.toSet() to 7, codeEight.toSet() to 8, codeNine.toSet() to 9 ) } private val ONE_FOUR_SEVEN_EIGHT_LENGTHS = setOf(2, 3, 4, 7)
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
2,397
advent-of-kotlin-2021
Apache License 2.0
src/Day15.kt
paulgrugnale
573,105,050
false
{"Kotlin": 6378}
import Position.Companion.manhattanDistance import java.lang.Integer.max import java.lang.Integer.min import kotlin.math.abs fun main() { fun positionsWithoutBeaconForRow(input: List<Position>, row: Int): List<IntRange> { val sensorsAffectingRow = input.filter { abs(it.sensorY - row) <= it.manhattanDistance() } val xRanges = sensorsAffectingRow.map { val (xMin, xMax) = funMath(it.sensorX, it.sensorY, row, it.manhattanDistance()) Pair(xMin, xMax) }.sortedBy { it.first } return xRanges.fold(mutableListOf<Pair<Int, Int>>()) { acc, item -> if (acc.isEmpty() || acc.last().second < item.first) { acc.add(item) } else { val last = acc.removeLast() acc.add(Pair(min(item.first, last.first), max(item.second, last.second))) } acc }.map { IntRange(it.first, it.second) } } fun part1(input: List<Position>, row: Int): Int { val sensorsAffectingRow = input.filter { abs(it.sensorY - row) <= it.manhattanDistance() } val rangesWithoutBeacon = positionsWithoutBeaconForRow(input, row) val beaconsInRow = sensorsAffectingRow.filter {it.beaconY == row }.map { it.beaconX }.distinct() .count { beacon -> rangesWithoutBeacon.map { beacon in it }.any { it } } return rangesWithoutBeacon.sumOf { it.count() } - beaconsInRow } fun part2(input: List<Position>, validRange: IntRange): Long { var emptyX = -1 val answerY = validRange.asSequence().find { row -> val rangesWithoutBeacon = positionsWithoutBeaconForRow(input, row) val beaconsInRow = input.filter { it.beaconY == row}.map { it.beaconX } rangesWithoutBeacon.map {range -> if ((range.first - 1) in validRange && (range.first - 1) !in beaconsInRow) { emptyX = range.first - 1 true } else { false } }.any { it } } println("row found at y=$answerY with empty X space at x=$emptyX") return emptyX * 4000000L + answerY!! } // test if implementation meets criteria from the description, like: //val input = readInput("Day15_test") val input = readInput("Day15") val regex = Regex("x=(-?\\d+), y=(-?\\d+)") val coordinates = input.map { val matchResults = regex.findAll(it).toList() Position( matchResults[0].groups[1]!!.value.toInt(), matchResults[0].groups[2]!!.value.toInt(), matchResults[1].groups[1]!!.value.toInt(), matchResults[1].groups[2]!!.value.toInt() ) } println("part 1 solution: ${part1(coordinates, 2000000)}") println("part 2 solution: ${part2(coordinates, 0..4000000)}") // println("part 1 solution: ${part1(coordinates, 10)}") // println("part 2 solution: ${part2(coordinates, 0..20)}") } data class Position( val sensorX: Int, val sensorY: Int, val beaconX: Int, val beaconY: Int ) { companion object { fun Position.manhattanDistance() = getManhattanDistance(sensorX, sensorY, beaconX, beaconY) } } private fun getManhattanDistance(x1:Int, y1: Int, x2: Int, y2: Int) = abs(x1 - x2) + abs(y1 - y2) private fun funMath(sensorX: Int, sensorY: Int, givenY: Int, maxDistance: Int): Pair<Int, Int>{ val yDifference = abs(sensorY - givenY) val rhs = maxDistance - yDifference val xGreaterEqualThan = (rhs - sensorX) * -1 val xLessEqualThan = (-rhs - sensorX) * -1 return xGreaterEqualThan to xLessEqualThan }
0
Kotlin
0
0
e62edc817a8b75e401d6c8a0a66243d009c31fbd
3,733
advent2022
Apache License 2.0
src/y2022/Day08.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.getCol import util.getRow import util.readInput import util.split object Day08 { fun part1(input: List<String>): Int { val heightGrid = input.mapIndexed { rowIdx, row -> row.mapIndexed { colIdx, h -> Tree(h, rowIdx, colIdx) } } return heightGrid .flatten() .count { isVisible(it, heightGrid) } } private fun isVisible(tree: Tree, grid: List<List<Tree>>): Boolean { return isVisible(tree.row, getCol(grid, tree.col)) || isVisible(tree.col, getRow(grid, tree.row)) } private fun isVisible(idx: Int, line: List<Tree>): Boolean { return line.split { it == line[idx] } .map { partLine -> partLine.all { it.height < line[idx].height } } .any { it } } class Tree(height: Char, val row: Int, val col: Int) { val height = height.digitToInt() } fun part2(input: List<String>): Int { val heightGrid = input.mapIndexed { rowIdx, row -> row.mapIndexed { colIdx, h -> Tree(h, rowIdx, colIdx) } } return heightGrid .flatten() .maxOf { scenicScore(it, heightGrid) } } private fun scenicScore(tree: Tree, grid: List<List<Tree>>): Int { return scenicScore(tree.row, getCol(grid, tree.col)) * scenicScore(tree.col, getRow(grid, tree.row)) } private fun scenicScore(idx: Int, line: List<Tree>): Int { val treeHeight = line[idx].height val (before, after) = line.split { it == line[idx] } return viewDistance(before.reversed(), treeHeight) * viewDistance(after, treeHeight) } private fun viewDistance(trees: List<Tree>, treeHeight: Int): Int { val visible = trees.takeWhile { it.height < treeHeight }.count() val extraTree = if (trees.drop(visible).firstOrNull()?.height == treeHeight) 1 else 0 return visible + extraTree } } fun main() { val testInput = """ 30373 25512 65332 33549 35390 """.trimIndent().split("\n") println("all of empty: " + listOf<Boolean>().all { true }) println(Day08.part1(testInput)) val input = readInput("resources/2022/day08") println(Day08.part1(input)) println(Day08.part2(testInput)) println(Day08.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,327
advent-of-code
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day09/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day09 import com.kingsleyadio.adventofcode.util.readInput fun part1(input: List<List<Int>>): Int { var result = 0 for (i in input.indices) { val inner = input[i] for (j in inner.indices) { val current = inner[j] val adjacents = adjacentPoints(i, j, input).map { (y, x) -> input[y][x] } if (adjacents.all { it > current }) result += current + 1 } } return result } fun part2(input: List<List<Int>>): Int { fun expanse(y: Int, x: Int): Int { fun evaluate(y: Int, x: Int, lookup: MutableSet<String>): Int { lookup.add("$y#$x") val value = input[y][x] return 1 + adjacentPoints(y, x, input) .asSequence() .filter { (newY, newX) -> input[newY][newX] in value+1..8 } .filterNot { (newY, newX) -> "$newY#$newX" in lookup } .sumOf { (newY, newX) -> evaluate(newY, newX, lookup) } } return evaluate(y, x, hashSetOf()) } val basins = arrayListOf<Int>() for (i in input.indices) { val inner = input[i] for (j in inner.indices) { val current = inner[j] val adjacents = adjacentPoints(i, j, input).map { (y, x) -> input[y][x] } if (adjacents.all { it > current }) basins.add(expanse(i, j)) } } return basins.sorted().takeLast(3).fold(1) { acc, n -> acc * n } } fun adjacentPoints(y: Int, x: Int, input: List<List<Int>>): List<IntArray> { return buildList { if (y > 0) add(intArrayOf(y - 1, x)) if (x < input[0].lastIndex) add(intArrayOf(y, x + 1)) if (y < input.lastIndex) add(intArrayOf(y + 1, x)) if (x > 0) add(intArrayOf(y, x - 1)) } } fun main() { val input = readInput(2021, 9).useLines { lines -> lines.map { line -> line.toCharArray().map { it.digitToInt() } }.toList() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
2,010
adventofcode
Apache License 2.0
src/Day11.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun List<String>.parseMonkeys() = map { section -> val lines = section.split('\n') val index = lines[0].split(' ')[1].dropLast(1).toInt() val items = lines[1].trim().split(' ').drop(2).map { it.removeSuffix(",").toLong() }.toMutableList() val condition: (Long) -> Long = lines[2].trim().split(' ').takeLast(2).let { (op, value) -> if (op == "*") ({ it * if (value == "old") it else value.toLong() }) else ({ it + if (value == "old") it else value.toLong() }) } val divisibleBy = lines[3].trim().split(' ').last().toLong() val testTrue = lines[4].trim().split(' ').last().toInt() val testFalse = lines[5].trim().split(' ').last().toInt() Monkey(index, items, condition, divisibleBy, testTrue, testFalse) }.sortedBy(Monkey::index) fun List<Monkey>.calculateInspections(rounds: Int, worryReducer: (Long) -> Long): LongArray { val inspections = LongArray(size) { 0 } repeat(rounds) { forEach { monkey -> monkey.items.forEach { item -> val new = worryReducer(monkey.operation(item)) if (new % monkey.divisibleBy == 0L) { this[monkey.testTrue].items.add(new) } else { this[monkey.testFalse].items.add(new) } } inspections[monkey.index] = inspections[monkey.index] + monkey.items.size monkey.items.clear() } } return inspections } fun part1(input: List<String>): Long { return input.parseMonkeys() .calculateInspections(rounds = 20) { it / 3 } .sortedDescending() .take(2) .product() } fun part2(input: List<String>): Long { val monkeys = input.parseMonkeys() val lcm = monkeys.map(Monkey::divisibleBy).lcm() return input.parseMonkeys() .calculateInspections(rounds = 10_000) { it % lcm } .sortedDescending() .take(2) .product() } // test if implementation meets criteria from the description, like: val testInput = readLinesSplitedbyEmptyLine("Day11_test") check(part1(testInput) == 10605L) val input = readLinesSplitedbyEmptyLine("Day11") println(part1(input)) // part 2 check(part2(testInput) == 2713310158) println(part2(input)) } private data class Monkey( val index: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val divisibleBy: Long, val testTrue: Int, val testFalse: Int, )
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
2,721
advent-of-code-2022
Apache License 2.0
src/Day09.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
fun main() { fun parse(input: List<String>) = input.map { it.toCharArray().map { c -> c.toString().toInt() } } fun isLowPoint(map: List<List<Int>>, y: Int, x: Int): Boolean { val value = map[y][x] if (y > 0 && map[y - 1][x] <= value) return false if (y < map.lastIndex && map[y + 1][x] <= value) return false if (x > 0 && map[y][x - 1] <= value) return false if (x < map[y].lastIndex && map[y][x + 1] <= value) return false return true } fun part1(input: List<String>): Int { val map = parse(input) var sum = 0 for (y in map.indices) { for (x in map[y].indices) { if (isLowPoint(map, y, x)) sum += 1 + map[y][x] } } return sum } fun computeBasin(map: List<List<Int>>, lowY: Int, lowX: Int): MutableList<Pair<Int, Int>> { val toVisit = mutableListOf(lowY to lowX) val visited = mutableListOf<Pair<Int, Int>>() fun shouldAdd(pair: Pair<Int, Int>) = map[pair.first][pair.second] != 9 && pair !in visited && pair !in toVisit while (toVisit.isNotEmpty()) { val coordinate = toVisit.removeLast().also(visited::add) val (y, x) = coordinate (y - 1 to x).takeIf { it.first in map.indices && shouldAdd(it) }?.let(toVisit::add) (y + 1 to x).takeIf { it.first in map.indices && shouldAdd(it) }?.let(toVisit::add) (y to x - 1).takeIf { it.second in map[it.first].indices && shouldAdd(it) }?.let(toVisit::add) (y to x + 1).takeIf { it.second in map[it.first].indices && shouldAdd(it) }?.let(toVisit::add) } return visited } fun part2(input: List<String>): Int { val map = parse(input) val basins = mutableListOf<Int>() for (y in map.indices) { for (x in map[y].indices) { if (isLowPoint(map, y, x)) { basins += computeBasin(map, y, x).size } } } basins.sortDescending() return basins.take(3).reduce(Int::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 15) check(part2(testInput) == 1134) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
2,408
AdventOfCode2021
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day19.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution fun main() { Day19.solve() } object Day19 : AdventSolution(2023, 19, "Aplenty") { override fun solvePartOne(input: String): Int { val (workflows, parts) = parse(input) val flows = workflows.associateBy { it.name } return parts.filter { it.acceptedBy(flows) }.sumOf(Part::value) } override fun solvePartTwo(input: String): Long { val workflows = parse(input).first.associateBy { it.name } val initial = PartRange(Part("xmas".map { it to 1 }.toMap()), Part("xmas".map { it to 4001 }.toMap())) val incomplete = mutableListOf<Pair<PartRange, Evaluation>>(initial to Evaluation.DecideByWorkflow("in")) val accepted = mutableListOf<PartRange>() while (incomplete.isNotEmpty()) { val (currentRange, currentTarget) = incomplete.removeLast() when (currentTarget) { is Evaluation.DecideByWorkflow -> { incomplete += workflows.getValue(currentTarget.name).evaluatePartRange(currentRange) } Evaluation.Accepted -> accepted += currentRange Evaluation.Rejected -> continue } } return accepted.sumOf(PartRange::countPartsWithinRange) } } private fun parse(input: String): Pair<List<Workflow>, List<Part>> { fun parsePart(input: String): Part { val values = """(\d+)""".toRegex().findAll(input).map { it.value.toInt() }.toList() return "xmas".asIterable().zip(values).toMap().let (::Part) } fun parseTarget(input: String) = when (input) { "A" -> Evaluation.Accepted "R" -> Evaluation.Rejected else -> Evaluation.DecideByWorkflow(input) } fun parseWorkflow(input: String): Workflow { val name = input.substringBefore("{") val flows = input.substringAfter("{").dropLast(1).split(",") val default = flows.last().let(::parseTarget) val comparisons = flows.dropLast(1).map { val property = it.first() val lessThan = it[1] == '<' val amount = it.substring(2).substringBefore(":").toInt() val target = it.substringAfter(":").let(::parseTarget) Comparison(property, lessThan, amount, target) } return Workflow(name, comparisons, default) } val (workflows, parts) = input.split("\n\n") return workflows.lines().map { parseWorkflow(it) } to parts.lines().map { parsePart(it) } } private data class Workflow(val name: String, val steps: List<Comparison>, val default: Evaluation) { fun evaluatePartRange(part: Part): Evaluation = steps.firstNotNullOfOrNull { it.eval(part) } ?: default fun evaluatePartRange(partRange: PartRange): List<Pair<PartRange, Evaluation>> { val resolved = mutableListOf<Pair<PartRange, Evaluation>>() val remainder = steps.fold(partRange) { range, comparison -> val (res, rem) = comparison.eval(range) resolved += res rem } return resolved + (remainder to default) } } private data class Comparison(val property: Char, val lessThan: Boolean, val v: Int, val evaluation: Evaluation) { fun eval(part: Part): Evaluation? { return if (lessThan && part[property] < v) evaluation else if (!lessThan && part[property] > v) evaluation else null } fun eval(range: PartRange): Pair<Pair<PartRange, Evaluation>, PartRange> = if (lessThan) { val (low, high) = range.partition(property, v) Pair(low to evaluation, high) } else { val (low, high) = range.partition(property, v + 1) Pair(high to evaluation, low) } } private sealed class Evaluation { data object Accepted : Evaluation() data object Rejected : Evaluation() data class DecideByWorkflow(val name: String) : Evaluation() } private data class Part(private val props:Map<Char,Int>) { fun copyWith(property: Char, value: Int) = Part(props + (property to value)) operator fun get(property: Char) = props.getValue(property) fun value() = props.values.sum() fun area() = props.values.fold(1L,Long::times) operator fun minus(o:Part) = Part(o.props.mapValues { (p,v)-> v - this[p] }) fun acceptedBy(workflows: Map<String, Workflow>): Boolean = generateSequence<Evaluation>(Evaluation.DecideByWorkflow("in")) { (it as? Evaluation.DecideByWorkflow)?.name?.let(workflows::get)?.evaluatePartRange(this) }.last() == Evaluation.Accepted } private data class PartRange(val start: Part, val endExclusive: Part) { fun partition(property: Char, startOfHigh: Int): Pair<PartRange, PartRange> { val lower = copy(endExclusive = endExclusive.copyWith(property, startOfHigh)) val higher = copy(start = start.copyWith(property, startOfHigh)) return lower to higher } fun countPartsWithinRange() = (endExclusive - start).area() }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
5,029
advent-of-code
MIT License
src/Day08.kt
rweekers
573,305,041
false
{"Kotlin": 38747}
fun main() { fun part1(trees: List<List<Int>>): Int { return trees.indices .flatMap { y -> trees.first().indices .map { x -> trees.isVisible(x, y) } }.count { it } } fun part2(trees: List<List<Int>>): Int { return trees.indices .flatMap { y -> trees.first().indices .map { x -> trees.visibleTreesFrom(x, y) .map { it.takeUntil { height -> height < trees[y][x] } } .map { it.size } .reduce { acc, i -> acc.times(i) } } }.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val testTrees: List<List<Int>> = testInput.indices.map { y -> testInput.first().indices.map { x -> testInput[y][x].digitToInt() } } check(part1(testTrees) == 21) check(part2(testTrees) == 8) val input = readInput("Day08") val trees: List<List<Int>> = input.indices.map { y -> input.first().indices.map { x -> input[y][x].digitToInt() } } println(part1(trees)) println(part2(trees)) } private fun List<List<Int>>.visibleTreesFrom(x: Int, y: Int): List<List<Int>> { val height = this.size val width = this.first().size return listOf( (y - 1 downTo 0).map { this[it][x] }, (x + 1 until width).map { this[y][it] }, (y + 1 until height).map { this[it][x] }, (x - 1 downTo 0).map { this[y][it] } ) } private fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean { return this.visibleTreesFrom(x, y).any { treeRow -> treeRow.all { it < this[y][x] } } }
0
Kotlin
0
1
276eae0afbc4fd9da596466e06866ae8a66c1807
1,782
adventofcode-2022
Apache License 2.0
app/src/main/kotlin/day09/Day09.kt
KingOfDog
433,706,881
false
{"Kotlin": 76907}
package day09 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 9 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay09Part1, ::solveDay09Part2) } fun solveDay09Part1(input: List<String>): Int { val heights = input.map { row -> row.toCharArray().map { it.digitToInt() } } val width = heights[0].size val height = heights.size val lowPoints = mutableListOf<Int>() heights.forEachIndexed { y, row -> row.forEachIndexed { x, point -> val surroundingPoints = listOf(0 to 1, 0 to -1, -1 to 0, 1 to 0) .map { x + it.first to y + it.second } .filterNot { it.first < 0 || it.second < 0 || it.first >= width || it.second >= height } .map { heights[it.second][it.first] } if (surroundingPoints.none { it <= point }) { lowPoints.add(point) } } } return lowPoints.sumOf { it + 1 } } fun solveDay09Part2(input: List<String>): Int { val heights = input.map { row -> row.toCharArray().map { it.digitToInt() } } val width = heights[0].size val height = heights.size val points = heights.mapIndexed { y, row -> row.mapIndexed { x, _ -> Point(x, y) } }.flatten() val availablePoints = points.toMutableList() val usedPoints = mutableListOf<Point>() val basins = points.asSequence() .filterNot { heights[it.y][it.x] == 9 } .filter { availablePoints.contains(it) } .map { heights.findBasin(it, width, height, usedPoints).also { points -> availablePoints.removeAll(points) usedPoints.addAll(points) println("Completed step for $it and found $points") } } .toList() return basins.map { it.size }.sortedDescending().subList(0, 3).reduce { acc, i -> acc * i } } data class Point(val x: Int, val y: Int) fun List<List<Int>>.findBasin( point: Point, width: Int, height: Int, alreadyVisited: List<Point> = emptyList() ): List<Point> { if (this[point.y][point.x] == 9) { return emptyList() } val neighbors = point.getNeighbors(width, height).filterNot { alreadyVisited.contains(it) } val visited = alreadyVisited + neighbors + listOf(point) val neighborBasins = mutableSetOf<Point>() for (neighbor in neighbors) { val basin = this.findBasin(neighbor, width, height, visited + neighborBasins) neighborBasins.addAll(basin) } return neighborBasins.toList() + listOf(point) } fun Point.getNeighbors(width: Int, height: Int): List<Point> { return listOf(0 to 1, 0 to -1, -1 to 0, 1 to 0) .map { Point(x + it.first, y + it.second) } .filterNot { it.x < 0 || it.y < 0 || it.x >= width || it.y >= height } }
0
Kotlin
0
0
576e5599ada224e5cf21ccf20757673ca6f8310a
2,881
advent-of-code-kt
Apache License 2.0
src/Day12.kt
dmstocking
575,012,721
false
{"Kotlin": 40350}
// Cheat the package to get true isolation between source files package day12 import readInput import java.util.PriorityQueue import kotlin.math.abs data class Position(val x: Int, val y: Int) { var cost = 0 fun up(): Position = copy(y = y - 1) fun down(): Position = copy(y = y + 1) fun right(): Position = copy(x = x + 1) fun left(): Position = copy(x = x - 1) fun distance(other: Position) = abs(x - other.x) + abs(y - other.y) } data class Map(val start: Position, val end: Position, val data: List<List<Int>>) { fun shortestPath(start: Position): List<Position>? { val queue = PriorityQueue<Position> { a, b -> (a.distance(end) + a.cost).compareTo(b.distance(end) + b.cost) } var at = start queue.add(at) val closed = mutableSetOf<Position>() val cameFrom = mutableMapOf<Position, Position>() val cost = mutableMapOf<Position, Int>() while (at != end) { if (queue.size == 0) { return null } at = queue.remove() closed.add(at) listOf(at.up(), at.down(), at.right(), at.left()) .filter { it.y in data.indices && it.x in data.first().indices } .filter { data[it.y][it.x] - data[at.y][at.x] <= 1 } .filter { it !in closed } .forEach { val oldCost = cost[it] val newCost = (cost[at] ?: 0) + 1 if (oldCost == null || newCost < oldCost) { queue.remove(it) it.cost = newCost cost[it] = newCost queue.add(it) cameFrom[it] = at } } } return generateSequence { val next = cameFrom[at] next?.let { at = next } next } .toList() } companion object { fun parse(input: List<String>): Map { var start: Position? = null var end: Position? = null val data = input.mapIndexed { y, line -> line.mapIndexed { x, c -> val char = when (c) { 'S' -> { start = Position(x, y) 'a' } 'E' -> { end = Position(x, y) 'z' } else -> c } char.code - 'a'.code } } return Map(start!!, end!!, data) } } } fun main() { fun part1(input: List<String>): Int { val map = Map.parse(input) return map.shortestPath(map.start)?.size ?: -1 } fun part2(input: List<String>): Int { val map = Map.parse(input) return map .data .flatMapIndexed { y, line -> line.mapIndexed { x, elevation -> Position(x, y) to elevation }} .filter { (_, elevation) -> elevation == 0 } .map { (position, _) -> map.shortestPath(position)?.size ?: Int.MAX_VALUE } .minOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") println(part1(testInput)) check(part1(testInput) == 31) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e49d9247340037e4e70f55b0c201b3a39edd0a0f
3,528
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/advent/y2018/day6.kt
IgorPerikov
134,053,571
false
{"Kotlin": 29606}
package advent.y2018 import misc.readAdventInput fun main(args: Array<String>) { val points = parsePoints() println(getSizeOfBiggestLimitedArea(points)) println(getSizeOfSafeRegion(points)) } private fun getSizeOfSafeRegion(points: Set<Point>): Int { var result = 0 val maxX = points.map { it.x }.max()!! val maxY = points.map { it.y }.max()!! for (row in 0..maxY) { for (column in 0..maxX) { if (calcDistancesToAllPoints(row, column, points) < 10000) { result++ } } } return result } private fun calcDistancesToAllPoints(row: Int, column: Int, points: Set<Point>): Int { return points.map { point -> manhattanDistance(column, row, point.x, point.y) }.sum() } private fun getSizeOfBiggestLimitedArea(points: Set<Point>): Int { val grid = generateGrid(points) grid.forEachIndexed { rowNumber, row -> row.forEachIndexed { column, _ -> val closestPoint = findClosestPoint(rowNumber, column, points) if (closestPoint != null) { grid[rowNumber][column] = closestPoint } } } return removeInfiniteAreas(grid, points.map { it.name }) .map { pointName -> countPointEntries(grid, pointName) } .max()!! } private fun findClosestPoint(row: Int, column: Int, points: Set<Point>): Int? { val distances = points .map { point -> Pair(manhattanDistance(point.x, point.y, column, row), point.name) } .sortedBy { it.first } if (distances[0].first == distances[1].first) { return null } else { return distances[0].second } } private fun removeInfiniteAreas(grid: Array<IntArray>, pointNames: List<Int>): Set<Int> { val resultPoints = HashSet(pointNames) for (i in 0 until grid.size) { resultPoints.remove(grid[i][0]) resultPoints.remove(grid[i][grid[0].size - 1]) } for (i in 0 until grid[0].size) { resultPoints.remove(grid[0][i]) resultPoints.remove(grid[grid.size - 1][i]) } return resultPoints } private fun countPointEntries(grid: Array<IntArray>, pointName: Int): Int { return grid.iterator() .asSequence() .flatMap { it.asSequence() } .count { it == pointName } } private fun parsePoints(): Set<Point> { var i = 1 return readAdventInput(6, 2018) .map { val coordinates = it.split(", ") Point(coordinates[0].toInt(), coordinates[1].toInt(), i++) } .toHashSet() } private fun generateGrid(points: Set<Point>): Array<IntArray> { val maxX = points.map { it.x }.max()!! val maxY = points.map { it.y }.max()!! return Array(maxY) { IntArray(maxX) { 0 } } } private fun manhattanDistance(x1: Int, y1: Int, x2: Int, y2: Int) = Math.abs(x1 - x2) + Math.abs(y1 - y2) private data class Point(val x: Int, val y: Int, val name: Int)
0
Kotlin
0
0
b30cf179f7b7ae534ee55d432b13859b77bbc4b7
2,916
kotlin-solutions
MIT License
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day11.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput import kotlin.math.abs class Day11 { fun part1(text: List<String>): Long { val expandingRows = text.getExpansionRowIndexes() val expandingColumns = text.transpose().getExpansionRowIndexes() val galaxyCombinations = text.getGalaxies().combinations().toList() return galaxyCombinations.sumOf { (a, b) -> getGalaxyPathLength(a, b, expandingColumns, expandingRows) } } fun part2(text: List<String>): Long { val rows = text.getExpansionRowIndexes() val columns = text.transpose().getExpansionRowIndexes() val galaxyCombinations = text.getGalaxies().combinations().toList() return galaxyCombinations.sumOf { (a, b) -> getGalaxyPathLength(a, b, columns, rows, 1000000) } } private fun List<String>.getExpansionRowIndexes() = mapIndexedNotNull { index, line -> line.takeIf { it.all('.'::equals) }?.let { index } } private fun List<String>.transpose(): List<String> = first().indices.map { x -> indices.map { y -> this[y][x] } }.map(List<Char>::toCharArray).map(::String) private fun List<String>.getGalaxies() = flatMapIndexed { y: Int, line: String -> line.mapIndexedNotNull { x, char -> char.takeIf('#'::equals)?.let { Galaxy(1, x, y) } } }.mapIndexed { index, pair -> pair.copy(id = index + 1) } private fun <T> List<T>.combinations() = asSequence() .flatMapIndexed { index: Int, a: T -> drop(index + 1).map { b -> a to b } } private fun getGalaxyPathLength( galaxy1: Galaxy, galaxy2: Galaxy, columns: List<Int>, rows: List<Int>, expansionMultiplier: Long = 2L, ): Long { val expandedX = (minOf(galaxy1.x, galaxy2.x)..maxOf(galaxy1.x, galaxy2.x)) .count { it in columns } .toLong() .times(expansionMultiplier.dec()) val expandedY = (minOf(galaxy1.y, galaxy2.y)..maxOf(galaxy1.y, galaxy2.y)) .count { it in rows } .toLong() .times(expansionMultiplier.dec()) val xDiff = abs(galaxy1.x - galaxy2.x).toLong() val yDiff = abs(galaxy1.y - galaxy2.y).toLong() return xDiff + yDiff + expandedX + expandedY } data class Galaxy(val id: Int, val x: Int, val y: Int) } fun main() { val answer1 = Day11().part1(readInput("Day11")) println(answer1) val answer2 = Day11().part2(readInput("Day11")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
2,575
advent-of-code-2023
MIT License
src/y2023/Day22.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.timingStatistics object Day22 { data class Brick( val xRange: IntRange, val yRange: IntRange, val zRange: IntRange ) { fun xyOverlap(other: Brick): Boolean { return xRange.intersects(other.xRange) && yRange.intersects(other.yRange) } } fun IntRange.intersects(other: IntRange): Boolean { return (first in other || last in other || other.first in this || other.last in this) } private fun parse(input: List<String>): List<Brick> { return input.map { line -> val (starts, ends) = line.split('~').map { raw -> raw.split(',').map { it.toInt() } } Brick( starts[0]..ends[0], starts[1]..ends[1], starts[2]..ends[2] ) }.sortedBy { it.zRange.first } } fun part1(input: List<String>): Int { val bricks = parse(input) val fallenBricks = fallenBricks(bricks) val brickLookupBottom = fallenBricks.groupBy { it.zRange.first } val brickLookupTop = fallenBricks.groupBy { it.zRange.last } val disintegratable = fallenBricks.filter { brick -> val above = (brickLookupBottom[brick.zRange.last + 1] ?: emptyList()).filter { it.xyOverlap(brick) } if (above.isEmpty()) { true } else { above.all { aboveBrick -> val below = (brickLookupTop[aboveBrick.zRange.first - 1] ?: emptyList()) .filter { it.xyOverlap(aboveBrick) } below.size >= 2 } } }.toSet() return disintegratable.size } private fun fallenBricks(bricks: List<Brick>): MutableList<Brick> { val fallenBricks = mutableListOf<Brick>() bricks.forEach { brick -> val z = fallenBricks.filter { brick.xyOverlap(it) }.maxOfOrNull { it.zRange.last } ?: 0 fallenBricks.add( Brick( brick.xRange, brick.yRange, z + 1..(z + 1 + brick.zRange.last - brick.zRange.first) ) ) } return fallenBricks } fun part2(input: List<String>): Int { val bricks = parse(input) val fallenBricks = fallenBricks(bricks) val brickLookupBottom = fallenBricks.groupBy { it.zRange.first } val brickLookupTop = fallenBricks.groupBy { it.zRange.last } return fallenBricks.sumOf { brick -> val allToFall = mutableSetOf<Brick>() var top = listOf(brick) while (top.isNotEmpty()) { top = top.flatMap { current -> val supportedByCurrent = (brickLookupBottom[current.zRange.last + 1] ?: emptyList()) .filter { it.xyOverlap(current) } supportedByCurrent.filter { above -> val supportingAbove = (brickLookupTop[above.zRange.first - 1] ?: emptyList()) .filter { it.xyOverlap(above) } check(supportingAbove.isNotEmpty()) { "No support for $above" } supportingAbove.all { it in allToFall || it in top } } } allToFall.addAll(top) } allToFall.size } } } fun main() { val testInput = """ 1,0,1~1,2,1 0,0,2~2,0,2 0,2,3~2,2,3 0,0,4~0,2,4 2,0,5~2,2,5 0,1,6~2,1,6 1,1,8~1,1,9 """.trimIndent().split("\n") println("------Tests------") println(Day22.part1(testInput)) println(Day22.part2(testInput)) println("------Real------") val input = readInput(2023, 22) println("Part 1 result: ${Day22.part1(input)}") println("Part 2 result: ${Day22.part2(input)}") timingStatistics { Day22.part1(input) } timingStatistics { Day22.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
4,004
advent-of-code
Apache License 2.0
src/Day02.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
private enum class Outcome(val score: Int) { WIN(6), DRAW(3), LOSE(0); fun inverted(): Outcome = when (this) { WIN -> LOSE; DRAW -> DRAW; LOSE -> WIN } } private sealed class Shape(val score: Int) { object Rock : Shape(1) object Paper : Shape(2) object Scissors : Shape(3) fun evaluate(other: Shape): Outcome = when { this == other -> Outcome.DRAW this == Rock && other == Scissors -> Outcome.WIN this == Scissors && other == Paper -> Outcome.WIN this == Paper && other == Rock -> Outcome.WIN else -> Outcome.LOSE } } private operator fun <T1, T2> List<T1>.times(other: List<T2>): List<Pair<T1, T2>> = buildList { [email protected] { left -> other.forEach { right -> add(left to right) } } } private object Lookup { private val scenarios = buildList { val shapes = listOf(Shape.Rock, Shape.Paper, Shape.Scissors) (shapes * shapes).forEach { (shape1, shape2) -> add(Round(shape1, shape2)) } } fun find(shape1: Shape, shape2: Shape): Round = scenarios.single { it.shape1 == shape1 && it.shape2 == shape2 } fun find(shape1: Shape, outcome: Outcome): Round = scenarios.single { it.shape1 == shape1 && it.result.outcome2 == outcome } } private fun shapeFromCode(code: String) = when (code) { "A", "X" -> Shape.Rock "B", "Y" -> Shape.Paper "C", "Z" -> Shape.Scissors else -> throw IllegalArgumentException() } private fun outcomeFromCode(code: String) = when (code) { "X" -> Outcome.LOSE "Y" -> Outcome.DRAW "Z" -> Outcome.WIN else -> throw IllegalArgumentException() } private data class Tournament(val rounds: List<Round>) { val totalScore2 = rounds.sumOf { it.shape2.score + it.result.outcome2.score } } private data class Round(val shape1: Shape, val shape2: Shape) { val result: Result = shape1.evaluate(shape2).let { outcome1 -> Result(outcome1, outcome1.inverted()) } } private data class Result(val outcome1: Outcome, val outcome2: Outcome) fun main() { fun parse(input: List<String>, transform: (String, String) -> Round): Tournament = input .map { it.split(" ") } .map { transform(it[0], it[1]) } .let(::Tournament) fun part1(input: List<String>): Int = parse(input) { code1, code2 -> Lookup.find(shapeFromCode(code1), shapeFromCode(code2)) }.totalScore2 fun part2(input: List<String>): Int = parse(input) { code1, code2 -> Lookup.find(shapeFromCode(code1), outcomeFromCode(code2)) }.totalScore2 val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
2,792
advent-of-code-in-kotlin-2022
Apache License 2.0
src/Day07.kt
bin-wang
572,801,360
false
{"Kotlin": 19395}
object Day07 { data class File(val name: String, val size: Int) class Directory(val name: String, val parent: Directory?) { var dirs: List<Directory> = listOf() var files: List<File> = listOf() val size: Int by lazy { files.sumOf { it.size } + dirs.sumOf { it.size } } fun traverse(): List<Directory> { return listOf(this) + dirs.flatMap { it.traverse() } } } sealed interface Command { companion object { fun from(input: String): Command { val tokens = input.split(' ').filter(String::isNotBlank) return when (tokens[0]) { "cd" -> CD(directoryName = tokens[1]) "ls" -> LS else -> error("Unable to parse command") } } } } data class CD(val directoryName: String) : Command object LS : Command const val total = 70000000 const val needed = 30000000 } fun main() { fun parseInputAsFilesystemTree(input: String): Day07.Directory { val snippets = input.split("$").filter(String::isNotBlank).map { it.trim().lines() } val root = Day07.Directory("/", parent = null) var currentDir = root snippets.forEach { s -> when (val command = Day07.Command.from(s.first())) { Day07.LS -> { val (dirTokens, fileTokens) = s.drop(1).partition { it.startsWith("dir") } currentDir.dirs = dirTokens.map { val (_, dirName) = it.split(' ') Day07.Directory(dirName, parent = currentDir) } currentDir.files = fileTokens.map { val (size, fileName) = it.split(' ') Day07.File(fileName, size.toInt()) } } is Day07.CD -> { currentDir = when (command.directoryName) { "/" -> root ".." -> currentDir.parent!! else -> currentDir.dirs.first { it.name == command.directoryName } } } } } return root } fun part1(root: Day07.Directory) = root.traverse().mapNotNull { directory -> directory.size.takeIf { it <= 100000 } }.sum() fun part2(root: Day07.Directory): Int { val free = Day07.total - root.size val toFree = Day07.needed - free return root.traverse().mapNotNull { directory -> directory.size.takeIf { it >= toFree } }.min() } val testInput = readInputAsString("Day07_test") val testRoot = parseInputAsFilesystemTree(testInput) check(part1(testRoot) == 95437) check(part2(testRoot) == 24933642) val input = readInputAsString("Day07") val root = parseInputAsFilesystemTree(input) println(part1(root)) println(part2(root)) }
0
Kotlin
0
0
dca2c4915594a4b4ca2791843b53b71fd068fe28
2,993
aoc22-kt
Apache License 2.0
src/main/kotlin/adventofcode2023/day2/day2.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day2 import adventofcode2023.readInput import kotlin.math.max fun main() { val input = readInput("day2.txt") println("Day 2") println("Puzzle 1: ${puzzle1(input, GameRecord(red = 12, green = 13, blue = 14))}") println("Puzzle 2: ${puzzle2(input)}") } data class GameRecord( val green: Int = 0, val red: Int = 0, val blue: Int = 0 ) fun puzzle1(input: List<String>, initial: GameRecord): Int { return input.map { l -> dummyLineParsing(l) } .filter { isGamePossible(initial, it.second) } .sumOf { (id, _) -> id } } fun puzzle2(input: List<String>): Int { return input.map { l -> dummyLineParsing(l) } .map { (_, records) -> calculateMinimalGameAmount(records) } .map(::calculatePower) .sum() } fun dummyLineParsing(line: String): Pair<Int, List<GameRecord>> { val (gameIdStr, colorsStr) = line.split(":") val gameId = gameIdStr.substring(5).toInt() val gameRecords = colorsStr.split(";").map { s -> s.split(",").map { val (v, color) = it.trim().split(" ") color to v.toInt() }.toMap() }.map { m -> GameRecord( green = m.getOrDefault("green", 0), red = m.getOrDefault("red", 0), blue = m.getOrDefault("blue", 0) ) } return Pair(gameId, gameRecords) } fun isGamePossible(initial: GameRecord, input: List<GameRecord>): Boolean = !input.any { gr -> gr.green > initial.green || gr.blue > initial.blue || gr.red > initial.red } fun calculateMinimalGameAmount(input: List<GameRecord>): GameRecord = input.reduce { acc, gr -> GameRecord(red = max(acc.red, gr.red), green = max(acc.green, gr.green), blue = max(acc.blue, gr.blue)) } fun calculatePower(gameRecord: GameRecord): Int = gameRecord.red * gameRecord.blue * gameRecord.green
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
1,871
adventofcode2023
MIT License
src/Day08.kt
kthun
572,871,866
false
{"Kotlin": 17958}
enum class Direction { NORTH, SOUTH, EAST, WEST } fun main() { fun part1(input: List<String>): Int { val trees = input.map { line -> line.toCharArray().map { it.toString().toInt() } } val height = trees.size val width = trees[0].size val numVisibleTrees = trees.mapIndexed { row, line -> line.mapIndexed { col, tree -> if ((0 until row).map { trees[it][col] }.none { otherTree -> otherTree >= tree } || (row + 1 until height).map { trees[it][col] }.none { otherTree -> otherTree >= tree } || (0 until col).map { trees[row][it] }.none { otherTree -> otherTree >= tree } || (col + 1 until width).map { trees[row][it] }.none { otherTree -> otherTree >= tree }) { 1 } else { 0 } } } .flatten() .sum() return numVisibleTrees } fun treesSeen(trees: List<List<Int>>, tree: Int, row: Int, col: Int, gridHeight: Int, gridWidth: Int, direction: Direction): Int { var seen = 0 when (direction) { Direction.NORTH -> { for (r in row - 1 downTo 0) { seen++ if (trees[r][col] >= tree) break } } Direction.SOUTH -> { for (r in row + 1 until gridHeight) { seen++ if (trees[r][col] >= tree) break } } Direction.EAST -> { for (c in col + 1 until gridWidth) { seen++ if (trees[row][c] >= tree) break } } Direction.WEST -> { for (c in col - 1 downTo 0) { seen++ if (trees[row][c] >= tree) break } } } return seen } fun scenicScore(trees: List<List<Int>>, tree: Int, row: Int, col: Int, gridHeight: Int, gridWidth: Int): Int { val treesSeenWest = treesSeen(trees, tree, row, col, gridHeight, gridWidth, Direction.WEST) val treesSeenEast = treesSeen(trees, tree, row, col, gridHeight, gridWidth, Direction.EAST) val treesSeenNorth = treesSeen(trees, tree, row, col, gridHeight, gridWidth, Direction.NORTH) val treesSeenSouth = treesSeen(trees, tree, row, col, gridHeight, gridWidth, Direction.SOUTH) return treesSeenSouth * treesSeenNorth * treesSeenEast * treesSeenWest } fun part2(input: List<String>): Int { val trees = input.map { line -> line.toCharArray().map { it.toString().toInt() } } val height = trees.size val width = trees[0].size val bestScenicScore = trees.mapIndexed { row, line -> line.mapIndexed { col, tree -> scenicScore(trees, tree, row, col, height, width) .also { if (col in 1 until width - 1 && row in 1 until height - 1) { println("($col, $row) is $tree tall and has score $it") } } } } .flatten() .maxByOrNull { it } ?: 0 return bestScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") check(part1(testInput) == 21) println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
5452702e4e20ef2db3adc8112427c0229ebd1c29
3,605
aoc-2022
Apache License 2.0
src/year2021/day14/Day14.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2021.day14 import util.assertTrue import util.model.Counter import util.read2021DayInput fun main() { fun task1(input: List<String>) = findOptimalPolymer(input, 10) fun task2(input: List<String>) = findOptimalPolymer(input, 40) val input = read2021DayInput("Day14") assertTrue(task1(input) == "${3342}".toLong()) assertTrue(task2(input) == "${3776553567525}".toLong()) } fun findOptimalPolymer(input: List<String>, insertionLimit: Int): Long { val polymerTemplate = input.first() val rules = input.takeLast(input.size - 2).map { it.split(" -> ") }.map { Rule(it[0], it[1]) } polymerTemplate.windowed(2).forEach { rules.first { rule -> it == rule.name }.counter++ } val finalRules = rec(rules, Counter(), insertionLimit) val letters = rules.map { it.insertion }.distinct().map { letter -> Pair(letter, finalRules.sumOf { rule -> rule.name.count { "$it" == letter } * rule.counter } / 2 ) }.sortedBy { it.second } return calcWithOffset(polymerTemplate, letters.last()) - calcWithOffset(polymerTemplate, letters.first()) } fun calcWithOffset(polymerTemplate: String, letter: Pair<String, Long>): Long { return if (letter.first.single() == polymerTemplate.first() || letter.first.single() == polymerTemplate.last() ) letter.second + 1 else letter.second } fun rec(rules: List<Rule>, counter: Counter, limit: Int): List<Rule> { if (counter.i > limit - 1) return rules val temp = rules.map { it.copy() }.toMutableList() for (i in rules.indices) { if (rules[i].counter > 0) { temp[i].counter -= rules[i].counter temp[i].outcome.forEach { insertion -> temp.first { it.name == insertion }.counter += rules[i].counter } } } counter.i++ return rec(temp, counter, limit) } data class Rule( val name: String, val insertion: String, var counter: Long = 0 ) { val outcome = mutableListOf<String>() init { outcome.addAll(listOf(name.first() + insertion, insertion + name.last())) } }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
2,106
advent-of-code-kotlin-template
Apache License 2.0
src/Day02.kt
WaatzeG
573,594,703
false
{"Kotlin": 7476}
fun main() { val testInput = readInput("Day02_input") val solutionPart1 = part1(testInput) println("Solution part 1: $solutionPart1") val solutionPart2 = part2(testInput) println("Solution part 2: $solutionPart2") } /** * Total score strategy 1 */ private fun part1(input: List<String>): Int { val opponentActions = mapOf( "A" to RockPaperScissorsAction.Rock, "B" to RockPaperScissorsAction.Paper, "C" to RockPaperScissorsAction.Scissors ) val counterActions = mapOf( "X" to CounterAction(RockPaperScissorsAction.Rock, 1), "Y" to CounterAction(RockPaperScissorsAction.Paper, 2), "Z" to CounterAction(RockPaperScissorsAction.Scissors, 3), ) return input.sumOf { games -> val (opponentAction, counterAction) = games.split(" ") .let { game -> opponentActions.getValue(game[0]) to counterActions.getValue(game[1]) } val gameResult = determineGameResult(opponentAction, counterAction.action) gameResult.points + counterAction.points } } /** * Total score strategy 2 */ private fun part2(input: List<String>): Int { val opponentActions = mapOf( "A" to RockPaperScissorsAction.Rock, "B" to RockPaperScissorsAction.Paper, "C" to RockPaperScissorsAction.Scissors ) val gameResults = mapOf( "X" to RockPaperScissorsGameResult.Loss, "Y" to RockPaperScissorsGameResult.Draw, "Z" to RockPaperScissorsGameResult.Win, ) return input.sumOf { games -> val (opponentAction, gameResult) = games.split(" ") .let { game -> opponentActions.getValue(game[0]) to gameResults.getValue(game[1]) } val counterAction = determineCounterAction(gameResult, opponentAction) gameResult.points + counterAction.points } } private fun determineGameResult( opponentAction: RockPaperScissorsAction, ownAction: RockPaperScissorsAction, ): RockPaperScissorsGameResult { return when { opponentAction == ownAction -> RockPaperScissorsGameResult.Draw opponentAction.defeats(ownAction) -> RockPaperScissorsGameResult.Loss else -> RockPaperScissorsGameResult.Win } } private fun determineCounterAction( gameResult: RockPaperScissorsGameResult, opponentsAction: RockPaperScissorsAction, ): RockPaperScissorsAction { return when (gameResult) { RockPaperScissorsGameResult.Draw -> opponentsAction RockPaperScissorsGameResult.Win -> RockPaperScissorsAction.values().first { it.defeats(opponentsAction) } else -> RockPaperScissorsAction.values().first { opponentsAction.defeats(it) } } } private data class CounterAction(val action: RockPaperScissorsAction, val points: Int) private enum class RockPaperScissorsAction(val points: Int) { Rock(1), Paper(2), Scissors(3); fun defeats(other: RockPaperScissorsAction): Boolean { return when (this) { Scissors -> other == Paper Paper -> other == Rock Rock -> other == Scissors } } } private enum class RockPaperScissorsGameResult(val points: Int) { Draw(3), Win(6), Loss(0); }
0
Kotlin
0
0
324a98c51580b86121b6962651f1ba9eaad8f468
3,219
advent_of_code_2022_kotlin
Apache License 2.0
src/Day15.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
import kotlin.math.abs import kotlin.math.sign fun main() { fun List<IntRange>.union(): List<IntRange> { val sorted = sortedBy { it.first } val init = mutableListOf(sorted.first()) return sortedBy { it.first }.fold(init) { acc, r -> val last = acc.last() if (r.first <= last.last) { acc[acc.lastIndex] = (last.first..maxOf(last.last, r.last)) } else { acc += r } acc } } fun Point.frequency() = (x * 4_000_000L) + y infix fun Point.distanceTo(other: Point): Int { return abs(x - other.x) + abs(y - other.y) } infix fun Point.lineTo(other: Point): List<Point> { val xDelta = (other.x - x).sign val yDelta = (other.y - y).sign val steps = maxOf(abs(x - other.x), abs(y - other.y)) return (1..steps).scan(this) { prev, _ -> Point(prev.x + xDelta, prev.y + yDelta) } } fun Point.findRange(y: Int, distance: Int): IntRange? { val width = distance - abs(this.y - y) return (this.x - width..this.x + width).takeIf { it.first <= it.last } } fun parse(input: List<String>): MutableList<Pair<Point, Point>> { return input.map { val sensorX = it.substringAfter("Sensor at x=").substringBefore(",").toInt() val sensorY = it.substringBefore(":").substringAfter("y=").toInt() val beaconX = it.substringAfter("closest beacon is at x=").substringBefore(",").toInt() val beaconY = it.substringAfterLast("y=").toInt() Pair(Point(sensorX, sensorY), Point(beaconX, beaconY)) } .toMutableList() } fun part1(input: List<String>): Int { val pairs = parse(input) val y = 2_000_000 return pairs .mapNotNull { (sensor, beacon) -> val distance = sensor distanceTo beacon sensor.findRange(y, distance) } .union() .sumOf { it.last - it.first } } fun part2(input: List<String>): Long { val pairs = parse(input) val cave = 0..4_000_000L return pairs.firstNotNullOf { (sensor, beacon) -> val distance = sensor distanceTo beacon val up = Point(sensor.x, sensor.y - distance - 1) val down = Point(sensor.x, sensor.y + distance + 1) val left = Point(sensor.x - distance - 1, sensor.y) val right = Point(sensor.x + distance + 1, sensor.y) (up.lineTo(right) + right.lineTo(down) + down.lineTo(left) + left.lineTo(up)) .filter { it.x in cave && it.y in cave } .firstOrNull { point -> pairs.all { (sensor, beacon) -> sensor distanceTo point > sensor distanceTo beacon } } }.frequency() } val input = readInput("inputs/Day15") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
3,008
aoc-2022
Apache License 2.0
src/Day08.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution08(input: List<String>) { val trees = input.map { it.toCharArray() } val coords = trees.indices.cartesianProduct(trees[0].indices) val maxX = trees[0].indices.max() val maxY = trees.indices.max() fun getTree(c: Coordinate) = trees[c.y][c.x] fun getTreesAbove(c: Coordinate) = (0 until c.y).map { trees[it][c.x] } fun getTreesBelow(c: Coordinate) = (c.y + 1..maxY).map { trees[it][c.x] } fun getTreesLeft(c: Coordinate) = (0 until c.x).map { trees[c.y][it] } fun getTreesRight(c: Coordinate) = (c.x + 1..maxX).map { trees[c.y][it] } fun getScenicScoreAbove(c: Coordinate) = if (c.y == 0) 0 else (c.y - 1 downTo 1).takeWhile { getTree(c) > trees[it][c.x] }.count() + 1 fun getScenicScoreBelow(c: Coordinate) = if (c.y == maxY) 0 else (c.y + 1 until maxY).takeWhile { getTree(c) > trees[it][c.x] }.count() + 1 fun getScenicScoreLeft(c: Coordinate) = if (c.x == 0) 0 else (c.x - 1 downTo 1).takeWhile { getTree(c) > trees[c.y][it] }.count() + 1 fun getScenicScoreRight(c: Coordinate) = if (c.x == maxX) 0 else (c.x + 1 until maxX).takeWhile { getTree(c) > trees[c.y][it] }.count() + 1 fun part1() = coords.count { c -> getTreesAbove(c).all { getTree(c) > it } || getTreesBelow(c).all { getTree(c) > it } || getTreesLeft(c).all { getTree(c) > it } || getTreesRight(c).all { getTree(c) > it } } fun part2() = coords.maxOf { getScenicScoreAbove(it) * getScenicScoreBelow(it) * getScenicScoreLeft(it) * getScenicScoreRight(it) } } fun main() { val testSolution = Solution08(readInput("Day08_test")) check(testSolution.part1() == 21) check(testSolution.part2() == 8) val solution = Solution08(readInput("Day08")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,880
aoc-2022
Apache License 2.0
src/Day08.kt
erikthered
572,804,470
false
{"Kotlin": 36722}
fun main() { fun part1(input: List<String>): Int { val grid = input.map { line -> line.map { it.digitToInt() } } var visible = 0 grid.forEachIndexed { y, row -> // Add all trees in first or last row if (y == 0 || y == grid.lastIndex) { visible += row.size } else { row.forEachIndexed { x, height -> // Add all trees in first or last col if (x == 0 || x == row.lastIndex) { visible += 1 } else { if (height > row.subList(0, x).max() || height > row.subList(x + 1, row.lastIndex + 1).max() || height > grid.map { row -> row[x] }.subList(0, y).max() || height > grid.map { row -> row[x] }.subList(y + 1, grid.lastIndex + 1).max() ) visible += 1 } } } } return visible } fun part2(input: List<String>): Int { val rows = input.map { line -> line.map { it.digitToInt() } } var maxScore = 0 rows.forEachIndexed { y, row -> row.forEachIndexed { x, height -> val left = row.subList(0, x).reversed() val right = row.subList(x + 1, row.lastIndex + 1) val up = rows.map { row -> row[x] }.subList(0, y).reversed() val down = rows.map { row -> row[x] }.subList(y + 1, rows.lastIndex + 1) val score = arrayOf(left, right, up, down).map { direction -> direction.indexOfFirst { it >= height }.let { if (it == -1) direction.size else it + 1 } }.reduce { a, b -> a * b } if (score > maxScore) maxScore = score } } return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3946827754a449cbe2a9e3e249a0db06fdc3995d
2,180
aoc-2022-kotlin
Apache License 2.0
src/com/ncorti/aoc2023/Day07.kt
cortinico
723,409,155
false
{"Kotlin": 76642}
package com.ncorti.aoc2023 class CardComparator(val withJoker: Boolean) : Comparator<Pair<String, Int>> { private val cardRank = arrayOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A') private val cardRankWithJoker = arrayOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A') private fun compareCard(card1: Char, card2: Char): Int = if (withJoker) cardRankWithJoker.indexOf(card1) - cardRankWithJoker.indexOf(card2) else cardRank.indexOf(card1) - cardRank.indexOf(card2) private fun handScore(hand: String): Int { val cards = hand.toCharArray() val grouping = cards.groupBy { it }.mapValues { it.value.size }.toMutableMap() if (withJoker && 'J' in grouping) { val jokerInstances = grouping['J']!! grouping.remove('J') if (jokerInstances == 5) { grouping['A'] = 5 } else { val smartSortedEntries = grouping.entries.sortedWith { (key1, value1), (key2, value2) -> when { value1 > value2 -> -1 value1 < value2 -> 1 else -> compareCard(key1, key2) } } val (firstEntry, firstValue) = smartSortedEntries[0] grouping[firstEntry] = firstValue + jokerInstances } } return when { grouping.values.any { it == 5 } -> 7 grouping.values.any { it == 4 } -> 6 grouping.values.any { it == 3 } && grouping.values.any { it == 2 } -> 5 grouping.values.any { it == 3 } -> 4 grouping.values.count { it == 2 } == 2 -> 3 grouping.values.any { it == 2 } -> 2 else -> 1 } } override fun compare(o1: Pair<String, Int>, o2: Pair<String, Int>): Int { val (hand1, _) = o1 val (hand2, _) = o2 val score1 = handScore(hand1) val score2 = handScore(hand2) return when { score1 > score2 -> 1 score1 < score2 -> -1 else -> { for (i in hand1.indices) { val card1 = hand1[i] val card2 = hand2[i] val cardComparison = compareCard(card1, card2) if (cardComparison != 0) { return cardComparison } } 0 } } } } fun main() { fun part(withJoker: Boolean): Int { val hands = getInputAsText("07") { split("\n").filter(String::isNotBlank).map { val (card, rank) = it.split(" ") card to rank.toInt() } } return hands.sortedWith(CardComparator(withJoker = withJoker)).foldIndexed(0) { index, acc, (card, rank) -> acc + (rank * (index + 1)) } } println(part(withJoker = false)) println(part(withJoker = true)) }
1
Kotlin
0
1
84e06f0cb0350a1eed17317a762359e9c9543ae5
3,011
adventofcode-2023
MIT License
src/Day12.kt
arhor
572,349,244
false
{"Kotlin": 36845}
import java.util.* fun main() { val input = readInput {} val yIndicies = 0..input.lastIndex val xIndicies = 0..input.first().lastIndex fun validNeighbours(curr: Point, next: Point): Boolean { if (next.x in xIndicies && next.y in yIndicies) { val currHeight = determineHeight(input[curr.y][curr.x]) val nextHeight = determineHeight(input[next.y][next.x]) return nextHeight <= currHeight + 1 } return false } val data = input.withIndex().flatMap { (y, line) -> line.withIndex().map { (x, _) -> Point(x, y) } } println("Part 1: ${solvePuzzle1(input, data, ::validNeighbours)}") println("Part 2: ${solvePuzzle2(input, data, ::validNeighbours)}") } private fun solvePuzzle1(input: List<String>, data: List<Point>, validNeighbours: Point.(Point) -> Boolean): Double { val alpha = data.first { input[it.y][it.x] == 'S' } val omega = data.first { input[it.y][it.x] == 'E' } return dijkstra(alpha, omega, validNeighbours) } private fun solvePuzzle2(input: List<String>, data: List<Point>, validNeighbours: Point.(Point) -> Boolean): Double { val alpha = data.filter { input[it.y][it.x].let { height -> height == 'S' || height == 'a' } } val omega = data.first { input[it.y][it.x] == 'E' } return alpha.minOf { dijkstra(it, omega, validNeighbours) } } private fun determineHeight(value: Char) = when (value) { 'S' -> 'a' 'E' -> 'z' else -> value }.code private fun dijkstra(alpha: Point, omega: Point, validNeighbours: (Point, Point) -> Boolean): Double { val unvisited = PriorityQueue<Point>().apply { offer(alpha) } val distances = HashMap<Point, Double>().apply { put(alpha, 0.0) }.withDefault { Double.POSITIVE_INFINITY } while (!unvisited.isEmpty()) { val curr = unvisited.poll() val dist = distances.getValue(curr) + 1 for (next in curr.adjacentPoints(diagonal = false)) { if (validNeighbours(curr, next) && dist < distances.getValue(next)) { distances[next] = dist unvisited.add(next) } } } return distances.filterKeys { it == omega }.values.minOrNull() ?: Double.POSITIVE_INFINITY }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
2,231
aoc-2022-in-kotlin
Apache License 2.0
src/main/Day08.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day08 import geometry.Direction import geometry.Direction.* import utils.readInput import kotlin.math.max typealias Grid = List<String> data class Tree(val height: Int) { operator fun compareTo(tree: Tree): Int = height.compareTo(tree.height) } fun Grid.tree(row: Int, column: Int) = get(row)[column].toString().toInt().let(::Tree) fun Grid.countVisibleTrees(): Int { val visible = mutableMapOf<Pair<Int, Int>, Tree>() for (i in indices) { val max = mutableMapOf<Direction, Int>() fun check(row: Int, column: Int, direction: Direction) { val tree = tree(row, column) if (tree.height > max.getOrDefault(direction, Int.MIN_VALUE)) { visible[row to column] = tree max[direction] = tree.height } } for (j in indices) { check(row = i, column = j, direction = Right) check(row = j, column = i, direction = Down) check(row = i, column = size - 1 - j, direction = Left) check(row = size - 1 - j, column = i, direction = Up) } } return visible.size } fun Grid.highestScenicScore(): Int { var maxScore = 0 for (row in 1..size - 2) { for (column in 1..size - 2) { maxScore = max(score(row, column), maxScore) } } return maxScore } fun Grid.score(row: Int, column: Int): Int = when { row == 0 || column == 0 || row == size - 1 || column == size - 1 -> 0 else -> Direction.values() .map(findTrees(column, row)) .map { it.countVisible(tree(row, column)) } .reduce(Int::times) } private fun Grid.findTrees(column: Int, row: Int): (Direction) -> List<Tree> = { when (it) { Right -> (column + 1 until size).map { tree(row, it) } Down -> (row + 1 until size).map { tree(it, column) } Left -> (column - 1 downTo 0).map { tree(row, it) } Up -> (row - 1 downTo 0).map { tree(it, column) } } } private fun List<Tree>.countVisible(origin: Tree): Int { var score = 0 for (tree in this) { score += 1 if (tree >= origin) { break } } return score } fun part1(filename: String): Int = readInput(filename).countVisibleTrees() fun part2(filename: String): Int = readInput(filename).highestScenicScore() private const val filename = "Day08" fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
2,502
aoc-2022
Apache License 2.0
src/Day02.kt
TheOnlyTails
573,028,916
false
{"Kotlin": 9156}
private enum class RockPaperScissors(val play: Char, val response: Char, val score: Int) { Rock('A', 'X', 1), Paper('B', 'Y', 2), Scissors('C', 'Z', 3); companion object { val winners = mapOf( Rock to Paper, Paper to Scissors, Scissors to Rock, ) } } private enum class RoundResult(val c: Char) { Lose('X'), Draw('Y'), Win('Z') } fun main() { fun part1(input: List<String>): Int { return input .map { val (play, response) = it.split(" ") play to response } .map { (play, response) -> RockPaperScissors.values().find { it.play == play.single() }!! to RockPaperScissors.values() .find { it.response == response.single() }!! }.sumOf { (play, response) -> val drawScore = if (play == response) 3 else 0 val winnerScore = if (RockPaperScissors.winners[play] == response) 6 else 0 response.score + drawScore + winnerScore } } fun part2(input: List<String>): Int { return input .map { val (play, response) = it.split(" ") play to response } .map { (play, response) -> val enumPlay = RockPaperScissors.values().find { it.play == play.single() }!! val correspondingResponse = when (RoundResult.values().find { it.c == response.single() }!!) { RoundResult.Lose -> RockPaperScissors.winners[RockPaperScissors.winners[enumPlay]]!! RoundResult.Draw -> enumPlay RoundResult.Win -> RockPaperScissors.winners[enumPlay]!! } enumPlay to correspondingResponse }.sumOf { (play, response) -> val drawScore = if (play == response) 3 else 0 val winnerScore = if (RockPaperScissors.winners[play] == response) 6 else 0 response.score + drawScore + winnerScore } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
685ce47586b6d5cea30dc92f4a8e55e688005d7c
2,342
advent-of-code-2022
Apache License 2.0
advent-of-code-2023/src/Day03.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
private typealias EngineSchematic = List<CharArray> private const val DAY = "Day03" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 4361 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 467835 measureAnswer { part2(input()) } } } private fun part1(input: EngineSchematic): Int { return input.sumIf(predicate = { !it.isDigit() && it != '.' }) { row, col -> input.findNeighborNumbers(row, col).sum() } } private fun part2(input: EngineSchematic): Int { return input.sumIf(predicate = { it == '*' }) { row, col -> val numbers = input.findNeighborNumbers(row, col) if (numbers.size == 2) numbers[0] * numbers[1] else 0 } } private fun EngineSchematic.sumIf( predicate: (char: Char) -> Boolean, selector: (row: Int, col: Int) -> Int, ): Int { var sum = 0 for (row in indices) { for (col in this[row].indices) { if (predicate(this[row][col])) sum += selector(row, col) } } return sum } private fun EngineSchematic.findNeighborNumbers(row: Int, col: Int): List<Int> { return neighborsOf(row, col) .filter { (r, c) -> r in indices && c in first().indices } .map { (r, c) -> this[r].extractNumberAt(c) } .filter { it != 0 } .toList() } private fun neighborsOf(r: Int, c: Int): Sequence<Pair<Int, Int>> = sequenceOf( r - 1 to c - 1, // top left r - 1 to c, // top r - 1 to c + 1, // top right r to c - 1, // left r to c + 1, // right r + 1 to c - 1, // bottom left r + 1 to c, // bottom r + 1 to c + 1, // bottom right ) private fun CharArray.extractNumberAt(index: Int): Int { if (!this[index].isDigit()) return 0 var numberStart = 0 for (i in index downTo 0) { if (this[i].isDigit()) numberStart = i else break } var numberEnd = 0 for (i in index..lastIndex) { if (this[i].isDigit()) numberEnd = i else break } val number = String(sliceArray(numberStart..numberEnd)).toInt() for (i in numberStart..numberEnd) this[i] = '.' return number } private fun readInput(name: String) = readLines(name).map { it.toCharArray() }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,314
advent-of-code
Apache License 2.0
src/day08/Day08.kt
Regiva
573,089,637
false
{"Kotlin": 29453}
package day08 import readLines typealias Forest = List<List<Int>> fun main() { val id = "08" val testOutputPart1 = 21 val testOutputPart2 = 8 val testInput = readTreeHeightMap("day$id/Day${id}_test") println("--- Part 1 ---") println(part1(testInput)) check(part1(testInput) == testOutputPart1) println("--- Part 2 ---") println(part2(testInput)) check(part2(testInput) == testOutputPart2) val input = readTreeHeightMap("day$id/Day$id") println(part1(input)) println(part2(input)) } // Time — O(), Memory — O() fun part1(forest: Forest): Int { val n = forest.size val m = forest.first().size var count = 2 * (n + m - 2) fun Forest.isTreeVisibleByDirection(index: Int, jndex: Int, direction: Directions): Boolean { val treeHeight = this[index][jndex] return generateTreesByDirection(index, jndex, direction).all { treeHeight > it } } for (i in 1 until n - 1) { for (j in 1 until m - 1) { if (Directions.values().any { forest.isTreeVisibleByDirection(i, j, it) }) count++ } } return count } // Time — O(), Memory — O() private fun part2(forest: Forest): Int { var maxScore = 0 fun Forest.countVisibleTreesByDirection(index: Int, jndex: Int, direction: Directions): Int { val treeHeight = this[index][jndex] var count = 0 for (currentTree in generateTreesByDirection(index, jndex, direction)) { count++ if (currentTree >= treeHeight) return count } return count } for (i in 1 until forest.lastIndex) { for (j in 1 until forest.first().lastIndex) { val score = Directions.values() .map { forest.countVisibleTreesByDirection(i, j, it) } .reduce(Int::times) maxScore = maxOf(score, maxScore) } } return maxScore } private fun Forest.generateTreesByDirection(index: Int, jndex: Int, direction: Directions): Sequence<Int> { return generateSequence(direction.next(index to jndex), direction::next) .takeWhile { (i, j) -> i in indices && j in first().indices } .map { (i, j) -> this[i][j] } } fun readTreeHeightMap(fileName: String): Forest { return readLines(fileName).map { it.map(Char::digitToInt) } } private enum class Directions(val verticalChange: Int = 0, val horizontalChange: Int = 0) { Up(verticalChange = -1), Down(verticalChange = +1), Left(horizontalChange = -1), Right(horizontalChange = +1); fun next(coordinates: Pair<Int, Int>): Pair<Int, Int> { val (i, j) = coordinates return (i + verticalChange) to (j + horizontalChange) } }
0
Kotlin
0
0
2d9de95ee18916327f28a3565e68999c061ba810
2,718
advent-of-code-2022
Apache License 2.0
src/poyea/aoc/mmxxii/day23/Day23.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day23 import poyea.aoc.utils.readInput data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) } enum class Direction(val neighbours: (Point) -> Set<Point>, val destination: (Point) -> Point) { EAST( neighbours = { (x, y) -> setOf(Point(x + 1, y - 1), Point(x + 1, y), Point(x + 1, y + 1)) }, destination = { (x, y) -> Point(x + 1, y) } ), SOUTH( neighbours = { (x, y) -> setOf(Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1)) }, destination = { (x, y) -> Point(x, y + 1) } ), WEST( neighbours = { (x, y) -> setOf(Point(x - 1, y - 1), Point(x - 1, y), Point(x - 1, y + 1)) }, destination = { (x, y) -> Point(x - 1, y) } ), NORTH( neighbours = { (x, y) -> setOf(Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1)) }, destination = { (x, y) -> Point(x, y - 1) } ) } data class Grid(val elves: Set<Point>, val directions: List<Direction>) { fun performRound(): Grid { val (nonMovers, movers) = elves.partition { elf -> directions.none { dir -> dir.neighbours(elf).any(elves::contains) } } val propositions = movers.associateWith { elf -> directions .firstOrNull { dir -> dir.neighbours(elf).none(elves::contains) } ?.destination ?.invoke(elf) ?: elf } val validPropositions = propositions.values.groupingBy { it }.eachCount().filter { it.value == 1 }.keys val movedOrLeft = propositions.map { (current, next) -> if (next in validPropositions) next else current } return Grid( elves = nonMovers union movedOrLeft, directions = directions.drop(1) + directions.first() ) } fun countEmptyTiles(): Int { val min = Point(elves.minOf { it.x }, elves.minOf { it.y }) val max = Point(elves.maxOf { it.x }, elves.maxOf { it.y }) val width = max.x - min.x + 1 val height = max.y - min.y + 1 return (width * height) - elves.size } companion object { fun from(input: List<String>): Grid { return Grid( elves = input .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c != '#') null else Point(x, y) } } .toSet(), directions = listOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST) ) } } } fun part1(input: String): Int { return generateSequence(Grid.from(input.lines()), Grid::performRound).elementAt(10).countEmptyTiles() } fun part2(input: String): Int { return generateSequence(Grid.from(input.lines()), Grid::performRound) .zipWithNext() .takeWhile { it.first.elves != it.second.elves } .count() + 1 } fun main() { println(part1(readInput("Day23"))) println(part2(readInput("Day23"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
3,165
aoc-mmxxii
MIT License
y2017/src/main/kotlin/adventofcode/y2017/Day07.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution object Day07 : AdventSolution(2017, 7, "Recursive Circus") { override fun solvePartOne(input: String): String { return findRootProgram(parse(input)).name } override fun solvePartTwo(input: String): String { val rows = parse(input) val root = findRootProgram(rows) val rootProgram = toLinkedProgramTree(rows, root) val unbalancedSequence = generateSequence(rootProgram) { prev -> prev.children.find { it.isUnbalanced } } val parent = unbalancedSequence.last() val expectedWeightOfChildren = parent.children .groupingBy { it.combinedWeight } .eachCount() .entries .find { a -> a.value > 1 } ?.key!! val programWithIncorrectWeight = parent.children .find { it.combinedWeight != expectedWeightOfChildren }!! return (programWithIncorrectWeight.weight + expectedWeightOfChildren - programWithIncorrectWeight.combinedWeight).toString() } private fun parse(input: String) = input .lines() .map { UnlinkedProgram(it) } private fun findRootProgram(programs: List<UnlinkedProgram>) = sequenceOfAncestors(programs.first(), programs).last() private fun sequenceOfAncestors(start: UnlinkedProgram, programs: List<UnlinkedProgram>) = generateSequence(start) { prev -> programs.find { program -> prev.name in program.children } } } //Parsing an input row to a program description. No linking between rows private data class UnlinkedProgram(val name: String, val weight: Int, val children: List<String>) { constructor(input: String) : this( name = input.substringBefore(" ("), weight = input.substringAfter("(") .substringBefore(")") .toInt(), children = input.substringAfter("-> ", "") .split(", ") .filterNot { it.isBlank() }) } private fun toLinkedProgramTree(programs: List<UnlinkedProgram>, root: UnlinkedProgram): Program { return Program(root.name, root.weight, root.children.map { childName -> toLinkedProgramTree(programs, programs.find { it.name in childName }!!) }) } private data class Program(val name: String, val weight: Int, val children: List<Program>) { val combinedWeight: Int by lazy { weight + children.sumOf { it.combinedWeight } } val isUnbalanced: Boolean by lazy { children.distinctBy { it.combinedWeight }.size > 1 } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,399
advent-of-code
MIT License
src/Day13.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
import kotlin.math.min class WeirdLists(private val intValue: Int? = null) : Comparable<WeirdLists> { constructor(list: List<WeirdLists>): this(null) { container = list as MutableList<WeirdLists> } var container: MutableList<WeirdLists> = mutableListOf() override fun compareTo(other: WeirdLists): Int { return when { intValue != null && other.intValue != null -> intValue.compareTo(other.intValue) intValue == null && other.intValue == null -> { var i = 0 while (i < min(container.size, other.container.size)) { val compRes = container[i].compareTo(other.container[i]) if (compRes != 0) { return compRes } i++ } return when { container.size == other.container.size -> 0 i == container.size -> -1 else -> 1 } } intValue != null -> WeirdLists(listOf(this)).compareTo(other) else -> this.compareTo(WeirdLists(listOf(other))) } } } fun main() { fun parseThing(line: String, startPos: Int): Pair<WeirdLists, Int> { if (line[startPos].isDigit()) { val lastPos = line.substring(startPos).indexOfFirst { !it.isDigit() } + startPos return Pair(WeirdLists(line.substring(startPos, lastPos).toInt()), lastPos) } if (line[startPos] == '[') { if (line[startPos + 1] == ']') { return Pair(WeirdLists(), startPos + 2) } val root = WeirdLists() val (curVal, nextPos) = parseThing(line, startPos + 1) root.container.add(curVal) var curPos = nextPos while (line[curPos] == ',') { val (newVal, newPos) = parseThing(line, curPos + 1) root.container.add(newVal) curPos = newPos } assert(line[curPos] == ']') return Pair(root, curPos + 1) } error("Weird start") } fun part1(input: List<String>): Int { val groupedLines = input.joinToString("/n").split("/n/n").map { it.split("/n") } .map { (firstLine, secondLine) -> Pair(parseThing(firstLine, 0).first, parseThing(secondLine, 0).first) } return groupedLines.withIndex().filter { (_, pair) -> pair.first < pair.second }.sumOf { it.index + 1} } fun part2(input: List<String>): Int { val flattenedLines = input.joinToString("/n").split("/n/n").map { it.split("/n") }.flatten() .map { line -> parseThing(line, 0).first}.toMutableList() val withTwo = WeirdLists(listOf(WeirdLists(listOf(WeirdLists(2))))) val withSix = WeirdLists(listOf(WeirdLists(listOf(WeirdLists(6))))) flattenedLines.add(withTwo) flattenedLines.add(withSix) flattenedLines.sort() return (flattenedLines.indexOf(withTwo) + 1) * (flattenedLines.indexOf(withSix) + 1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) // println(part1(testInput)) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
3,392
advent-of-kotlin-2022
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day07.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution import java.util.Arrays import java.util.Collections fun main() { Day07.solve() } object Day07 : AdventSolution(2023, 7, "Camel Cards") { override fun solvePartOne(input: String): Long { val hands = input.lines().map { val (hand, bid) = it.split(" ") Hand(hand, bid.toInt()) } return hands.sorted().mapIndexed { i, h -> (i + 1L) * h.bid }.sum() } override fun solvePartTwo(input: String): Long { val hands = input.lines().map { val (hand, bid) = it.split(" ") JokerHand(hand, bid.toInt()) } return hands.sorted().mapIndexed { i, h -> (i + 1L) * h.bid }.sum() } } private open class Hand(str: String, val bid: Int) : Comparable<Hand> { open val cardValues = "23456789TJQKA" val hand: List<Card> by lazy { str.map { Card(it, cardValues) } } open val handType: HandType by lazy { hand.groupingBy { it }.eachCount().values.sorted().let(HandType::fromCardFrequency) } override fun compareTo(other: Hand): Int = compareValuesBy( this, other, { it.handType }, { it.hand[0] }, { it.hand[1] }, { it.hand[2] }, { it.hand[3] }, { it.hand[4] }) } private class JokerHand(str: String, bid: Int) : Hand(str, bid) { override val cardValues = "J23456789TQKA" override val handType: HandType by lazy { val freq = hand.groupingBy { it }.eachCount() val jokers = freq[joker] ?: 0 val other = freq.minus(joker).values.sorted() val best = other.dropLast(1) + ((other.lastOrNull() ?: 0) + jokers) HandType.fromCardFrequency(best) } } private val joker = Card('J', "J23456789TQKA") private enum class HandType(val freq: List<Int>) { HighCard(listOf(1, 1, 1, 1, 1)), OnePair(listOf(1, 1, 1, 2)), TwoPair(listOf(1, 2, 2)), ThreeOfAKind(listOf(1, 1, 3)), FullHouse(listOf(2, 3)), FourOfAKind(listOf(1, 4)), FiveOfAKind(listOf(5)); companion object { fun fromCardFrequency(freq: List<Int>) = HandType.entries.first { freq == it.freq } } } private class Card(card: Char, ordering: String) : Comparable<Card> { private val value = ordering.indexOf(card) override fun compareTo(other: Card): Int = value.compareTo(other.value) override fun equals(other: Any?): Boolean = (other as? Card)?.value == value override fun hashCode() = value.hashCode() }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,531
advent-of-code
MIT License
src/main/kotlin/aoc2020/ex7.kt
noamfree
433,962,392
false
{"Kotlin": 93533}
fun main() { val input = readInputFile("aoc2020/input7") //println(input.lines()[0]) val rawRequirements = input.lines().map { parseLine(it) } val (colorMap, requirements) = createColorMap(rawRequirements) part1(colorMap, requirements) part2(colorMap, requirements) } private fun part2(colorMap: MutableMap<String, Color>, requirements: List<Requirement>) { println(countContainedAndSelf("shiny gold", colorMap, requirements) - 1) } private fun part1(colorMap: MutableMap<String, Color>, requirements: List<Requirement>) { println(findContainersOf("shiny gold", colorMap, requirements).size) } private fun countContainedAndSelf(colorString: String, colorMap: MutableMap<String, Color>, requirements: List<Requirement>): Int { val requirement = requirements.find { it.container.originalString == colorString }!! if (requirement.containedOptions.isEmpty()) return 1 println(requirement) return requirement.containedOptions.sumOf { option -> option.number * countContainedAndSelf(option.color.originalString, colorMap, requirements) } + 1 } private fun findContainersOf(colorString: String, colorMap: MutableMap<String, Color>, requirements: List<Requirement>): Set<String> { var iterStart = setOf<String>(colorString) var iterEnd = findContainersOf(iterStart, requirements) while (iterStart.size != iterEnd.size) { iterStart = iterEnd iterEnd += findContainersOf(iterStart, requirements) } return iterEnd } private fun findContainersOf(contained: Set<String>, requirements: List<Requirement>): Set<String> { return requirements.filter { requirement -> requirement.containedOptions.find { it.color.originalString in contained } != null }.map { it.container.originalString }.toSet() } data class Color(val int: Int, val originalString: String) private fun createColorMap(rawRequirements: List<Pair<String, List<RawContained>>>): Pair<MutableMap<String, Color>, List<Requirement>> { val map = mutableMapOf<String, Color>() val requirements = rawRequirements.mapIndexed { index, requirement -> val containerColor = map.getOrPut(requirement.first) { Color(map.size, requirement.first) } val containedOptions = requirement.second.mapNotNull { rawContained -> if (rawContained == RawContained.EMPTY) return@mapNotNull null val color = map.getOrPut(rawContained.color) { Color(map.size, rawContained.color) } ContainedOption(color, rawContained.number) } Requirement(containerColor, containedOptions, lineInFile = index+1) } return map to requirements } private data class Requirement(val container: Color, val containedOptions: List<ContainedOption>, val lineInFile: Int = 0) { override fun toString(): String { return "line ${lineInFile}: ${container.originalString} contains ${containedOptions.map { "${it.number} ${it.color.originalString}" }.joinToString(", ")}" } } data class ContainedOption(val color: Color, val number: Int) data class RawContained(val color: String, val number: Int) { companion object { val EMPTY = RawContained("", 0) } } fun parseLine(line: String): Pair<String, List<RawContained>> { require(line.last() == '.') val s = line.dropLast(1).split("contain") require(s.size == 2) val container = s[0] val inTheBag = s[1] return getContainerColor(container) to getContainedOptions(inTheBag) } private fun getContainedOptions(containedStrings: String): List<RawContained> { val optionStrings = containedStrings.split(", ") if (optionStrings.isEmpty()) return emptyList() require(optionStrings.first().startsWith("")) val fistOptionCorrected = optionStrings.first().drop(1) return optionStrings.drop(1).map { getContainedOption(it) } + getContainedOption(fistOptionCorrected) } private fun getContainedOption(optionString: String): RawContained { require(!optionString.startsWith(" ")) if (optionString == "no other bags") { return RawContained.EMPTY } val splitted = optionString.split(" ") require(splitted.size == 4) require(splitted[3] == "bag" || splitted[3] == "bags") val number = splitted[0].toInt() val color = "${splitted[1]} ${splitted[2]}" return RawContained(color, number) } private fun getContainerColor(containerString: String): String { require(containerString.endsWith(" bags ")) return containerString.dropLast(6) }
0
Kotlin
0
0
566cbb2ef2caaf77c349822f42153badc36565b7
4,614
AOC-2021
MIT License
src/day03/Day03.kt
gagandeep-io
573,585,563
false
{"Kotlin": 9775}
package day03 import readInput fun main() { fun Char.priority(): Int = when (this) { in 'a'..'z' -> { (this - 'a') + 1 } in 'A'..'Z' -> { (this - 'A') + 27 } else -> { 0 } } fun part1(input: List<String>): Int = input.sumOf { line -> val (firstHalf, secondHalf) = line.trimEnd() val commonItem = firstHalf.toSet() intersect secondHalf.toSet() commonItem.sumOf { it.priority() } } fun part2(input: List<String>): Int = input.chunked(3).map { it.map { str -> str.toSet() }.toList() } .sumOf { it.fold(it.first()) { acc, chars -> acc intersect chars }.sumOf { ch -> ch.priority() } } val inputForPartOne = readInput("day03/Day03_test") println(part1(inputForPartOne)) val inputForPartTwo = readInput("day03/Day03_test_part2") println(part2(inputForPartTwo)) } private fun <E> List<E>.splitInAGroupOf(n: Int): List<List<E>> = this.mapIndexed { index, line -> Pair(index / n, line) }.groupBy({ it.first }) { it.second }.map { it.value } private operator fun String.component1(): String = substring(0, length / 2) private operator fun String.component2(): String = substring(length / 2, length) private infix fun String.common(other: String): Char { val map = IntArray(128) { 0 } this.toCharArray().forEach { map[it.code]++ } return other.first { map[it.code] >= 1 } } private fun List<String>.commonItem(): Char { val map = IntArray(128) { 0 } this.forEachIndexed { index, string -> string.toCharArray().forEach { if (map[it.code] == index) { map[it.code] = index + 1 } } } return map.indexOfFirst { it == size }.toChar() }
0
Kotlin
0
0
952887dd94ccc81c6a8763abade862e2d73ef924
1,770
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc2023/Day02.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import multiplyOf import readInput import java.util.* import kotlin.math.min private enum class Color { RED, GREEN, BLUE } private data class Cube(val amount: Int, val color: Color) private data class Round(val cubes: Set<Cube>) private data class Game(val id: Int, val rounds: List<Round>) { companion object { fun fromString(str: String): Game { val split = str.split(": ") val rounds = split[1].split("; ").map { round -> round.split(", ").map { cubes -> val cubesSplit = cubes.split(" ") Cube(cubesSplit[0].toInt(), Color.valueOf(cubesSplit[1].uppercase(Locale.getDefault()))) }.toSet() }.map { Round(it) } return Game(split[0].replace("Game ", "").toInt(), rounds) } } } object Day02 { fun part1(input: List<String>): Int { // only 12 red cubes, 13 green cubes, and 14 blue cubes val isGamePossible = { game: Game -> game.rounds.all { round -> round.cubes.all { cube -> when (cube.color) { Color.RED -> cube.amount <= 12 Color.GREEN -> cube.amount <= 13 Color.BLUE -> cube.amount <= 14 } } } } return input.map { Game.fromString(it) }.filter { isGamePossible(it) }.sumOf { it.id } } fun part2(input: List<String>): Int { val getMaxAmountOfCubes = { game: Game, color: Color -> game.rounds.flatMap { round -> round.cubes.filter { it.color == color }.map { it.amount } }.max() } val getMinimumSet = { game: Game -> val red = getMaxAmountOfCubes(game, Color.RED) val green = getMaxAmountOfCubes(game, Color.GREEN) val blue = getMaxAmountOfCubes(game, Color.BLUE) setOf(Cube(red, Color.RED), Cube(green, Color.GREEN), Cube(blue, Color.BLUE)) } return input.map { Game.fromString(it) }.map { getMinimumSet(it) }.sumOf { minSet -> minSet.multiplyOf { it.amount } } } } fun main() { val testInput = readInput("Day02_test", 2023) check(Day02.part1(testInput) == 8) check(Day02.part2(testInput) == 2286) val input = readInput("Day02", 2023) println(Day02.part1(input)) println(Day02.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
2,453
adventOfCode
Apache License 2.0
2022/src/main/kotlin/day24.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Graph import utils.Parser import utils.Solution import utils.Vec2i import utils.badInput import utils.mapParser fun main() { Day24.run() } object Day24 : Solution<Pair<Day24.Context, List<Day24.Blizzard>>>() { override val name = "day24" override val parser = Parser { it.trim() }.mapParser(Parser.charGrid).map { grid -> val ctx = Context(Vec2i(0, -1), Vec2i(grid.width - 3, grid.height - 2), grid.width - 2, grid.height - 2) val blizzards = grid.cells.filter { (p, char) -> char in setOf('<', '>', '^', 'v') && p.x in 1 until grid.width - 1 && p.y in 1 until grid.height }.map { (pos, char) -> Blizzard(pos + Vec2i(-1, -1), when (char) { '^' -> Direction.UP 'v' -> Direction.DOWN '<' -> Direction.LEFT '>' -> Direction.RIGHT else -> badInput() }) } ctx to blizzards } enum class Direction(val v: Vec2i) { UP(Vec2i(0, -1)), DOWN(Vec2i(0, 1)), LEFT(Vec2i(-1, 0)), RIGHT(Vec2i(1, 0)), STAY(Vec2i(0, 0)), } data class Blizzard(val pos: Vec2i, val dir: Direction) { fun move(bounds: Vec2i) = Blizzard((pos + dir.v + bounds) % bounds, dir) } data class State(val pos: Vec2i, val blizzards: List<Blizzard>) data class Context(val startPos: Vec2i, val endPos: Vec2i, val width: Int, val height: Int) override fun part1(input: Pair<Context, List<Blizzard>>): Int { val ctx = input.first val graph = makeGraph(ctx) val initialState = State(ctx.startPos, input.second) return graph.shortestPath(initialState) { it.pos == ctx.endPos }.first } override fun part2(input: Pair<Context, List<Blizzard>>): Int { val ctx = input.first val graph = makeGraph(ctx) val initialState = State(ctx.startPos, input.second) val pt1 = graph.shortestPath(initialState) { it.pos == ctx.endPos } val pt2 = graph.shortestPath(pt1.second) { it.pos == ctx.startPos } val pt3 = graph.shortestPath(pt2.second) { it.pos == ctx.endPos } return pt1.first + pt2.first + pt3.first } private fun makeGraph(ctx: Context): Graph<State, Unit> { val bounds = Vec2i(ctx.width, ctx.height) val graph = Graph<State, Unit>( edgeFn = { state -> // move blizzards by 1 val newBlizzards = state.blizzards.map { b -> b.move(bounds) } val blizzCoords = newBlizzards.map { it.pos }.toSet() // try out all possible moves Direction.values().map { state.pos + it.v } .filter { pos -> // must be in bounds or start/end pos == ctx.startPos || pos == ctx.endPos || (pos.x in 0 until ctx.width && pos.y in 0 until ctx.height) } .filter { pos -> // cannot be occupied by blizzard pos !in blizzCoords } .map { pos -> Unit to State(pos, newBlizzards) } } ) return graph } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,902
aoc_kotlin
MIT License
advent-of-code-2022/src/Day16.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import kotlin.math.abs fun main() { val testInput = readInput("Day16_test") val input = readInput("Day16") "Part 1" { part1(testInput) shouldBe 1651 measureAnswer { part1(input) } } "Part 2" { part2(testInput) shouldBe 1707 measureAnswer { part2(input) } } } private fun part1(input: Map<String, Valve>): Int { val valvesToOpen = input.valuableValves() return input.maxRate("AA", timeLeft = 30, valvesToOpen) } private fun part2(input: Map<String, Valve>): Int { val valvesToOpen = input.valuableValves() fun combinations(size: Int): Sequence<Set<String>> { if (size == 1) return sequenceOf(setOf(valvesToOpen.first())) return sequence { for (combination in combinations(size - 1)) { for (add in valvesToOpen - combination) { yield(combination + add) } } } } // This can be optimized. Current values: // - 10 combinations for test input (answer at 4th combination) // - 3003 combinations for my input (answer at 259th combination) val combinations = combinations(valvesToOpen.size / 2).associateWith { valvesToOpen - it } println("Total: ${combinations.size}") val sharedMem = mutableMapOf<List<Any>, Int>() var count = 0 var currentMax = 0 return combinations .maxOf { (myValves, elephantValves) -> val myRate = input.maxRate("AA", timeLeft = 26, myValves, sharedMem) val elephantRate = input.maxRate("AA", timeLeft = 26, elephantValves, sharedMem) (myRate + elephantRate).also { value -> currentMax = maxOf(currentMax, value) println("${++count}: $myValves $elephantValves -> $value ($currentMax)") } } } // Returns valves with non-zero rate private fun Map<String, Valve>.valuableValves(): Set<String> = values.asSequence().filter { it.rate != 0 }.map { it.name }.toSet() private fun Map<String, Valve>.maxRate( current: String, timeLeft: Int, closed: Set<String>, mem: MutableMap<List<Any>, Int> = mutableMapOf(), ): Int { if (timeLeft <= 2 || closed.isEmpty()) return 0 return mem.getOrPut(listOf(current, timeLeft, closed)) { val valve = getValue(current) val ifKeepAsIs = valve.next.maxOf { maxRate(it, timeLeft - 1, closed, mem) } val ifOpen = if (valve.rate != 0 && current in closed) { val timeAfterOpen = timeLeft - 1 (valve.rate * timeAfterOpen) + valve.next.maxOf { maxRate(it, timeAfterOpen - 1, closed - current, mem) } } else { 0 } maxOf(ifKeepAsIs, ifOpen) } } // === Input reading === private val regex = Regex("^Valve (..) has flow rate=(\\d+); tunnels? leads? to valves? (.+)$") private fun readInput(name: String) = buildMap { for (line in readLines(name)) { val (source, rate, destinations) = regex.matchEntire(line)!!.destructured put(source, Valve(source, rate.toInt(), destinations.splitToSequence(", ").toSet())) } } private data class Valve(val name: String, val rate: Int, val next: Set<String>)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
3,207
advent-of-code
Apache License 2.0
src/day08/Day08.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day08 import readInput fun main() { fun part1(input: List<String>): Int { val intInput = input.map { row -> row.map { it.toString().toInt() } } val forest = createForest(intInput) return forest.flatten().count { it.visible() } } fun part2(input: List<String>): Int { val intInput = input.map { row -> row.map { it.toString().toInt() } } val forest = createForest(intInput) return forest.flatten().maxOf { it.scenicScore() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") println("test part1: ${part1(testInput)}") println("result part1: ${part1(input)}") println("test part2: ${part2(testInput)}") println("result part2: ${part2(input)}") } fun createForest(input: List<List<Int>>): List<List<Tree>> { return List(input.size) { row -> List(input[0].size) { col -> val treeRow = input[row] val treeCol = input.map { it[col] } Tree( treeRow[col], mapOf( Direction.UP to treeCol.slice(0 until row).reversed(), Direction.DOWN to treeCol.slice(row + 1 until treeCol.size), Direction.LEFT to treeRow.slice(0 until col).reversed(), Direction.RIGHT to treeRow.slice(col + 1 until treeRow.size) ) ) } } } enum class Direction { UP, DOWN, LEFT, RIGHT } data class Tree(val size: Int, val directionMap: Map<Direction, List<Int>>) { fun visible(): Boolean { return directionMap.values.any { it.isEmpty() } || directionMap.values.any { list -> list.all { size > it } } } fun scenicScore(): Int { return directionMap.values.map { trees -> val view = trees.takeWhile { size > it }.count() if (view == trees.size) view else view + 1 } .fold(1) { acc, it -> acc * it } } }
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
2,029
advent-of-code-22
Apache License 2.0
src/Day15.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
import java.awt.Point import kotlin.math.abs fun main() { data class Sensor(val pos: Point, val beacon: Point) { val xDistance = abs(beacon.x - pos.x) val yDistance = abs(beacon.y - pos.y) fun abscessesCoveredAt(y: Int): Set<Int> { val evaluationYDistance = abs(y - pos.y) val xSemiLength = xDistance + (yDistance - evaluationYDistance) return ((pos.x - xSemiLength)..(pos.x + xSemiLength)).toSet() } fun abscessesCoveredAt(y: Int, maxSearch: Int): IntRange? { val evaluationYDistance = abs(y - pos.y) val xSemiLength = xDistance + yDistance - evaluationYDistance if (xSemiLength < 0) return null return maxOf(0, pos.x - xSemiLength)..minOf(maxSearch, pos.x + xSemiLength) } } val sensorPattern = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") fun part1(input: List<String>, y: Int): Int { return input.map { val (sensorX, sensorY, beaconX, beaconY) = sensorPattern.find(it)!!.destructured Sensor(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt())) }.fold(setOf<Int>()) { points, sensor -> points.plus(sensor.abscessesCoveredAt(y)) }.size - 1 } fun part2(input: List<String>, maxSearch: Int): Long { val sensors = input.map { val (sensorX, sensorY, beaconX, beaconY) = sensorPattern.find(it)!!.destructured Sensor(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt())) } return (0..maxSearch).asSequence().map { y -> sensors.fold(listOf<IntRange>()) { listOfRanges, sensor -> val range = sensor.abscessesCoveredAt(y, maxSearch) ?: return@fold listOfRanges val (includes, doesNotInclude) = listOfRanges.partition { r -> r.contains(range.first) || r.contains(range.last) || range.contains(r.first) || range.contains(r.last) } doesNotInclude + listOf(includes.let { inc -> if (inc.isEmpty()) range else minOf(range.first, inc.minOf { it.first })..maxOf(range.last, inc.maxOf { it.last }) }) } }.withIndex().first { it.value.size > 1 }.let { val x = (if (it.value[0].first < it.value[1].first) it.value[0].last else it.value[1].last) + 1 println("y=${it.index} + x=$x * 4000000 = ${it.index + Math.multiplyExact(x.toLong(), 4000000L)}") Math.addExact(it.index.toLong(), Math.multiplyExact(x.toLong(), 4000000L)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("resources/Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
3,054
advent_of_code_2022
Apache License 2.0
src/Day16.kt
felldo
572,233,925
false
{"Kotlin": 76496}
private fun dijkstra(grid: Map<String, Pair<Int, List<String>>>, from: String): Map<String, Int> { val distances = grid.asSequence().map { it.key to Int.MAX_VALUE }.toMap().toMutableMap() val used = mutableSetOf<String>() distances[from] = 0 for (iteration in 0 until grid.size) { val v = distances.asSequence().filter { it.key !in used }.minBy { it.value }.key if (distances[v] == Int.MAX_VALUE) break used += v grid[v]!!.second.forEach { distances[it] = minOf(distances[it]!!, distances[v]!! + 1) } } return distances } private fun part1(flows: Map<String, Int>, dijkstras: Map<String, Map<String, Int>>): Int { fun weightedDepthFirstSearch( flows: Map<String, Int>, dijkstras: Map<String, Map<String, Int>>, currentVertex: String, iterateLimit: Int, currentWeight: Int = 0, used: MutableSet<String> = mutableSetOf(), ): Int { if (currentVertex in used || used.size == flows.size || iterateLimit <= 0) return currentWeight used += currentVertex val result = dijkstras[currentVertex]!!.maxOf { (vertex, path) -> weightedDepthFirstSearch( flows, dijkstras, vertex, iterateLimit - path - 1, currentWeight + (flows[currentVertex] ?: 0) * iterateLimit, used, ) } used -= currentVertex return result } return weightedDepthFirstSearch(flows, dijkstras, "AA", 30) } fun <T> Pair<T, T>.map(first: Boolean, value: T) = if (first) copy(first = value) else copy(second = value) fun <T> Pair<T, T>.get(first: Boolean) = if (first) this.first else second fun main() { val graph = buildMap { readInput("Day16") .toMutableList() .map { val (from, flow, tos) = """Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? (.*)""".toRegex() .matchEntire(it)!! .destructured this[from] = flow.toInt() to tos.split(", ") } } val flows = graph.asSequence().filter { it.value.first != 0 }.map { it.key to it.value.first }.toMap() val dijkstras = graph.asSequence() .filter { it.key in flows || it.key == "AA" } .map { (vertex, _) -> vertex to dijkstra(graph, vertex).filterKeys { it in flows } } .toMap() println(part1(flows, dijkstras)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
2,482
advent-of-code-kotlin-2022
Apache License 2.0
src/day16/a/day16a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day16.a import readInputLines import shouldBe import util.Graph import java.util.regex.Pattern import kotlin.math.max fun main() { val graph = simplifyGraph(read()) var best = 0 fun step(v: Valve, t: Int, sum: Int) { for (vtx in graph[v.key]!!.connected) { val len = vtx.distanceFrom(v.key) val dst = vtx.other(v.key).value if (!dst.used && dst.rate != 0) { if (t + 1 + len < 30) { dst.used = true val s = sum + (30 - t - len) * dst.rate best = max(best, s) step(dst, t + 1 + len, s) dst.used = false } } } } val start = graph["AA"]!!.value step(start, 1, 0) shouldBe(2250, best) } /** * Many Valves have rate == 0, and these are eliminated from the graph. * Only the "AA" Valve is preserved, but the 'used' flag is set such that it will be ignored. * Every remaining Valve will be connected with every other Valve by a vertex with as its length * the shortest distance that can be found by traveling the original graph. * In the subsequent search, this will prevent repeatedly evaluating the same Valve order through suboptimal paths. */ fun simplifyGraph(graph: Graph<String, Valve>): Graph<String, Valve> { val simplified = Graph<String, Valve>() graph.nodes() .filter { it.value.rate != 0 || it.key == "AA" } .forEach { simplified.add(it.key, it.value) } simplified.nodes().toList().let { list -> for ((i, a) in list.withIndex()) { val d = graph.calculateLeastDistanceTable(a.key) for (b in list.subList(i + 1, list.size)) { val p = d[b.key]!! simplified.connect(a.key, b.key, p) } } } simplified["AA"]!!.value.used = true return simplified } class Valve( val key: String, val rate: Int, ) { override fun toString(): String { return key } var used = false } fun read(): Graph<String, Valve> { val g = Graph<String, Valve>() val connectTo = HashMap<String, ArrayList<String>>() readInputLines(16).forEach { line -> val fr = line.split(Pattern.compile("[^0-9]+")).filter { it.isNotBlank() }[0].toInt() val va = line.substring(1).split(Pattern.compile("[^A-Z]")).filter { it.isNotBlank() } val valve = Valve(va[0], fr) g.add(valve.key, valve) connectTo[valve.key] = ArrayList(va.subList(1, va.size)) } g.nodes().forEach { a -> for (k in connectTo[a.key]!!) { val b = g[k]!! g.connect(a.key, b.key, 1) } } return g }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,712
advent-of-code-2022
Apache License 2.0
src/Day08.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
fun main() { fun isVisible(row: Int, col: Int, height: Int, forest: List<String>): Boolean = when { // Outter trees are always visible (col == 0 || col == forest[row].lastIndex || row == 0 || row == forest.lastIndex) -> true // Visible from Left forest[row].subSequence(0 until col).map(Char::digitToInt).all { it < height } -> true // Visible from right (col < forest[row].lastIndex && forest[row].subSequence(col + 1..forest[row].lastIndex).map(Char::digitToInt) .all { it < height }) -> true // Visible from top (0 until row).toList().map { forest[it][col].digitToInt() }.all { it < height } -> true // Visible from bottom (row < forest.lastIndex && (row + 1..forest.lastIndex).toList().map { forest[it][col].digitToInt() }.all { it < height }) -> true else -> false } fun List<Int>.canopy(height: Int): List<Int> = slice(0..if (indexOfFirst { it >= height } > -1) indexOfFirst { it >= height } else lastIndex) fun treeScore(row: Int, col: Int, height: Int, forest: List<String>): Int { if (col == 0 || col == forest[row].lastIndex || row == 0 || row == forest.lastIndex) return 0 return forest[row].subSequence(0 until col).reversed().map(Char::digitToInt).canopy(height).count() * forest[row].subSequence(col + 1..forest[row].lastIndex).map(Char::digitToInt).canopy(height).count() * (0 until row).toList().reversed().map { forest[it][col].digitToInt() }.canopy(height).count() * (row + 1..forest.lastIndex).toList().map { forest[it][col].digitToInt() }.canopy(height).count() } fun part1(input: List<String>): Int = input.foldIndexed(0) { rowIndex, rowAccumulator, cur -> cur.foldIndexed(rowAccumulator) { colIndex, acc, tree -> if (isVisible(rowIndex, colIndex, tree.digitToInt(), input)) acc + 1 else acc } } fun part2(input: List<String>): Int = input.mapIndexed { rowIndex, cur -> cur.mapIndexed { colIndex, tree -> treeScore(rowIndex, colIndex, tree.digitToInt(), input) }.max() }.max() // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
2,531
aoc-2022-demo
Apache License 2.0
src/year2021/Day14.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = parseInput(readLines("2021", "day14").filter { it != "" }) val testInput = parseInput(readLines("2021", "day14_test").filter { it != "" }) check(part1(testInput) == 1588L) println("Part 1:" + part1(input)) check(part2(testInput) == 2188189693529L) println("Part 2:" + part2(input)) } private fun parseInput(lines: List<String>): Day14Input { val template = (0..lines.first().length - 2) .map { "${lines.first()[it]}${lines.first()[it + 1]}" } .groupBy { it } .map { Pair(it.value.first(), it.value.size.toLong()) } .toMap() val rules = lines .drop(1) .map { it.split(" -> ") } .associate { Pair(it[0], it[1]) } return Day14Input(template, rules) } private fun part1(input: Day14Input): Long { return solveExtendedPolymerization(input, 10) } private fun part2(input: Day14Input): Long { return solveExtendedPolymerization(input, 40) } private fun solveExtendedPolymerization( input: Day14Input, steps: Int, ): Long { var current = input.template.toMutableMap() repeat(steps) { val next = mutableMapOf<String, Long>() for ((key, value) in current) { if (input.rules[key] != null) { val first = "${key[0]}${input.rules[key]}" val second = "${input.rules[key]}${key[1]}" next[first] = next.getOrDefault(first, 0) + value next[second] = next.getOrDefault(second, 0) + value } else { next[key] = next.getOrDefault(key, 0) + value } } current = next } val occurrences = current .flatMap { (key, value) -> listOf(Pair(key[0], value), Pair(key[1], value)) } .groupBy { it.first } .map { (it.value.sumOf { it.second } + 1) / 2 } return occurrences.maxOf { it } - occurrences.minOf { it } } data class Day14Input(val template: Map<String, Long>, val rules: Map<String, String>)
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
2,102
advent_of_code
MIT License
src/day18/Day18.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day18 import utils.* val NEIGHBOR_OFFSETS = listOf( Voxel(1, 0, 0), Voxel(0, 1, 0), Voxel(0, 0, 1), Voxel(-1, 0, 0), Voxel(0, -1, 0), Voxel(0, 0, -1) ) data class Voxel(val x: Int, val y: Int, val z: Int) { val neighbors get() = NEIGHBOR_OFFSETS.map { dir -> this + dir } operator fun plus(other: Voxel): Voxel = Voxel(x + other.x, y + other.y, z + other.z) operator fun minus(other: Voxel): Voxel = Voxel(x - other.x, y - other.y, z - other.z) override operator fun equals(other: Any?): Boolean = other is Voxel && other.x == x && other.y == y && other.z == z override fun hashCode(): Int = (x * 31 + y) * 31 + z fun isInCuboid(start: Voxel, end: Voxel): Boolean = x in start.x..end.x && y in start.y..end.y && z in start.z..end.z fun minCoords(other: Voxel): Voxel = Voxel( minOf(x, other.x), minOf(y, other.y), minOf(z, other.z) ) fun maxCoords(other: Voxel): Voxel = Voxel( maxOf(x, other.x), maxOf(y, other.y), maxOf(z, other.z) ) } fun parseVoxels(input: List<String>): Set<Voxel> = input .map { line -> val (x, y, z) = line.split(",").map(String::toInt) Voxel(x, y ,z) } .toSet() fun part1(input: List<String>): Int { val voxels = parseVoxels(input) return voxels.sumOf { voxel -> voxel.neighbors.count { it !in voxels } } } fun floodFill(voxels: Set<Voxel>, start: Voxel, end: Voxel): Int { val visited = (voxels + start).toMutableSet() var count = 0 generateSequence(setOf(start)) { stack -> stack .flatMap { voxel -> voxel.neighbors } .filter { it.isInCuboid(start, end) && it !in visited } .toSet() .onEach { voxel -> count += voxel.neighbors.count { it in voxels } visited.add(voxel) } }.find { it.isEmpty() } return count } fun part2(input: List<String>): Int { val voxels = parseVoxels(input) val min = voxels.reduce { acc, next -> acc.minCoords(next) } val max = voxels.reduce { acc, next -> acc.maxCoords(next) } return floodFill(voxels, min - Voxel(1, 1, 1), max + Voxel(1, 1, 1)) } fun main() { val testInput = readInput("Day18_test") expect(part1(testInput), 64) expect(part2(testInput), 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
2,646
AOC-2022-Kotlin
Apache License 2.0
src/Day08.kt
slawa4s
573,050,411
false
{"Kotlin": 20679}
fun main() { fun getColumn(matrix: List<List<Int>>, col: Int) = List(matrix.size) { matrix[it][col] } fun getRow(matrix: List<List<Int>>, row: Int) = matrix[row] fun isVisible(treeGrid: List<List<Int>>, i: Int, j: Int): Boolean { val element = treeGrid[i][j] return i == 0 || j == 0 || i == treeGrid.lastIndex || j == treeGrid.lastIndex || getRow(treeGrid, i).slice(0 until j).max() < element || getRow(treeGrid, i).slice(j + 1 until treeGrid.size).max() < element || getColumn(treeGrid, j).slice(0 until i).max() < element || getColumn(treeGrid, j).slice(i + 1 until treeGrid.size).max() < element } fun getScorePerLine(element: Int, line: List<Int>): Int { val getLessTrees = line.takeWhile { it < element }.count() return getLessTrees + if (getLessTrees == line.size) 0 else 1 } fun getScenicScore(treeGrid: List<List<Int>>, i: Int, j: Int): Int { val element = treeGrid[i][j] return getScorePerLine(element, getRow(treeGrid, i).slice(0 until j).reversed()) * getScorePerLine(element, getRow(treeGrid, i).slice(j + 1 until treeGrid.size)) * getScorePerLine(element, getColumn(treeGrid, j).slice(0 until i).reversed()) * getScorePerLine(element, getColumn(treeGrid, j).slice(i + 1 until treeGrid.size)) } fun getGridOFTrees(input: List<String>): List<List<Int>> = input .map { line -> line.map{ Integer.parseInt(it.toString()) } } val treeGrid = getGridOFTrees(readInput("Day08")) fun part1(treeGrid: List<List<Int>>): Int = treeGrid.mapIndexed { indexRow, line -> List(line.size) { indexCol -> if (isVisible(treeGrid, indexRow, indexCol)) 1 else 0 } }.flatten().sum() fun part2(treeGrid: List<List<Int>>): Int = treeGrid.mapIndexed { indexRow, line -> List(line.size) { indexCol -> getScenicScore(treeGrid, indexRow, indexCol) } }.flatten().max() println(part1(treeGrid)) println(part2(treeGrid)) }
0
Kotlin
0
0
cd8bbbb3a710dc542c2832959a6a03a0d2516866
2,092
aoc-2022-in-kotlin
Apache License 2.0
src/Day15.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
import kotlin.math.abs import kotlin.math.max /** * [Day15](https://adventofcode.com/2022/day/15) */ private class Day15 { data class Point(val x: Int, val y: Int) } fun main() { fun toDetects(input: List<String>): List<Pair<Day15.Point, Day15.Point>> = input.map { line -> """Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""" .toRegex().find(line)!!.groupValues.let { (_, sx, sy, bx, by) -> Day15.Point(sx.toInt(), sy.toInt()) to Day15.Point(bx.toInt(), by.toInt()) } } fun mergeRange(ranges: List<IntRange>): List<IntRange> { // [0].first <= [1].first <= ... var left = ranges.sortedBy(IntRange::first) val group = mutableListOf<IntRange>() while (left.isNotEmpty()) { var base = left.first() val sub = left.takeWhile { when { // base.first <= it.first must be true because ranges sorted by first // if 'it' and base is cross, first of 'it' should be smaller than or equal to last of 'base' it.first <= base.last -> { base = base.first..max(base.last, it.last) true } else -> false } } group.add(base) left = left.subList(sub.size, left.size) } return group } fun calcCoveredRanges(detects: List<Pair<Day15.Point, Day15.Point>>, targetRow: Int): List<IntRange> { val ranges = detects.map { (sensor, beacon) -> val distance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y) val rem = distance - abs(sensor.y - targetRow) (sensor.x - rem..sensor.x + rem) }.filterNot(IntRange::isEmpty) return mergeRange(ranges) } fun part1(input: List<String>, targetRow: Int): Int { val detects = toDetects(input) val coveredRanges = calcCoveredRanges(detects, targetRow) val overlaps = detects.flatMap(Pair<Day15.Point, Day15.Point>::toList).toSet().count { p -> p.y == targetRow && coveredRanges.any { it.contains(p.x) } } return coveredRanges.sumOf(IntRange::count) - overlaps } fun part2(input: List<String>): Long { val detects = toDetects(input) val (sMinX, sMaxX, sMinY, sMaxY) = detects.map(Pair<Day15.Point, Day15.Point>::first).let { list -> val (minX, maxX) = list.map(Day15.Point::x).let { it.min() to it.max() } val (minY, maxY) = list.map(Day15.Point::y).let { it.min() to it.max() } listOf(minX, maxX, minY, maxY) } for (y in sMinY..sMaxY) { val coveredRanges = calcCoveredRanges(detects, y) if (!coveredRanges.any { it.first <= sMinX && sMaxX <= it.last }) { val x = coveredRanges[1].first - 1 return x.toLong() * 4_000_000L + y.toLong() } } return -1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput) == 56_000_011L) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input)) }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
3,344
aoc-in-kotlin-2022
Apache License 2.0
src/Day13.kt
juliantoledo
570,579,626
false
{"Kotlin": 34375}
interface Packets {} class PacketList(val packets: List<Packets>): Packets {} class PacketItem(val packets: Int) : Packets {} fun compare(p1: Packets, p2: Packets): Int { return when { p1 is PacketItem && p2 is PacketItem -> (p1.packets.compareTo(p2.packets)) p1 is PacketList && p2 is PacketList -> compare(p1, p2) p1 is PacketList && p2 is PacketItem -> compare(p1, PacketList(listOf(p2))) p1 is PacketItem && p2 is PacketList -> compare(PacketList(listOf(p1)), p2) else -> throw Exception("Error comparing Packets") } } fun compare(p1: PacketList, p2: PacketList): Int { val pairs = p1.packets.zip(p2.packets) for ((pl1, pl2) in pairs) { val res = compare(pl1, pl2) if (res != 0) return res } return p1.packets.size.compareTo(p2.packets.size) } fun parse(string: String): Packets? { if (string.isEmpty()) return null if (string[0].isDigit()) return PacketItem(string.toInt()) var bracketCount = 0 var lastComma = 0 val packets = mutableListOf<Packets?>() string.forEachIndexed { index, value -> if (value == '[') bracketCount++ if (value == ']') { bracketCount-- if (bracketCount == 0) packets += parse(string.take(index).drop(lastComma + 1)) } if (value == ',') { if (bracketCount == 1) { packets += parse(string.take(index).drop(lastComma + 1)) lastComma = index } } } return PacketList(packets.filterNotNull()) } fun main() { fun solve(input: List<String>): Int { var packets: MutableList<Packets?> = input.filter { it.isNotEmpty() }.map { parse(it) } as MutableList<Packets?> // Part 1 val total = packets.chunked(2).mapIndexed { index, pair -> if (compare(pair.first()!!, pair.last()!!) < 0) index + 1 else 0 }.sum() // Part 2 val divider1 = parse("[[2]]") val divider2 = parse("[[6]]") packets.add(divider1) packets.add(divider2) val sorted = packets.sortedWith { p1, p2 -> compare(p1!!, p2!!) } val second = (sorted.indexOf(divider1) + 1) * (sorted.indexOf(divider2) + 1) println("Part2: $second") return total } var test = solve(readInput("Day13_test")) println("Test1: $test") check(test == 13) val first = solve(readInput("Day13_input")) println("Part1: $first") }
0
Kotlin
0
0
0b9af1c79b4ef14c64e9a949508af53358335f43
2,464
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
fun main() { fun toRightFrom(input: List<String>, i: Int, j: Int) = (j + 1 until input[0].length).map { input[i][it] } fun toLeftFrom(input: List<String>, i: Int, j: Int) = (j - 1 downTo 0).map { input[i][it] } fun toDownFrom(input: List<String>, i: Int, j: Int) = (i + 1 until input.size).map { input[it][j] } fun toUpFrom(input: List<String>, i: Int, j: Int) = (i - 1 downTo 0).map { input[it][j] } fun part1(input: List<String>): Int { return input.withIndex().sumOf { (i, line) -> line.withIndex().count { (j, char) -> toRightFrom(input, i, j).all { it < char } || toLeftFrom(input, i, j).all { it < char } || toDownFrom(input, i, j).all { it < char } || toUpFrom(input, i, j).all { it < char } } } } fun <E> lenOfSuccessfulPrefix(list: List<E>, predicate: (E) -> Boolean): Int { return (list.indexOfFirst {!predicate(it)}.takeIf {it >= 0}?.inc() ?: list.size) } fun part2(input: List<String>): Int { return input.withIndex().maxOf { (i, line) -> line.withIndex().maxOf { (j, char) -> lenOfSuccessfulPrefix(toRightFrom(input, i, j)) { it < char } * lenOfSuccessfulPrefix(toLeftFrom(input, i, j)) { it < char } * lenOfSuccessfulPrefix(toDownFrom(input, i, j)) { it < char } * lenOfSuccessfulPrefix(toUpFrom(input, i, j)) { it < char } } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
1,778
advent-of-kotlin-2022
Apache License 2.0
src/Day16.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
data class Day16Valve(val name: String, val rate: Int, val connections: List<String>) { val distanceMap = mutableMapOf<String, Int>() fun computeDistances(nodes: List<Day16Valve>) = apply { distanceMap[name] = 0 ArrayDeque<Day16Valve>().let { queue -> queue.add(this) val visited = mutableSetOf<String>() while (queue.isNotEmpty()) { val current = queue.removeFirst() val distance = current.distanceMap[name]!! visited.add(current.name) current.connections.filter { it !in visited }.forEach { n -> val neighbor = nodes.first { it.name == n } neighbor.distanceMap[name] = distance + 1 queue.addLast(neighbor) } } } distanceMap.remove(name) } companion object { val parseRegex = """Valve (?<name>[A-Z]+) has flow rate=(?<rate>[0-9]+); tunnels* leads* to valves* (?<connections>.+)""".toRegex() fun loadValves(input: List<String>): List<Day16Valve> = input.mapNotNull { line-> parseRegex.matchEntire(line)?.let { r -> val groups = r.groups as MatchNamedGroupCollection Day16Valve( groups["name"]!!.value, groups["rate"]!!.value.toInt(), groups["connections"]!!.value.split(",").map { it.trim() }) } } } } fun main() { fun List<Day16Valve>.computeAllDistances(): List<Day16Valve> { filter { it.rate > 0 } .forEach { rated -> rated.computeDistances(this) } return this } fun Day16Valve.remaining(opened: Set<String>, timeLeft: Int) = distanceMap.filter { (key, timeNeeded) -> key !in opened && timeNeeded + 1 <= timeLeft } fun List<Day16Valve>.highestPath( opened: Set<String>, node: String, minutesLeft: Int, sum: Int, open: Int ): Pair<Int, List<String>> { val curNode = this.first { it.name == node } return when { minutesLeft < 0 -> Pair(0, emptyList()) minutesLeft == 0 -> Pair(sum, emptyList()) minutesLeft == 1 -> Pair(sum + open, emptyList()) curNode.distanceMap.all { (key, _) -> key in opened } -> Pair(sum + minutesLeft * open, emptyList()) else -> curNode.remaining(opened, minutesLeft) .map { (nNode, distance) -> highestPath( opened + node, nNode, minutesLeft - (distance + 1), sum + (distance + 1) * open, open + this.first { it.name == nNode }.rate ).let{ Pair(it.first,listOf(nNode)+it.second) } }.plus( Pair(sum + minutesLeft * open, emptyList()) ) .maxBy{it.first} } } fun part1(input: List<String>): Int = Day16Valve.loadValves(input) .computeAllDistances() .highestPath(emptySet(), "AA", 30, 0, 0).let{ println(it.second) it.first } fun part2(input: List<String>): Int = 0 // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 0) println("checked") val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
3,672
aoc-2022-demo
Apache License 2.0
src/main/kotlin/Day07.kt
alex859
573,174,372
false
{"Kotlin": 80552}
fun main() { val testInput = readInput("Day07_test.txt") check(testInput.result() == 95437) check(testInput.result2() == 24933642) val input = readInput("Day07.txt") println(input.result()) println(input.result2()) } fun String.result(): Int { return readCommandsAsStrings().directories().sizes().values.filter { it <= 100000 }.sum() } fun String.result2(): Int { val directories = readCommandsAsStrings().directories() val values = directories.sizes().values val sizeOfOuterMost = directories.sizes()["/"] ?: error("cannot find root") val freeSpace = 70000000 - sizeOfOuterMost val spaceToFree = 30000000 - freeSpace return values .filter { it >= spaceToFree } .min() } fun Map<String, Int>.sizes(): Map<String, Int> { val allDirectories = keys return allDirectories.associateWith { filter { (key, _) -> key.startsWith(it) }.map { (_, value) -> value }.sum() } } fun Map<String, Int>.spaceToFree(): Int = 30000000 - freeSpace(total = 70000000) fun Map<String, Int>.freeSpace(total: Int): Int = total - (this["/"]?: error("cannot find root")) fun List<Command>.sizeOf(dir: String): Int { return chunked(2).map { (cd, ls) -> when (cd) { is ChangeDir -> when (ls) { is ListDir -> cd.dir to ls else -> TODO("expecting $ls to be ListDir") } else -> TODO("expecting $cd to be ChangeDir") } }.filter { (myDir, _) -> myDir == dir } .map { (_, ls) -> ls.size } .first() } fun List<Command>.directories(): MutableMap<String, Int> { val directories = mutableMapOf<String, Int>() var currentDirectory = "" forEach { command -> when (command) { is ChangeDir -> { currentDirectory = currentDirectory.change(command.dir) } is ListDir -> { directories += currentDirectory to command.size } } } return directories } private fun String.change(dir: String): String = when (dir) { "/" -> "/" ".." -> split("/").toList().dropLast(1).joinToString("/") else -> this + (if (this == "/") dir else "/$dir") } internal fun String.readCommandsAsStrings() = split("$ ") .map { it.trim() } .filter { it.isNotEmpty() } .map { it.readCommand() } fun String.readCommand(): Command { return if (startsWith("cd")) { val (_, dir) = split(" ") ChangeDir(dir) } else if (startsWith("ls")) { ListDir(lines().drop(1)) } else { TODO() } } sealed interface Command data class ChangeDir(val dir: String): Command data class ListDir(val files: List<String>): Command { val size: Int get() { return files .filter { !it.startsWith("dir ") } .sumOf { val (size, _) = it.split(" ") size.toInt() } } } class Shell { private var currentDirectory = "/" fun execute(cmd: String) { val (_, dir) = cmd.split(" ") this.currentDirectory = dir } fun currentDirectory(): String { return currentDirectory } }
0
Kotlin
0
0
fbbd1543b5c5d57885e620ede296b9103477f61d
3,212
advent-of-code-kotlin-2022
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import kotlin.math.absoluteValue import kotlin.math.sign fun main() = Day12.solve() object Day12 : AdventSolution(2019, 12, "The N-body problem") { override fun solvePartOne(input: String): Int { val moons = parse(input).map { Moon(it, Vec3(0, 0, 0)) } repeat(1000) { moons.forEach { m -> moons.filter { it != m }.forEach { m.attract(it) } } moons.forEach { it.move() } } return moons.sumOf { it.energy() } } override fun solvePartTwo(input: String): Long { val positions = parse(input) return listOf(Vec3::x, Vec3::y, Vec3::z) .map { positions.map(it) } .map { 2 * findHalfCycle(it).toLong() } .reduce(::lcm) } private fun findHalfCycle(positions: List<Int>): Int { val pv = positions.map { it to 0 } fun still(state: List<Pair<Int, Int>>) = state.all { it.second == 0 } return evolve(pv).drop(1).takeWhile { !still(it) }.count() + 1 } private fun evolve(state: List<Pair<Int, Int>>) = generateSequence(state) { old -> old.map { (p, v) -> val vn = v + old.sumOf { (it.first - p).sign } p + vn to vn } } private fun lcm(a: Long, b: Long) = a * b / gcd(a, b) private tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) private fun parse(input: String): List<Vec3> = input .lines() .map { """<x=(-?\d+), y=(-?\d+), z=(-?\d+)>""".toRegex().matchEntire(it)!!.destructured } .map { (x, y, z) -> Vec3(x.toInt(), y.toInt(), z.toInt()) } private data class Vec3(val x: Int, val y: Int, val z: Int) { operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z) operator fun minus(o: Vec3) = Vec3(x - o.x, y - o.y, z - o.z) fun sign() = Vec3(x.sign, y.sign, z.sign) fun energy() = listOf(x, y, z).sumOf { it.absoluteValue } } private data class Moon(var p: Vec3, var v: Vec3) { fun move() { p += v } fun attract(o: Moon) { v += (o.p - p).sign() } fun energy() = p.energy() * v.energy() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,293
advent-of-code
MIT License
src/day12/Day12ToddGinsbergSolution.kt
commanderpepper
574,647,779
false
{"Kotlin": 44999}
package day12 import readInput import java.util.* fun main(){ val dayTwelveInput = readInput("day12") val heightMap = parseInput(dayTwelveInput) heightMap.elevations.forEach(::println) val shortestPath = heightMap.shortestPath( begin = heightMap.start, isGoal = { it == heightMap.end }, canMove = { from, to -> to - from <= 1 } ) println(shortestPath) val startingElevations = heightMap.findPointsFromElevation { it == 0 } println(startingElevations) val pathsToEnd = startingElevations.map { try { heightMap.shortestPath( begin = it, isGoal = { it == heightMap.end }, canMove = { from, to -> to - from <= 1 } ) } catch (e: Exception){ Int.MAX_VALUE } } println(pathsToEnd) println(pathsToEnd.min()) val toddsPartTwoSolution = heightMap.shortestPath( begin = heightMap.end, isGoal = { heightMap.elevations[it] == 0 }, canMove = { from, to -> from - to <= 1 } ) println(toddsPartTwoSolution) } data class Point2D(val x: Int = 0, val y: Int = 0) { fun cardinalNeighbors(): Set<Point2D> = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1) ) } private class HeightMap(val elevations: Map<Point2D, Int>, val start: Point2D, val end: Point2D) { fun shortestPath( begin: Point2D, isGoal: (Point2D) -> Boolean, canMove: (Int, Int) -> Boolean ): Int { val seen = mutableSetOf<Point2D>() val queue = PriorityQueue<PathCost>().apply { add(PathCost(begin, 0)) } while (queue.isNotEmpty()) { val nextPoint = queue.poll() if (nextPoint.point !in seen) { seen += nextPoint.point val neighbors = nextPoint.point.cardinalNeighbors() .filter { it in elevations } .filter { canMove(elevations.getValue(nextPoint.point), elevations.getValue(it)) } if (neighbors.any { isGoal(it) }) return nextPoint.cost + 1 queue.addAll(neighbors.map { PathCost(it, nextPoint.cost + 1) }) } } throw IllegalStateException("No valid path found") } /** * Quick solution I came to when I first read part two of day twelve. */ fun findPointsFromElevation(meetsConditon: (Int) -> Boolean): List<Point2D>{ return elevations.filter { meetsConditon(it.value) }.keys.toList() } } private fun parseInput(input: List<String>): HeightMap { var start: Point2D? = null var end: Point2D? = null val elevations = input.flatMapIndexed { y, row -> row.mapIndexed { x, char -> val here = Point2D(x, y) here to when (char) { 'S' -> 0.also { start = here } 'E' -> 25.also { end = here } else -> char - 'a' } } }.toMap() return HeightMap(elevations, start!!, end!!) } private data class PathCost(val point: Point2D, val cost: Int) : Comparable<PathCost> { override fun compareTo(other: PathCost): Int = this.cost.compareTo(other.cost) }
0
Kotlin
0
0
fef291c511408c1a6f34a24ed7070ceabc0894a1
3,282
advent-of-code-kotlin-2022
Apache License 2.0
src/Day16.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
import java.util.BitSet fun main() { class Valve(val rate: Int, val targets: List<Int>) fun parseInput(input: List<String>): List<Valve> { val regex = Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)") val tempMap: Map<String, Pair<Int, List<String>>> = input.associate { line -> val (name, rate, targets) = regex.matchEntire(line)!!.destructured name to Pair(rate.toInt(), targets.split(", ")) }.toMap() val idxToName = tempMap.keys.sortedBy { it }.withIndex().associate { it.index to it.value }.toMap() val nameToIdx = idxToName.map { it.value to it.key }.toMap() return (0 until tempMap.size).map { idx -> val v = tempMap[idxToName[idx]!!]!! Valve(v.first, v.second.map { nameToIdx[it]!! }) }.toList() } fun findShortestPaths(valves: List<Valve>): Map<Int, Map<Int, Int>> { val shortestPaths = mutableMapOf<Int, Map<Int, Int>>() val allNodes = valves.indices allNodes.forEach { node -> shortestPaths[node] = allNodes.associateWith { if (node == it) 0 else if (valves[node].targets.contains(it)) 1 else 99999 } } allNodes.forEach { node -> allNodes.forEach { source -> allNodes.forEach { target -> val newDistance = shortestPaths[source]!![node]!! + shortestPaths[node]!![target]!! if (newDistance < shortestPaths[source]!![target]!!) { shortestPaths[source] = shortestPaths[source]!!.toMutableMap().apply { this[target] = newDistance } } } } } return shortestPaths .map { (k, v) -> k to v .filter { valves[it.key].rate > 0 && it.key != k } }.toMap() } fun part1(input: List<String>): Int { val valves = parseInput(input) val cache = mutableMapOf<Triple<Int, Int, BitSet>, Int>() val shortestPaths = findShortestPaths(valves) fun makeBestChoice(current: Int, remainingSteps: Int, opened: BitSet): Int { if (Triple(current, remainingSteps, opened) in cache) { return cache[Triple(current, remainingSteps, opened)]!! } val result = shortestPaths[current]!! .filter { !opened.get(it.key + 1) && (remainingSteps - (it.value + 1)) >= 0 } .map { (target, distance) -> val stepsLeftAfterOpen = remainingSteps - (distance + 1) val newOpened = (opened.clone() as BitSet).apply { set(target + 1) } valves[target].rate * stepsLeftAfterOpen + makeBestChoice(target, stepsLeftAfterOpen, newOpened) }.maxOrNull() ?: 0 cache[Triple(current, remainingSteps, opened)] = result return result } return makeBestChoice(0, 30, BitSet()) } fun part2(input: List<String>): Int { val valves = parseInput(input) val shortestPaths = findShortestPaths(valves) val cache = mutableMapOf<Triple<Pair<Int, Int>, Pair<Int, Int>, BitSet>, Int>() fun makeBestChoice(current: Pair<Int, Int>, remainingSteps: Pair<Int, Int>, opened: BitSet): Int { if (remainingSteps.first < remainingSteps.second) { return makeBestChoice(current.swap(), remainingSteps.swap(), opened) } if (Triple(current, remainingSteps, opened) in cache) { return cache[Triple(current, remainingSteps, opened)]!! } val result = listOf(0, 1) .filter { remainingSteps.get(it) >= 0 } .flatMap { player -> val playerCurrent = current.get(player) val playerRemainingSteps = remainingSteps.get(player) shortestPaths[playerCurrent]!! .filter { !opened.get(it.key + 1) && (playerRemainingSteps - (it.value - 1)) >= 0 } .map { (target, distance) -> val stepsLeftAfterOpen = playerRemainingSteps - (distance + 1) val newOpened = (opened.clone() as BitSet).apply { set(target + 1) } val newRemainingSteps = remainingSteps.set(player, stepsLeftAfterOpen) val newCurrent = current.set(player, target) valves[target].rate * stepsLeftAfterOpen + makeBestChoice(newCurrent, newRemainingSteps, newOpened) } }.maxOrNull() ?: 0 cache[Triple(current, remainingSteps, opened)] = result return result } return makeBestChoice(Pair(0, 0), Pair(26, 26), BitSet()) } val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) } private fun <A> Pair<A, A>.get(i: Int): A { return when (i) { 0 -> first 1 -> second else -> throw IllegalArgumentException() } } private fun <A> Pair<A, A>.set(i: Int, value: A): Pair<A, A> { return when (i) { 0 -> Pair(value, second) 1 -> Pair(first, value) else -> throw IllegalArgumentException() } } private fun <A> Pair<A, A>.swap(): Pair<A, A> { return Pair(second, first) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
5,579
aoc-2022
Apache License 2.0
src/Day18.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
fun main() { data class Point(val x: Int, val y: Int, val z: Int) { fun neighbours() = setOf( Point(x + 1, y, z), // right Point(x - 1, y, z), // left Point(x, y + 1, z), // up Point(x, y - 1, z), // down Point(x, y, z + 1), // front Point(x, y, z - 1), // back ) } fun computeAirBoundary(points: List<Point>, start: Point, max: Point): Set<Point> { var toVisit = setOf(start) val visited = mutableSetOf(start) while (toVisit.isNotEmpty()) { toVisit = toVisit .flatMap { it.neighbours() - points.toSet() } .minus(visited) .filter { it.x in start.x..max.x && it.y in start.y..max.y && it.z in start.z..max.z } .toSet() visited += toVisit } return visited } fun parseInput(lines: List<String>) = lines .map { it.split(",") } .map { (x, y, z) -> Point(x.toInt(), y.toInt(), z.toInt()) } fun part1(input: List<String>): Int { val points = parseInput(input) return points.sumOf { it.neighbours().count { n -> n !in points } } } fun part2(input: List<String>): Int { val points = parseInput(input) val start = Point(points.minOf { it.x } - 1, points.minOf { it.y } - 1, points.minOf { it.z } - 1) val max = Point(points.maxOf { it.x } + 1, points.maxOf { it.y } + 1, points.maxOf { it.z } + 1) val airBoundary = computeAirBoundary(points, start, max) return points.sumOf { it.neighbours().count { n -> n in airBoundary } } } val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
1,850
aoc-2022
Apache License 2.0
src/Day08.kt
niltsiar
572,887,970
false
{"Kotlin": 16548}
fun main() { fun part1(input: List<String>): Int { return input.indices.sumOf { i -> input.first().indices.count { j -> createListOfTrees(i, j, input.size, input.first().length).any { trees -> trees.all { (x, y) -> input[x][y] < input[i][j] } } } } } fun part2(input: List<String>): Int { return input.indices.maxOf { i -> input.first().indices.maxOf { j -> createListOfTrees(i, j, input.size, input.first().length).map { trees -> minOf(trees.takeWhile { (x, y) -> input[x][y] < input[i][j] }.size + 1, trees.size) }.reduce(Int::times) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } fun createListOfTrees(i: Int, j: Int, maxRows: Int, maxColumns: Int): List<List<Pair<Int, Int>>> { val left = (j - 1 downTo 0).map { i to it } val right = (j + 1 until maxColumns).map { i to it } val up = (i - 1 downTo 0).map { it to j } val down = (i + 1 until maxRows).map { it to j } return listOf(left, right, up, down) }
0
Kotlin
0
0
766b3e168fc481e4039fc41a90de4283133d3dd5
1,366
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2023/src/Day07.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
private const val DAY = "Day07" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { solve(testInput()) shouldBe 6440 measureAnswer { solve(input()) } } "Part 2" { solve(testInput(), withJoker = true) shouldBe 5905 measureAnswer { solve(input(), withJoker = true) } } } private fun solve(input: List<Hand>, withJoker: Boolean = false): Int = input .sortedWith(Hand.comparator(withJoker)) .withIndex() .sumOf { (index, hand) -> hand.bid * (index + 1) } private fun readInput(name: String) = readLines(name).map { line -> val (cards, rawBid) = line.split(" ") Hand(cards, rawBid.toInt()) } private data class Hand(val cards: String, val bid: Int) { fun power(withJoker: Boolean): Int { val cardsCount = mutableMapOf<Char, Int>() cards.groupingBy { it }.eachCountTo(cardsCount) val jokers = if (withJoker) cardsCount.remove('J') ?: 0 else 0 val maxCardsCount = cardsCount.values.maxOrNull() ?: 0 return when (maxCardsCount + jokers) { 5 -> FIVE_OF_KIND 4 -> FOUR_OF_KIND 3 -> if (cardsCount.size == 2) FULL_HOUSE else THREE_OF_KIND 2 -> if (cardsCount.size == 3) TWO_PAIR else ONE_PAIR else -> HIGH_CARD } } companion object { fun comparator(withJoker: Boolean): Comparator<Hand> { return compareBy<Hand> { it.power(withJoker) } .thenComparing { left, right -> left.cards.indices.asSequence() .map { i -> compareCards(left.cards[i], right.cards[i], withJoker) } .first { it != 0 } } } private fun compareCards(cardA: Char, cardB: Char, withJoker: Boolean): Int { return rankOfCard(cardA, withJoker) compareTo rankOfCard(cardB, withJoker) } private fun rankOfCard(card: Char, withJoker: Boolean): Int = when (card) { in '2'..'9' -> card.digitToInt() 'T' -> 10 'J' -> if (withJoker) 1 else 11 'Q' -> 12 'K' -> 13 'A' -> 14 else -> error("Unexpected card: $card") } } } const val FIVE_OF_KIND = 6 const val FOUR_OF_KIND = 5 const val FULL_HOUSE = 4 const val THREE_OF_KIND = 3 const val TWO_PAIR = 2 const val ONE_PAIR = 1 const val HIGH_CARD = 0
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,453
advent-of-code
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day05/day05.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day05 import eu.janvdb.aocutil.kotlin.CombinedRange import eu.janvdb.aocutil.kotlin.SimpleRange import eu.janvdb.aocutil.kotlin.readGroupedLines import java.util.* //const val FILENAME = "input05-test.txt" const val FILENAME = "input05.txt" fun main() { val groupedLines = readGroupedLines(2023, FILENAME) part1(groupedLines) part2(groupedLines) } private fun part1(groupedLines: List<List<String>>) { val seeds = parseSingleRanges(groupedLines[0][0]) val mappings = Mappings.parse(groupedLines) val seedsMapped = mappings.map(seeds) println(seedsMapped.min().start) } private fun part2(groupedLines: List<List<String>>) { val seeds = parseRanges(groupedLines[0][0]) val mappings = Mappings.parse(groupedLines) val seedsMapped = mappings.map(seeds) println(seedsMapped.min().start) } fun parseSingleRanges(line: String): CombinedRange { return line.split(": ")[1].split(" ") .map { it.toLong() } .map { SimpleRange(it, it) } .fold(CombinedRange()) { acc, range -> acc.add(range) } } fun parseRanges(line: String): CombinedRange { return line.split(": ")[1].split(" ") .map { it.toLong() } .chunked(2) { SimpleRange(it[0], it[0] + it[1] - 1) } .fold(CombinedRange()) { acc, range -> acc.add(range) } } data class Mappings(val mappings: List<Mapping>) { fun map(source: CombinedRange): CombinedRange { return mappings.fold(source) { acc, mapping -> mapping.map(acc) } } companion object { fun parse(groupedLines: List<List<String>>): Mappings { val maps = groupedLines.drop(1).map { Mapping.parse(it) } return Mappings(maps) } } } data class Mapping(val name: String, val entries: List<MappingEntry>) { fun map(rangeSet: CombinedRange): CombinedRange { val todo = LinkedList(rangeSet.ranges) var result = CombinedRange() while (!todo.isEmpty()) { val range = todo.removeFirst() if (range.isEmpty()) continue val overlap = entries.find { it.sourceRange.overlapsWith(range) } if (overlap == null) { result = result.add(range) } else { result = result.add( range.intersectWith(overlap.sourceRange).move(overlap.destinationStart - overlap.sourceRange.start) ) range.subtract(overlap.sourceRange).forEach { todo.add(it) } } } println(result) return result } companion object { fun parse(lines: List<String>): Mapping { val name = lines[0] val entries = lines.drop(1) .map { MappingEntry.parse(it) } .sortedBy { it.sourceRange.start } return Mapping(name, entries) } } } data class MappingEntry(val sourceRange: SimpleRange, val destinationStart: Long) { companion object { fun parse(line: String): MappingEntry { val parts = line.split(" ").map { it.toLong() } val sourceRange = SimpleRange(parts[1], parts[2] + parts[1] - 1) return MappingEntry(sourceRange, parts[0]) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
3,241
advent-of-code
Apache License 2.0
src/Day08.kt
ked4ma
573,017,240
false
{"Kotlin": 51348}
import kotlin.math.max /** * [Day08](https://adventofcode.com/2022/day/8) */ fun main() { fun trees(input: List<String>): Array<Array<Int>> = input.map { line -> line.toCharArray().map(Char::digitToInt).toTypedArray() }.toTypedArray() fun toInfoList(input: List<String>): Pair<Array<Array<Int>>, Array<Array<Array<Int>>>> { val trees = trees(input) val around = Array(trees.size) { Array(trees[0].size) { Array(4) { 0 } } }.also { val lastI = trees.lastIndex val lastJ = trees[0].lastIndex for (i in trees.indices) { for (j in trees[0].indices) { if (j < lastJ) { // left it[i][j + 1][0] = max(it[i][j][0], trees[i][j]) // right it[i][lastJ - j - 1][2] = max(it[i][lastJ - j][2], trees[i][lastJ - j]) } if (i < lastI) { // up it[i + 1][j][1] = max(it[i][j][1], trees[i][j]) // down it[lastI - i - 1][j][3] = max(it[lastI - i][j][3], trees[lastI - i][j]) } } } } return trees to around } fun part1(input: List<String>): Int { val (trees, around) = toInfoList(input) return (trees.size + trees[0].size) * 2 - 4 + (1 until trees.lastIndex).sumOf { i -> (1 until trees[0].lastIndex).count { j -> trees[i][j] > around[i][j].min() } } } fun part2(input: List<String>): Int { val trees = trees(input) val lastI = trees.lastIndex val lastJ = trees[0].lastIndex val around = Array(trees.size) { Array(trees[0].size) { Array(4) { 0 } } } fun search(i: Int, j: Int, direction: Int, value: Int): Int { if (i == 0 || i == lastI || j == 0 || j == lastJ) return 0 val (ni, nj) = when (direction) { 0 -> i to j - 1 // left 1 -> i - 1 to j // up 2 -> i to j + 1 // right 3 -> i + 1 to j // down else -> throw RuntimeException() } around[i][j][direction] = if (trees[ni][nj] < value) search(ni, nj, direction, value) + 1 else 1 return around[i][j][direction] } for (i in 1 until trees.lastIndex) { for (j in 1 until trees[0].lastIndex) { for (k in 0..3) { search(i, j, k, trees[i][j]) } } } return around.maxOf { row -> row.maxOf { cell -> cell.reduce { acc, v -> acc * v } } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
6d4794d75b33c4ca7e83e45a85823e828c833c62
3,215
aoc-in-kotlin-2022
Apache License 2.0
src/Day13.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
fun main() { val input = readInput("Day13") val testInput = readInput("Day13_test") fun part1(input: List<String>): Int { return input.filter { it.isNotBlank() }.map(::parseList).chunked(2) .sumOfIndexed { idx, (x, y) -> if (x.compareTo(y) == -1) idx + 1 else 0 } } fun part2(input: List<String>): Int { val dividers = listOf(parseList("[[2]]"), parseList("[[6]]")) val all = input.filter { it.isNotBlank() }.map(::parseList).plus(dividers).sorted() return dividers.map { all.binarySearch(it) + 1 }.reduce { acc, i -> acc * i } } println(part1(testInput)) check(part1(testInput) == 13) println(part2(testInput)) check(part2(testInput) == 140) println("Part1") println(part1(input)) // 6428 println("Part2") println(part2(input)) // 22464 } private data class NumberBuilder(var currentNum: Int = 0, var hasNum: Boolean = false) { fun addDigit(digit: Int) { currentNum = currentNum * 10 + digit hasNum = true } fun collectNumber() = if (hasNum) currentNum.also { hasNum = false; currentNum = 0 } else null } private fun parseList(inp: String): Packet { val root = PacketList(null) var currentList = root val numberBuilder = NumberBuilder() inp.forEach { when (it) { '[' -> currentList = currentList.addList() ']' -> { numberBuilder.collectNumber()?.also { currentList.addElement(it) } currentList = currentList.parent!! } ' ' -> {} ',' -> numberBuilder.collectNumber()?.also { currentList.addElement(it) } else -> numberBuilder.addDigit(it - '0') } } return root.children[0] } private sealed class Packet : Comparable<Packet> { override fun compareTo(other: Packet): Int { if (this is PacketNumber && other is PacketNumber) return value.compareTo(other.value) return compareList(asPacketList(), other.asPacketList()) } fun compareList(left: PacketList, right: PacketList): Int { left.children.zip(right.children) .forEach { (left, right) -> left.compareTo(right).let { if (it != 0) return it } } return left.children.size.compareTo(right.children.size) } fun asPacketList(): PacketList = if (this is PacketList) this else PacketList(null, mutableListOf(this)) } private data class PacketList( val parent: PacketList?, val children: MutableList<Packet> = mutableListOf() ) : Packet() { fun addElement(value: Int) { children.add(PacketNumber(value)) } fun addList(): PacketList = PacketList(this).also { children.add(it) } } private data class PacketNumber(val value: Int) : Packet()
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
2,761
advent-of-code-kotlin-2022
Apache License 2.0
advent-of-code-2022/src/Day11.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { "Part 1" { val testInput = readInput("Day11_test") val input = readInput("Day11") part1(testInput) shouldBe 10605 answer(part1(input)) } "Part 2" { val testInput = readInput("Day11_test") val input = readInput("Day11") part2(testInput) shouldBe 2713310158 answer(part2(input)) } } private fun part1(input: List<Monkey>): Long = solve(input, rounds = 20, keepCalm = true) private fun part2(input: List<Monkey>): Long = solve(input, rounds = 10_000, keepCalm = false) private fun solve(monkeys: List<Monkey>, rounds: Int, keepCalm: Boolean): Long { val inspectionsCounts = IntArray(monkeys.size) { 0 } // All `divideBy` values are prime numbers, so we can multiply them all together // and take remainder from division by resulting value. // We should do it after each operation to not overflow Int. val mod = monkeys.map { it.divideBy.toLong() }.reduce(Long::times) repeat(rounds) { for ((i, monkey) in monkeys.withIndex()) { inspectionsCounts[i] += monkey.items.size for (item in monkey.takeItems()) { val calmLevel = if (keepCalm) 3 else 1 val new = (monkey.operation(item) / calmLevel % mod).toInt() val target = if (new % monkey.divideBy == 0) monkey.ifTrue else monkey.ifFalse monkeys[target].items.add(new) } } } return inspectionsCounts.sortedDescending().take(2).map(Int::toLong).reduce(Long::times) } private fun readInput(name: String) = readText(name).splitToSequence("\n\n").map { rawMonkey -> val (items, operation, test, ifTrue, ifFalse) = rawMonkey.lines().drop(1) Monkey( startingItems = items.substringAfter(": ").split(", ").map(String::toInt), operation = parseOperation(operation), divideBy = test.substringAfter("divisible by ").toInt(), ifFalse = ifFalse.substringAfter("throw to monkey ").toInt(), ifTrue = ifTrue.substringAfter("throw to monkey ").toInt(), ) }.toList() private fun parseOperation(input: String): (Int) -> Long { val parts = input.substringAfter(" = ").split(" ") val operation: (Long, Long) -> Long = if (parts[1] == "+") Long::plus else Long::times val b = parts[2].toLongOrNull() return { old -> operation(old.toLong(), b ?: old.toLong()) } } private class Monkey( startingItems: List<Int>, val operation: (Int) -> Long, val divideBy: Int, val ifFalse: Int, val ifTrue: Int ) { val items: MutableList<Int> = startingItems.toMutableList() fun takeItems() = items.toList().also { items.clear() } }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,687
advent-of-code
Apache License 2.0
src/day08/Day08.kt
spyroid
433,555,350
false
null
package day08 import readInput import kotlin.system.measureTimeMillis fun main() { fun part1(seq: Sequence<Box>) = seq.map { box -> box.numbers().count { it in listOf(1, 4, 7, 8) } }.sum() fun part2(seq: Sequence<Box>) = seq.map { box -> box.asValue() }.sum() val testSeq = readDigits(readInput("day08/test")) val inputSeq = readDigits(readInput("day08/input")) var res1 = part1(testSeq) check(res1 == 26) { "Expected 26 but got $res1" } var time = measureTimeMillis { res1 = part1(inputSeq) } println("Part1: $res1 in $time ms") time = measureTimeMillis { res1 = part2(inputSeq) } println("Part2: $res1 in $time ms") } fun readDigits(list: List<String>): Sequence<Box> { return list.map { line -> line .split("|", " ") .filter { it.isNotBlank() } .map { it.toSet() } .let { Box(it.take(10), it.takeLast(4)) } }.asSequence() } data class Box(val left: List<Set<Char>>, var right: List<Set<Char>>) { private val mappings = findMappings() fun asValue() = right.map { mappings.getValue(it) }.joinToString("").toInt() fun numbers() = right.map { mappings.getValue(it) } private fun findMappings(): Map<Set<Char>, Int> { val digits = Array<Set<Char>>(10) { emptySet() } digits[1] = left.first { it.size == 2 } digits[4] = left.first { it.size == 4 } digits[7] = left.first { it.size == 3 } digits[8] = left.first { it.size == 7 } digits[3] = left .filter { it.size == 5 } .first { it.containsAll(digits[1]) } digits[9] = left .filter { it.size == 6 } .first { it.containsAll(digits[3]) } digits[0] = left .filter { it.size == 6 } .filter { it.containsAll(digits[1]) && it.containsAll(digits[7]) } .first { it != digits[9] } digits[6] = left .filter { it.size == 6 } .first { it != digits[0] && it != digits[9] } digits[5] = left .filter { it.size == 5 } .first { digits[6].containsAll(it) } digits[2] = left .filter { it.size == 5 } .first { it != digits[3] && it != digits[5] } return digits.mapIndexed { index, chars -> chars to index }.toMap() } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
2,344
Advent-of-Code-2021
Apache License 2.0
src/main/kotlin/day15/Day15.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day15 import readInput import kotlin.math.abs fun main() { data class Scanner(val sx: Int, val sy: Int, val bx: Int, val by: Int) { val dist: Int get() = abs(sx - bx) + abs(sy - by) } val pattern = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() fun parseScanners(input: List<String>) = input.mapNotNull { line -> pattern.matchEntire(line)?.let { match -> val sx = match.groups[1]!!.value.toInt() val sy = match.groups[2]!!.value.toInt() val bx = match.groups[3]!!.value.toInt() val by = match.groups[4]!!.value.toInt() Scanner(sx, sy, bx, by) } } fun calculateRanges( scanners: List<Scanner>, target: Int ) = scanners .mapNotNull { scanner -> val delta = scanner.dist - abs(scanner.sy - target) if (delta >= 0) { scanner.sx - delta to scanner.sx + delta } else { null } } .sortedBy { it.first } .fold(mutableListOf<Pair<Int, Int>>()) { ranges, range -> if (ranges.isEmpty()) { ranges.add(range) } else { val last = ranges.last() if (last.second >= range.first && last.second < range.second) { ranges.removeLast() ranges.add(last.first to range.second) } else if (last.second < range.first) { ranges.add(range.first to range.second) } } ranges } fun part1(input: List<String>, target: Int): Int { val scanners = parseScanners(input) val ranges = calculateRanges(scanners, target) val beacons = scanners.filter { it.by == target }.map { it.bx }.toSortedSet() var count = 0 var last = Int.MIN_VALUE for ((f, t) in ranges) { val start = maxOf(last + 1, f) val end = t val length = maxOf(0, end - start + 1) count += length - beacons.count { it in start..end } last = maxOf(last, end) } return count } fun part2(input: List<String>, limit: Int): Long { val scanners = parseScanners(input) for (y in 0 until limit) { val ranges = calculateRanges(scanners, y) if (ranges.size > 1) { val x = ranges[0].second + 1 return x.toLong() * 4000000 + y } } return -1 } val testInput = readInput("day15", "test") val input = readInput("day15", "input") check(part1(testInput, 10) == 26) println(part1(input, 2000000)) check(part2(testInput, 20) == 56000011L) println(part2(input, 4000000)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
2,849
aoc2022
Apache License 2.0
src/Day08.kt
kecolk
572,819,860
false
{"Kotlin": 22071}
fun main() { data class Tree(val height: Int, var seen: Boolean = false, var scenic: Int = 0) { fun getCount(): Int = if (seen) 1 else 0 } fun parseInput(input: List<String>): Array<Array<Tree>> = input.map { it.toList().map { tree -> Tree(tree.toString().toInt()) }.toTypedArray() }.toTypedArray() fun part1(forest: Array<Array<Tree>>): Int { val highestTop = MutableList(forest.size) { -1 } val highestBottom = MutableList(forest.size) { -1 } forest.forEach { item -> var highestLeft = -1 var highestRight = -1 item.forEachIndexed { columnIndex, tree -> if (tree.height > highestLeft) { tree.seen = true highestLeft = tree.height } if (tree.height > highestTop[columnIndex]) { tree.seen = true highestTop[columnIndex] = tree.height } } item.reversed().forEach { if (it.height > highestRight) { it.seen = true highestRight = it.height } } } forest.reversed().forEach { item -> item.forEachIndexed { columnIndex, tree -> if (tree.height > highestBottom[columnIndex]) { tree.seen = true highestBottom[columnIndex] = tree.height } } } return forest.sumOf { row -> row.sumOf { tree -> tree.getCount() } } } fun part2(input: Array<Array<Tree>>): Int { for (row: Int in 0 until input.size) { for (column: Int in 0 until input.first().size) { val treeHeight = input[row][column].height var currentTop = row var currentBottom = input.size - 1 - row var currentLeft = column var currentRight = input.size - 1 - column for (searchRow: Int in 0 until input.size) { if (searchRow < row && input[searchRow][column].height >= treeHeight) { currentTop = row - searchRow } if (searchRow > row && input[searchRow][column].height >= treeHeight && searchRow - row < currentBottom) { currentBottom = searchRow - row } } for (searchColumn: Int in 0 until input.first().size) { if (searchColumn < column && input[row][searchColumn].height >= treeHeight) { currentLeft = column - searchColumn } if (searchColumn > column && input[row][searchColumn].height >= treeHeight && searchColumn - column < currentRight) { currentRight = searchColumn - column } } input[row][column].scenic = currentTop * currentBottom * currentRight * currentLeft } } return input.maxOf { row -> row.maxOf { tree -> tree.scenic } } } val testForest = parseInput(readTextInput("Day08_test")) val forest = parseInput(readTextInput("Day08")) check(part1(testForest) == 21) check(part2(testForest) == 8) println(part1(forest)) println(part2(forest)) }
0
Kotlin
0
0
72b3680a146d9d05be4ee209d5ba93ae46a5cb13
3,389
kotlin_aoc_22
Apache License 2.0
src/y2021/Day09.kt
Yg0R2
433,731,745
false
null
package y2021 fun main() { fun part1(input: List<String>): Int { val heightmap: Array<Array<Int>> = input.toHeightMap() return heightmap .getLowestPointCoordinates() .sumOf { (x, y) -> heightmap[x][y] + 1 } } fun part2(input: List<String>): Int { val heightmap: Array<Array<Int>> = input.toHeightMap() return heightmap .getLowestPointCoordinates() .map { (x, y) -> getBasin(x, y, heightmap, setOf(x to y)) } .sortedByDescending { it.size } .take(3) .fold(1) { acc: Int, set: Set<Pair<Int, Int>> -> acc * set.size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 15) check(part2(testInput) == 1134) val input = readInput("Day09") println(part1(input)) println(part2(input)) } private fun List<String>.toHeightMap(): Array<Array<Int>> = this .map { it.split("") } .map { it.toIntList() } .map { it.toTypedArray() } .toTypedArray() private fun Array<Array<Int>>.getLowestPointCoordinates(): List<Pair<Int, Int>> = this .flatMapIndexed { x, heightPoints -> heightPoints .mapIndexedNotNull { y, currentHeight -> if ((x == 0 || this[x - 1][y] > currentHeight) && (x == this.size - 1 || this[x + 1][y] > currentHeight) && (y == 0 || this[x][y - 1] > currentHeight) && (y == this[x].size - 1 || this[x][y + 1] > currentHeight)) { x to y } else { null } } } private fun getBasin(x: Int, y: Int, heightmap: Array<Array<Int>>, basin: Set<Pair<Int, Int>>): Set<Pair<Int, Int>> { val currentHeight = heightmap[x][y] if (currentHeight == 9) { return basin } var newBasin = basin.toMutableSet() .also { it.add(x to y) } .toSet() if ((x> 0) && (heightmap[x - 1][y] >= currentHeight + 1)) { newBasin = getBasin(x - 1, y, heightmap, newBasin) } if ((x < heightmap.size - 1) && (heightmap[x + 1][y] >= currentHeight + 1)) { newBasin = getBasin(x + 1, y, heightmap, newBasin) } if ((y > 0) && (heightmap[x][y - 1] >= currentHeight + 1)) { newBasin = getBasin(x, y - 1, heightmap, newBasin) } if ((y < heightmap[x].size - 1) && (heightmap[x][y + 1] >= currentHeight + 1)) { newBasin = getBasin(x, y + 1, heightmap, newBasin) } return newBasin }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,663
advent-of-code
Apache License 2.0
src/Day13.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
fun chunkStringToList(str: String): List<String> { val withoutBrackets = str.filterIndexed { index, _ -> index != 0 && index != str.lastIndex } val elements = mutableListOf<String>() var bracketIndex = 0 val current = StringBuilder("") for (i in withoutBrackets.indices) { if ((withoutBrackets[i] == ',' && bracketIndex == 0)) { elements.add(current.toString()) current.clear() } else { current.append(withoutBrackets[i]) if (withoutBrackets[i] == '[') { bracketIndex++ } if (withoutBrackets[i] == ']') { bracketIndex-- } } } if (current.isNotEmpty()) elements.add(current.toString()) return elements } fun compareLists(first: String, second: String): Int { val elements1 = chunkStringToList(first) val elements2 = chunkStringToList(second) if (elements1.isEmpty() && elements2.isNotEmpty()) return 1 if (elements1.isEmpty()) return 0 if (elements2.isEmpty()) return -1 elements1.forEachIndexed { index, s -> if (elements2.size <= index) return -1 val comp = compare(s, elements2[index]) if (comp != 0) { return comp } } if (elements1.size == elements2.size) return 0 return 1 } fun compareNumbers(first: Int, second: Int): Int { return if (first == second) 0 else if (first < second) 1 else -1 } fun compareNumberList(number: Int, list: String): Int { return compareLists("[$number]", list) } fun compareNumberList(list: String, number: Int) = -compareNumberList(number, list) fun compare(first: String, second: String): Int { return if (first[0] == '[') { if (second[0] == '[') compareLists(first, second) else compareNumberList(first, second.toInt()) } else { if (second[0] == '[') compareNumberList(first.toInt(), second) else compareNumbers( first.toInt(), second.toInt() ) } } class PackageComparator { companion object : Comparator<String> { override fun compare(a: String, b: String): Int { return -compareLists(a, b) } } } fun main() { fun part1(input: List<String>): Int { val pairs = input.chunked(3).map { if (it.size == 3) it.subList(0, 2) else it } var result = 0 pairs.forEachIndexed { index, strings -> if (compareLists(strings[0], strings[1]) >= 0) result += (index + 1) } return result } fun part2(input: List<String>): Int { val index1 = "[[2]]" val index2 = "[[6]]" val packages = input.filter { it.isNotEmpty() } + listOf( index1, index2 ) val sortedPackages = packages.sortedWith(PackageComparator) return (sortedPackages.indexOf(index1)+1) * (sortedPackages.indexOf(index2)+1) } val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
3,028
Advent-of-code
Apache License 2.0
src/main/kotlin/day9/Day9.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day9 import readToList fun main() { println(part1()) println(part2()) } private fun part1(): Int { val heightMatrix = HeightMatrix(readInput()) heightMatrix.setLowPoints() val filter = heightMatrix.matrix .flatten() .filter { it.lowest } return filter .sumOf { it.height + 1 } } private fun part2(): Int { val heightMatrix = HeightMatrix(readInput()) heightMatrix.setLowPoints() val basins = heightMatrix.matrix .flatten() .filter { it.lowest } .map { lowPoint -> heightMatrix.findBasin(lowPoint) } val (a, b, c) = basins.sortedDescending() return a * b * c } private data class HeightMatrix(val matrix: List<List<Height>>) { fun get(rowIndex: Int, columnIndex: Int): Height? { return matrix.getOrNull(rowIndex)?.getOrNull(columnIndex) } fun setLowPoints() { for (row in matrix) { for (current in row) { if (getAdjacent(current).all { current.height < it.height }) { current.lowest = true } } } } fun findBasin(lowPoint: Height): Int { val adjacent = getAdjacent(lowPoint).filter { !it.basinPart && it.valid } var basinSize = 0 if (!lowPoint.basinPart) { lowPoint.basinPart = true basinSize++ } basinSize += adjacent .filter { lowPoint.height <= it.height } .sumOf { findBasin(it) } return basinSize } private fun getAdjacent(height: Height): List<Height> { return listOfNotNull( get(height.rowIndex - 1, height.columnIndex), get(height.rowIndex + 1, height.columnIndex), get(height.rowIndex, height.columnIndex - 1), get(height.rowIndex, height.columnIndex + 1), ) } } private data class Height( val height: Int, var lowest: Boolean = false, val valid: Boolean, var basinPart: Boolean = false, val columnIndex: Int, val rowIndex: Int ) private fun readInput() = readToList("day9.txt") .mapIndexed { rowIndex, line -> line.mapIndexed { columnIndex, char -> val numericValue = Character.getNumericValue(char) Height(height = numericValue, valid = numericValue != 9, columnIndex = columnIndex, rowIndex = rowIndex) } }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
2,417
aoc2021
Apache License 2.0
src/Day18.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
fun main() { fun part1(input: List<String>): Int { val points = mutableSetOf<Triple<Int, Int, Int>>() fun Triple<Int, Int, Int>.adjacent() = listOf( copy(first = first + 1), copy(first = first - 1), copy(second = second + 1), copy(second = second - 1), copy(third = third + 1), copy(third = third - 1), ) return input.asSequence() .map { it.split(",").map(String::toInt) } .map { (x, y, z) -> Triple(x, y, z) } .sumOf { point -> point.adjacent().sumOf { (if (it in points) -1 else 1).toInt() } .also { points += point } } } fun part2(input: List<String>): Int { val points = input.asSequence() .map { it.split(",").map(String::toInt) } .map { (x, y, z) -> Triple(x, y, z) } .toSet() val xRange = (points.minOf { (x) -> x } - 1)..(points.maxOf { (x) -> x } + 1) val yRange = (points.minOf { (_, y) -> y } - 1)..(points.maxOf { (_, y) -> y } + 1) val zRange = (points.minOf { (_, _, z) -> z } - 1)..(points.maxOf { (_, _, z) -> z } + 1) val visited = mutableSetOf<Triple<Int, Int, Int>>() fun Triple<Int, Int, Int>.adjacent() = listOfNotNull( (first + 1).takeIf { it in xRange }?.let { copy(first = it) }, (first - 1).takeIf { it in xRange }?.let { copy(first = it) }, (second + 1).takeIf { it in yRange }?.let { copy(second = it) }, (second - 1).takeIf { it in yRange }?.let { copy(second = it) }, (third + 1).takeIf { it in zRange }?.let { copy(third = it) }, (third - 1).takeIf { it in zRange }?.let { copy(third = it) }, ) val toVisit = mutableListOf(Triple(xRange.first, yRange.first, zRange.first)) return generateSequence { toVisit.removeFirstOrNull() } .filter(visited::add) .flatMap { it.adjacent() } .filterNot { it in visited } .count { point -> (point in points).also { if (!it) toVisit += point } } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readLines("Day18") with(part1(input)) { check(this == 4302) println(this) } with(part2(input)) { check(this == 2492) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
2,531
advent-of-code-kotlin-2022
Apache License 2.0
src/Day23.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import java.util.SortedSet import kotlin.math.abs fun main() { class Elf(val x: Int, val y: Int): Comparable<Elf> { fun propose(turn: Int, elves: SortedSet<Elf>): Elf { val nElf = Elf(x, y - 1) val sElf = Elf(x, y + 1) val eElf = Elf(x + 1, y) val wElf = Elf(x - 1, y) val n = nElf !in elves val ne = Elf(x + 1, y - 1) !in elves val e = eElf !in elves val se = Elf(x + 1, y + 1) !in elves val s = sElf !in elves val sw = Elf(x - 1, y + 1) !in elves val w = wElf !in elves val nw = Elf(x - 1, y - 1) !in elves if (n && ne && e && se && s && sw && w && nw) return this val movesNSWE = listOf( nElf.takeIf { nw && n && ne }, sElf.takeIf { sw && s && se }, wElf.takeIf { nw && w && sw }, eElf.takeIf { ne && e && se }, ) val moves = movesNSWE.drop(turn % 4) + movesNSWE.take(turn % 4) return moves.filterNotNull().firstOrNull() ?: this } override fun compareTo(other: Elf): Int { val compY = y.compareTo(other.y) if (compY == 0) return x.compareTo(other.x) return compY } override fun toString(): String { return "($x, $y)" } } fun parseInput(input: List<String>): SortedSet<Elf> { val set = sortedSetOf<Elf>() input.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char == '#') set.add(Elf(x, y)) } } return set } fun printMap(elves: SortedSet<Elf>) { val minX = elves.minOf { it.x } val minY = elves.minOf { it.y } val maxX = elves.maxOf { it.x } val maxY = elves.maxOf { it.y } (minY..maxY).forEach { y -> (minX..maxX).forEach { x -> print(if (Elf(x, y) in elves) '#' else '.') } println() } println("${elves.count()} elves in area $minX..$maxX : $minY..$maxY") } fun part1(input: List<String>): Int { var elves = parseInput(input) repeat(10) { turn -> printMap(elves) val elvesList = elves.toList() // For proper indexing val proposals = elvesList.map { it.propose(turn, elves) } val proposalsWithoutCollisions = proposals.filter { elf -> proposals.count { it.compareTo(elf) == 0 } == 1 }.toSortedSet() elves = proposals.mapIndexed { index, proposal -> if (proposal in proposalsWithoutCollisions) proposal else elvesList[index] }.toSortedSet() } println("(${elves.maxOf { it.x }} - ${elves.minOf { it.x }} + 1) * (${elves.maxOf { it.y }} - ${elves.minOf { it.y }} + 1) - ${elves.count()}") return (elves.maxOf { it.x } - elves.minOf { it.x } + 1) * (elves.maxOf { it.y } - elves.minOf { it.y } + 1) - elves.count() } fun part2(input: List<String>): Int { var elves = parseInput(input) var turn = 0 var lastNumberOfMoves = 42 while(lastNumberOfMoves > 0) { val elvesList = elves.toList() // For proper indexing val proposals = elvesList.map { it.propose(turn, elves) } val proposalsWithoutCollisions = proposals.filter { elf -> proposals.count { it.compareTo(elf) == 0 } == 1 }.toSortedSet() val newPositions = proposals.mapIndexed { index, proposal -> if (proposal in proposalsWithoutCollisions) proposal else elvesList[index] }.toSortedSet() lastNumberOfMoves = elves.zip(newPositions).count { it.first != it.second } println("Turn $turn : $lastNumberOfMoves moves") elves = newPositions ++turn } return turn } val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
3,931
aoc2022-kotlin
Apache License 2.0
src/Day08.kt
befrvnk
574,229,637
false
{"Kotlin": 15788}
import java.lang.Integer.min fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean { val maxXSize = this.first().size return when { x == 0 || x == maxXSize - 1 -> true y == 0 || y == size - 1 -> true else -> { val tree = this[x][y] val left = (0 until x).all { this[it][y] < tree } val right = (min(x + 1, maxXSize - 1) until maxXSize).all { this[it][y] < tree } val top = (0 until y).all { this[x][it] < tree } val bottom = (min(y + 1, size - 1) until size).all { this[x][it] < tree } top || right || bottom || left } } } fun List<List<Int>>.scenicScore(x: Int, y: Int): Int { val height = this[x][y] val maxYSize = this.first().size val top = (0 until x).reversed().indexOfFirst { this[it][y] >= height }.takeIf { it != -1 }?.plus(1) ?: x val bottom = (min(x + 1, size - 1) until size).indexOfFirst { this[it][y] >= height }.takeIf { it != -1 }?.plus(1) ?: (size - x - 1) val left = (0 until y).reversed().indexOfFirst { this[x][it] >= height }.takeIf { it != -1 }?.plus(1) ?: y val right = (min(y + 1, maxYSize - 1) until maxYSize).indexOfFirst { this[x][it] >= height }.takeIf { it != -1 }?.plus(1) ?: (maxYSize - y - 1) return top * right * bottom * left } fun main() { fun part1(input: List<String>): Int { val forest = input.map { row -> row.toList().map { it.toString().toInt() } } val visibleTrees = forest.mapIndexed { x, row -> List(row.size) { y -> if (forest.isVisible(x, y)) 1 else 0 }.sum() } .sum() return visibleTrees } fun part2(input: List<String>): Int { val forest = input.map { row -> row.toList().map { it.toString().toInt() } } val maxScenicScore = forest.mapIndexed { x, row -> List(row.size) { y -> forest.scenicScore(x, y) }.max() }.max() return maxScenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") println(part1(testInput)) println(part2(testInput)) // check(part1(testInput) == 7) // check(part2(testInput) == "MCD") val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
68e5dd5656c052d8c8a2ea9e03c62f4cd2438dd7
2,297
aoc-2022-kotlin
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2022/day15/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day15 import com.kingsleyadio.adventofcode.util.readInput import kotlin.math.abs fun main() { val data = parseInput() part1(data, 2_000_000) part2(data, 4_000_000) } fun part1(data: Map<Point, Point>, rowIndex: Int) { val (exclusions, sortedBeacons) = evaluateRow(data, rowIndex) var count = 0 var bIndex = 0 for (range in exclusions) { count += range.endInclusive - range.start + 1 while (bIndex < sortedBeacons.size && sortedBeacons[bIndex] < range.start) bIndex++ if (bIndex < sortedBeacons.size && sortedBeacons[bIndex] in range) count-- } println(count) } fun part2(data: Map<Point, Point>, maxIndex: Int) { for (y in 0..maxIndex) { val (exclusions, _) = evaluateRow(data, y) var left = 0 for (r in exclusions) { if (r.start > left) break else left = r.endInclusive + 1 } if (left <= maxIndex) { println(left * 4_000_000L + y) return } } } fun evaluateRow(data: Map<Point, Point>, rowIndex: Int): RowData { val exclusions = mutableListOf<ClosedRange<Int>>() // all empty cells at row $rowIndex val obstructingBeacons = hashSetOf<Int>() data.forEach { (sensor, beacon) -> val dx = abs(sensor.x - beacon.x) val dy = abs(sensor.y - beacon.y) val radius = dx + dy val ds = abs(sensor.y - rowIndex) if (radius < ds) return@forEach val boundX = radius - ds exclusions.add((sensor.x - boundX)..(sensor.x + boundX)) if (beacon.y == rowIndex) obstructingBeacons.add(beacon.x) } exclusions.sortBy { it.start } val sortedBeacons = obstructingBeacons.sorted() var left = 0 for (i in 1..exclusions.lastIndex) { val range = exclusions[i] val previous = exclusions[left] when (range.start) { in previous -> exclusions[left] = previous.start..maxOf(previous.endInclusive, range.endInclusive) else -> exclusions[++left] = range } } return RowData(exclusions.take(left + 1), sortedBeacons) } fun parseInput(): Map<Point, Point> { val np = "(-?\\d+)" val pattern = "Sensor at x=$np, y=$np: closest beacon is at x=$np, y=$np".toRegex() val data = mutableMapOf<Point, Point>() readInput(2022, 15).forEachLine { line -> val (sx, sy, bx, by) = pattern.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() } data[Point(sx, sy)] = Point(bx, by) } return data } data class Point(val x: Int, val y: Int) data class RowData(val exclusiveIndices: List<ClosedRange<Int>>, val beaconIndices: List<Int>)
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
2,697
adventofcode
Apache License 2.0
src/day05/Task.kt
dniHze
433,447,720
false
{"Kotlin": 35403}
package day05 import readInput import kotlin.math.max import kotlin.collections.sumOf import kotlin.math.abs fun main() { val input = readInput("day05") println(solvePartOne(input)) println(solvePartTwo(input)) } fun solvePartOne(input: List<String>): Int = input.toLineList() .filterStraightLines() .createLineMatrix() .sumAtLeast2LinesOverlap() fun solvePartTwo(input: List<String>): Int = input.toLineList() .createLineMatrix() .sumAtLeast2LinesOverlap() private fun List<String>.toLineList() = map { string -> string.split(" -> ") } .map { (start, end) -> Line(start.toCoordinates(), end.toCoordinates()) } private fun List<Line>.filterStraightLines() = filter { (start, end) -> start.x == end.x || start.y == end.y } private fun List<Line>.createLineMatrix() = fold( initial = Zero, ) { acc, line -> max(acc, line.max()) } .let { (x, y) -> Array(y + 1) { Array(x + 1) { 0 } } } .also { matrix -> onEach { line -> line.onEachMember { (x, y) -> matrix[y][x] += 1 } } } private fun Array<Array<Int>>.sumAtLeast2LinesOverlap() = sumOf { row -> row.sumOf { amount -> if (amount > 1) 1L else 0L } }.toInt() private fun String.toCoordinates() = split(',') .let { (x, y) -> Coordinates(x.toInt(), y.toInt()) } private fun step(start: Int, end: Int) = when { start == end -> 0 start < end -> 1 else -> -1 } private fun max(first: Coordinates, second: Coordinates) = Coordinates(x = max(first.x, second.x), y = max(first.y, second.y)) private data class Line( val start: Coordinates, val end: Coordinates, ) private data class Coordinates(val x: Int, val y: Int) private val Zero = Coordinates(x = 0, y = 0) private fun Line.onEachMember(block: (Coordinates) -> Unit) { val horizontalStep = step(start.x, end.x) val verticalStep = step(start.y, end.y) repeat(stepsCount()) { count -> block( Coordinates( x = start.x + horizontalStep * count, y = start.y + verticalStep * count ) ) } } private fun Line.stepsCount() = max(abs(end.x - start.x), abs(end.y - start.y)) + 1 private fun Line.max() = max(start, end)
0
Kotlin
0
1
f81794bd57abf513d129e63787bdf2a7a21fa0d3
2,287
aoc-2021
Apache License 2.0
src/Day18.kt
sebokopter
570,715,585
false
{"Kotlin": 38263}
import java.util.* data class Cube(val x: Int, val y: Int, val z: Int) { fun adjacentNeighbours(): Set<Cube> = setOf( Cube(x + 1, y, z), Cube(x - 1, y, z), Cube(x, y + 1, z), Cube(x, y - 1, z), Cube(x, y, z + 1), Cube(x, y, z - 1), ) companion object { fun fromCsv(commaSeparatedValues: String): Cube { val (x, y, z) = commaSeparatedValues.split(",").map { it.toInt() } return Cube(x, y, z) } } } fun main() { fun cubes(input: List<String>) = input .map { line -> Cube.fromCsv(line) }.toSet() fun part1(input: List<String>): Int { val cubes = cubes(input) return cubes.sumOf { cube -> cube.adjacentNeighbours().count { neighbour -> neighbour !in cubes } } } fun part2(input: List<String>): Int { val cubes = cubes(input) val xRange = cubes.minOf { (x, _, _) -> x - 1 }..cubes.maxOf { (x, _, _) -> x + 1 } val yRange = cubes.minOf { (_, y, _) -> y - 1 }..cubes.maxOf { (_, y, _) -> y + 1 } val zRange = cubes.minOf { (_, _, z) -> z - 1 }..cubes.maxOf { (_, _, z) -> z + 1 } fun Cube.inBounds() = x in xRange && y in yRange && z in zRange fun surroundingAir(cubes: Set<Cube>): Set<Cube> { tailrec fun fill(surrounding: Set<Cube>, current: Set<Cube>): Set<Cube> { if (current.isEmpty()) return surrounding val nextSet = current .asSequence() .flatMap { it.adjacentNeighbours() } .filter { it.inBounds() } .filter { it !in cubes && it !in current && it !in surrounding } .toSet() return fill(surrounding + current, nextSet) } return fill(emptySet(), setOf(Cube(xRange.first, yRange.first, zRange.first))) } val surroundingAir = surroundingAir(cubes) return cubes.sumOf { cube -> cube.adjacentNeighbours().count { neighbour -> neighbour in surroundingAir } } } val testInput = readInput("Day18_test") println("part1(testInput): " + part1(testInput)) println("part2(testInput): " + part2(testInput)) check(part1(testInput) == 10) check(part2(testInput) == 10) val testInput2 = readInput("Day18_test2") println("part1(testInput): " + part1(testInput2)) println("part2(testInput): " + part2(testInput2)) check(part1(testInput2) == 64) check(part2(testInput2) == 58) val input = readInput("Day18") println("part1(input): " + part1(input)) println("part2(input): " + part2(input)) }
0
Kotlin
0
0
bb2b689f48063d7a1b6892fc1807587f7050b9db
2,686
advent-of-code-2022
Apache License 2.0