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
src/main/kotlin/day02/Day02.kt
TheSench
572,930,570
false
{"Kotlin": 128505}
package day02 import runDay private fun main() { fun part1(input: List<String>): Int { return input.mapToCombinations().toScores().also(::println).sum() } fun part2(input: List<String>): Int { return input.mapToCombinationsBasedOnResult().toScores().also(::println).sum() } (object {}).runDay( part1 = ::part1, part1Check = 15, part2 = ::part2, part2Check = 12, ) } private fun List<String>.mapToCombinations() = map(String::toThrows).map { throws -> Combination(throws) } private fun List<String>.mapToCombinationsBasedOnResult() = map(String::toCombinationFromThrowAndResult) private fun List<Combination>.toScores() = map(Combination::toScore) private fun Combination.toScore() = yours versus theirs private fun String.toThrows() = split(" ").map(String::toThrow) private fun String.toCombinationFromThrowAndResult() = split(" ").let { (theirs, result) -> Combination(theirs.toThrow(), result.toResult()) } data class Combination(val yours: Throw, val theirs: Throw) { companion object { operator fun invoke(throws: List<Throw>): Combination { val (theirs, yours) = throws return Combination(yours, theirs) } operator fun invoke(theirs: Throw, result: Result) = Combination( result against theirs, theirs ) } } private fun roundScore(yours: Throw, theirs: Throw) = when { yours == theirs -> 3 yours beats theirs -> 6 else -> 0 } infix private fun Throw.versus(other: Throw) = this.shapeScore + roundScore(this, other) private fun Throw.losingThrow() = Throw.winningCombinations[this]!! private fun Throw.winningThrow() = Throw.winningCombinations.entries.find { (_, loser) -> loser == this }?.key!! private infix fun Result.against(theirs: Throw) = when (this) { Result.DRAW -> theirs Result.WIN -> theirs.winningThrow() Result.LOSE -> theirs.losingThrow() } private fun String.toThrow() = when (this) { "A", "X" -> Throw.ROCK "B", "Y" -> Throw.PAPER "C", "Z" -> Throw.SCISSORS else -> throw IllegalArgumentException() } enum class Throw(val shapeScore: Int) { ROCK(1), PAPER(2), SCISSORS(3); infix fun beats(other: Throw) = winningCombinations[this] == other companion object { val winningCombinations = mapOf( ROCK to SCISSORS, PAPER to ROCK, SCISSORS to PAPER, ) } } private fun String.toResult() = when (this) { "X" -> Result.LOSE "Y" -> Result.DRAW "Z" -> Result.WIN else -> throw IllegalArgumentException() } enum class Result { LOSE, DRAW, WIN; }
0
Kotlin
0
0
c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb
2,532
advent-of-code-2022
Apache License 2.0
src/Day22.kt
cypressious
572,898,685
false
{"Kotlin": 77610}
fun main() { data class Point(val x: Int, val y: Int) val mapChars = charArrayOf('.', '#') data class Direction(val dx: Int, val dy: Int, val value: Int) { fun next(x: Int, y: Int, map: List<String>): Point { var newX = x + dx var newY = y + dy if (dx == 1 && (newX > map[newY].lastIndex || map[newY][newX] == ' ')) newX = map[y].indexOfAny(mapChars) else if (dx == -1 && (newX < 0 || map[newY][newX] == ' ')) newX = map[y].lastIndexOfAny(mapChars) else if (dy == 1 && (newY > map.lastIndex || x !in map[newY].indices || map[newY][newX] == ' ')) newY = map.indexOfFirst { x in it.indices && it[newX] != ' ' } else if (dy == -1 && (newY < 0 || x !in map[newY].indices || map[newY][newX] == ' ')) newY = map.indexOfLast { x in it.indices && it[newX] != ' ' } return Point(newX, newY) } } data class Instruction(val steps: Int, val rotation: Int) val regex = """(\d+)(\w)?""".toRegex() val r = Direction(1, 0, 0) val d = Direction(0, 1, 1) val l = Direction(-1, 0, 2) val u = Direction(0, -1, 3) val directions = listOf(r, d, l, u) data class Edge(val face: Int, val direction: Direction) data class MapConfig( val tileSize: Int, val faces: Map<Int, Point>, val transitions: Map<Edge, Edge> ) fun parse(input: List<String>): Pair<List<String>, List<Instruction>> { val map = input.dropLast(2) val instructions = regex .findAll(input.last()) .map { val rotation = when (it.groupValues[2]) { "R" -> 1 "L" -> -1 else -> 0 } Instruction(it.groupValues[1].toInt(), rotation) }.toList() return Pair(map, instructions) } fun part1(input: List<String>): Int { val (map, instructions) = parse(input) var y = 0 var x = map[y].indexOf('.') var dirIndex = 0 for ((steps, rotation) in instructions) { val dir = directions[dirIndex] for (s in 1..steps) { val (newX, newY) = dir.next(x, y, map) if (map[newY][newX] == '#') break x = newX y = newY } dirIndex = Math.floorMod(dirIndex + rotation, directions.size) } return 1000 * (y + 1) + 4 * (x + 1) + directions[dirIndex].value } fun part2(input: List<String>, mapConfig: MapConfig): Int { val (size, faces, transitions) = mapConfig val (map, instructions) = parse(input) val cube = (1..6).associateWith { face -> val (x, y) = faces.getValue(face) map.subList(y * size, (y + 1) * size) .map { it.substring(x * size, (x + 1) * size) } } var y = 0 var x = 0 var face = 1 var dirIndex = 0 fun convert(x: Int, y: Int, oldDir: Direction, newDir: Direction): Point { var newX = Math.floorMod(x, size) var newY = Math.floorMod(y, size) @Suppress("CascadeIf") if (newDir == oldDir) { // do nothing } else if (newDir == r) { newY = when (oldDir) { l -> size - newY - 1 d -> size - newX - 1 u -> newX else -> throw IllegalArgumentException() } newX = 0 } else if (newDir == l) { newY = when (oldDir) { r -> size - newY - 1 d -> newX u -> size - newX - 1 else -> throw IllegalArgumentException() } newX = size - 1 } else if (newDir == d) { newX = when (oldDir) { r -> size - newY - 1 l -> newY u -> size - newX - 1 else -> throw IllegalArgumentException() } newY = 0 } else if (newDir == u) { newX = when (oldDir) { r -> newY d -> size - newX - 1 l -> size - newY - 1 else -> throw IllegalArgumentException() } newY = size - 1 } else { throw IllegalArgumentException() } return Point(newX, newY) } for ((steps, rotation) in instructions) { val dir = directions[dirIndex] var (dx, dy) = dir for (s in 1..steps) { var newY = y + dy var newX = x + dx var newFace = face var newDirIndex = dirIndex if (newX !in 0 until size || newY !in 0 until size) { val transition = transitions.getValue(Edge(face, dir)) newDirIndex = directions.indexOf(transition.direction) newFace = transition.face val p = convert(newX, newY, dir, transition.direction) newX = p.x newY = p.y } if (cube.getValue(newFace)[newY][newX] == '#') break x = newX y = newY face = newFace dirIndex = newDirIndex directions[dirIndex].let { (dxx, dyy) -> dx = dxx; dy = dyy } } dirIndex = Math.floorMod(dirIndex + rotation, directions.size) } val offset = faces.getValue(face) return 1000 * (offset.y * size + y + 1) + 4 * (offset.x * size + x + 1) + directions[dirIndex].value } // test if implementation meets criteria from the description, like: val testInput = readInput("Day22_test") check(part1(testInput) == 6032) check( part2( testInput, MapConfig( 4, mapOf( 1 to Point(2, 0), 2 to Point(0, 1), 3 to Point(1, 1), 4 to Point(2, 1), 5 to Point(2, 2), 6 to Point(3, 2), ), mapOf( Edge(1, r) to Edge(6, l), Edge(1, d) to Edge(4, d), Edge(1, l) to Edge(3, d), Edge(1, u) to Edge(2, d), Edge(2, r) to Edge(3, r), Edge(2, d) to Edge(5, u), Edge(2, l) to Edge(6, u), Edge(2, u) to Edge(1, d), Edge(3, r) to Edge(4, r), Edge(3, d) to Edge(5, r), Edge(3, l) to Edge(2, l), Edge(3, u) to Edge(1, r), Edge(4, r) to Edge(6, d), Edge(4, d) to Edge(5, d), Edge(4, l) to Edge(3, l), Edge(4, u) to Edge(1, u), Edge(5, r) to Edge(6, r), Edge(5, d) to Edge(2, u), Edge(5, l) to Edge(3, u), Edge(5, u) to Edge(4, u), Edge(6, r) to Edge(1, l), Edge(6, d) to Edge(2, r), Edge(6, l) to Edge(5, l), Edge(6, u) to Edge(4, l), ) ) ) == 5031 ) val input = readInput("Day22") println(part1(input)) println( part2( input, MapConfig( 50, mapOf( 1 to Point(1, 0), 2 to Point(2, 0), 3 to Point(1, 1), 4 to Point(0, 2), 5 to Point(1, 2), 6 to Point(0, 3), ), mapOf( Edge(1, r) to Edge(2, r), Edge(1, d) to Edge(3, d), Edge(1, l) to Edge(4, r), Edge(1, u) to Edge(6, r), Edge(2, r) to Edge(5, l), Edge(2, d) to Edge(3, l), Edge(2, l) to Edge(1, l), Edge(2, u) to Edge(6, u), Edge(3, r) to Edge(2, u), Edge(3, d) to Edge(5, d), Edge(3, l) to Edge(4, d), Edge(3, u) to Edge(1, u), Edge(4, r) to Edge(5, r), Edge(4, d) to Edge(6, d), Edge(4, l) to Edge(1, r), Edge(4, u) to Edge(3, r), Edge(5, r) to Edge(2, l), Edge(5, d) to Edge(6, l), Edge(5, l) to Edge(4, l), Edge(5, u) to Edge(3, u), Edge(6, r) to Edge(5, u), Edge(6, d) to Edge(2, d), Edge(6, l) to Edge(1, d), Edge(6, u) to Edge(4, u), ), ) ) ) }
0
Kotlin
0
1
7b4c3ee33efdb5850cca24f1baa7e7df887b019a
9,178
AdventOfCode2022
Apache License 2.0
src/day02/Day02Answer4.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day02 import day02.Gesture.* import day02.Outcome.* import readInput /** * Answers from [Advent of Code 2022 Day 2 | Kotlin](https://youtu.be/Fn0SY2yGDSA) */ fun main() { println(part1()) // 12586 println(part2()) // 13193 } enum class Gesture(val points: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun Gesture.beats(): Gesture { return when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } fun Char.toGesture(): Gesture { return when (this) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> error("Unknown input $this") } } val input = readInput("day02") .map { val (a, b) = it.split(" ") a.first() to b.first() } fun part1(): Int { return input.sumOf { (opponent, you) -> calculateScore(opponent.toGesture(), you.toGesture()) } } fun part2(): Int { return input.sumOf { (opponent, you) -> val yourHand = handForDesiredOutcome(opponent.toGesture(), you.toOutcome()) calculateScore(opponent.toGesture(), yourHand) } } enum class Outcome(val points: Int) { LOSS(0), DRAW(3), WIN(6) } // Calculate the outcome from the perspective of `first` fun calculateOutcome(first: Gesture, second: Gesture): Outcome = when { first == second -> DRAW first.beats() == second -> WIN else -> LOSS } fun calculateScore(opponent: Gesture, you: Gesture): Int { val outcome = calculateOutcome(you, opponent) return you.points + outcome.points } // region part2 fun Char.toOutcome(): Outcome { return when (this) { 'X' -> LOSS 'Y' -> DRAW 'Z' -> WIN else -> error("Unknown input $this") } } fun handForDesiredOutcome(opponentGesture: Gesture, desiredOutcome: Outcome): Gesture { return when (desiredOutcome) { DRAW -> opponentGesture LOSS -> opponentGesture.beats() WIN -> opponentGesture.beatenBy() } } fun Gesture.beatenBy(): Gesture { return when (this) { SCISSORS -> ROCK ROCK -> PAPER PAPER -> SCISSORS } } // endregion
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
2,172
advent-of-code-2022
Apache License 2.0
src/Day11.kt
khongi
572,983,386
false
{"Kotlin": 24901}
class Monkey(chunk: List<String>) { val items = mutableListOf<Long>() val testNumber: Int var inspectCount = 0 private set private val left: String private val right: String private val operation: String private val testTrueMonkey: Int private val testFalseMonkey: Int init { items.addAll(chunk[1].substringAfter(": ").split(", ").map { it.toLong() }) val (l, o, r) = chunk[2].substringAfter("= ").split(" ") left = l right = r operation = o testNumber = chunk[3].substringAfter("by ").toInt() testTrueMonkey = chunk[4].substringAfter("monkey ").toInt() testFalseMonkey = chunk[5].substringAfter("monkey ").toInt() } fun operate(old: Long): Long { val l = if (left == "old") old else left.toLong() val r = if (right == "old") old else right.toLong() return when (operation) { "+" -> l + r "*" -> l * r else -> error("illegal operation: $operation") } } fun test(item: Long): Int { inspectCount++ return if (item % testNumber == 0L) { testTrueMonkey } else { testFalseMonkey } } } fun main() { fun List<Int>.findLcm(): Int { var lcm = max() while (true) { if (count { lcm % it == 0 } != size) { lcm++ } else { return lcm } } } fun round(monkeys: List<Monkey>, lower: (Long) -> Long) { monkeys.forEach { monkey -> val iterator = monkey.items.iterator() while (iterator.hasNext()) { val item = iterator.next() val newItem = monkey.operate(item) val loweredItem = lower(newItem) val monkeyToThrowTo = monkey.test(loweredItem) iterator.remove() monkeys[monkeyToThrowTo].items.add(loweredItem) } } } fun part1(input: List<String>): Int { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeys.add(Monkey(it)) } repeat(20) { round(monkeys) { it / 3 } } monkeys.sortByDescending { it.inspectCount } return monkeys[0].inspectCount * monkeys[1].inspectCount } fun part2(input: List<String>): Long { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { monkeys.add(Monkey(it)) } val lcm = monkeys.map { it.testNumber }.findLcm() repeat(10000) { round(monkeys) { it % lcm } } monkeys.sortByDescending { it.inspectCount } return monkeys[0].inspectCount.toLong() * monkeys[1].inspectCount } val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9cc11bac157959f7934b031a941566d0daccdfbf
2,942
adventofcode2022
Apache License 2.0
2023/src/day05/day05.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day05 import GREEN import RESET import printTimeMillis import readInput val transforms = listOf( "soil", "fertilizer", "water", "light", "temperature", "humidity", "location" ) // 50 98 2 -> LongRange(98..99) offset = 50-98 = -48 // 52 50 48 -> LongRange(50..97) offset = 52-50 = 2 data class Offset( val range: LongRange, val offset: Long, ) data class Garden( val seeds: List<Long>, val srcToDest: Map<String, List<Offset>> ) private fun parseInput(input: List<String>): Garden { val seeds = input.first().split(": ")[1].split(" ").map { it.toLong() } val srcToDest = mutableMapOf<String, MutableList<Offset>>() var end = "" input.drop(1).forEach { if (it.contains("map:")) { // start = it.split("-to-")[0] but we only care about the destination end = it.split("-to-")[1].split(" ")[0] } else { val (destRangeStart, sourceRangeStart, rangeSize) = it.split(" ").map { it.toLong() } if (!srcToDest.containsKey(end)) { srcToDest[end] = mutableListOf() } val offset = Offset( range = LongRange(sourceRangeStart, sourceRangeStart + rangeSize - 1), offset = destRangeStart - sourceRangeStart ) srcToDest[end]!!.add(offset) } } return Garden( seeds = seeds, srcToDest = srcToDest ) } fun traverseGarden(garden: Garden, seed: Long): Long { var current = seed for (transform in transforms) { for (offset in garden.srcToDest[transform]!!) { if (offset.range.contains(current)) { current += offset.offset break } } } return current } fun part1(input: List<String>): Long { val garden = parseInput(input) return garden.seeds.map { traverseGarden(garden, it) }.min() } fun part2(input: List<String>): Long { val garden = parseInput(input) val ranges = garden.seeds.windowed(2, 2) { LongRange(it.first(), it.first() + it[1] - 1) } var min: Long = Long.MAX_VALUE for (range in ranges) { for (i in range) { val score = traverseGarden(garden, i) if (score < min) { min = score } } } return min } fun main() { val testInput = readInput("day05_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day05.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,798
advent-of-code
Apache License 2.0
src/Day13.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
class Packet(var packetList: List<Packet> = mutableListOf<Packet>(), var intVal: Int = -1) : Comparable<Packet> { companion object { private fun Regex.splitWithDelimiter(input: CharSequence) = Regex("((?<=%1\$s)|(?=%1\$s))".format(this.pattern)).split(input) fun of(input: String): Packet { val split = """[,\[\]]""".toRegex().splitWithDelimiter(input).filter { it.isNotBlank() && it != "," } return of(split.iterator()) } private fun of(it: Iterator<String>): Packet { val packets = mutableListOf<Packet>() while (it.hasNext()) { packets += when (val s = it.next()) { "[" -> of(it) "]" -> return Packet(packets) else -> Packet(intVal = s.toInt()) } } return Packet(packets) } } override fun compareTo(other: Packet): Int { if (intVal != -1 && other.intVal != -1) { return intVal.compareTo(other.intVal) } else if (intVal == -1 && other.intVal == -1) { val nonEqualPairs = packetList.zip(other.packetList).map { (mine, theirs) -> mine.compareTo(theirs) }.filter { it != 0 } if (nonEqualPairs.isEmpty()) { return packetList.size.compareTo(other.packetList.size) } else { return nonEqualPairs.first() } } else if (intVal == -1) { return this.compareTo(Packet(listOf(Packet(intVal = other.intVal)))) } else { return Packet(listOf(Packet(intVal = intVal))).compareTo(other) } } override fun toString(): String { var result = "" if (this.packetList.isEmpty()) result += intVal.toString() else { for (p in packetList) { result += p.toString() } } return result } } fun main() { fun part1(input: List<String>): Int { val packets = input.filter { it.isNotBlank() }.map { Packet.of(it) } return packets.chunked(2).mapIndexed { ind, (left, right) -> if (left < right) ind + 1 else 0 }.sum() } fun part2(input: List<String>): Int { val packets = input.filter { it.isNotBlank() }.map { Packet.of(it) }.toMutableList() val ducePacket=Packet.of("[[2]]") val sixerPacket=Packet.of("[[6]]") packets+=ducePacket packets+=sixerPacket packets.sort() return (packets.indexOf(ducePacket)+1)* (packets.indexOf(sixerPacket)+1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") val part1 = part1(input) println(part1) check(part1 == 5390) val part2 = part2(input) println(part2) check(part2==19261) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
2,893
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/EulerCircuit.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph Solution().test() data class DirectedWeightedGraphWithAdjMatrix(val matrix: Array<IntArray>) class Solution { fun test() { println("Test") val graph = DirectedWeightedGraphWithAdjMatrix( arrayOf( intArrayOf(0, 1, 1, 1, 1), intArrayOf(1, 0, 1, 0, 0), intArrayOf(1, 1, 0, 0, 0), intArrayOf(1, 0, 0, 0, 1), intArrayOf(1, 0, 0, 1, 0) ) ) val es = EulerianCycle() val path = es.hasCycle(graph) println(path) } } class EulerianCycle { // https://www.geeksforgeeks.org/eulerian-path-and-circuit/ // O(V+E) for connectivity + degree checks fun hasCycle(graph: DirectedWeightedGraphWithAdjMatrix): Boolean { /* eulerian cycle: all vertices have even degree all vertices (except 0-edge) connected eulerian path: all vertices except 2 have even degree all vertices (except 0-edge) connected */ val degress = countDegrees(graph) val oddCount = degress.count { it % 2 == 1 } println(degress.map { it }) println(oddCount) if (oddCount > 0) return false val visited = BooleanArray(graph.matrix.size) val firstWithEdges = degress.indexOfFirst { it > 0 } if (firstWithEdges == -1) return true // no edges -> counts as cycle! dfs(graph, visited, firstWithEdges) println(visited.map { it }) for (vertice in graph.matrix.indices) { // unconnected node with edges -> no cycle possible! if (!visited[vertice] && degress[vertice] != 0) return false } // all vertices have even degree // + all vertices (except 0-edge) connected return true } private fun dfs( graph: DirectedWeightedGraphWithAdjMatrix, visited: BooleanArray, vertice: Int ) { visited[vertice] = true for (nb in graph.matrix.indices) { if (graph.matrix[vertice][nb] == 1 && !visited[nb]) { dfs(graph, visited, nb) } } } private fun countDegrees(graph: DirectedWeightedGraphWithAdjMatrix): IntArray { val degrees = IntArray(graph.matrix.size) { 0 } for (vertice in graph.matrix.indices) { for (nb in graph.matrix.indices) { if (graph.matrix[vertice][nb] == 1) { degrees[vertice]++ } } } return degrees } } /* Directed graph: https://www.geeksforgeeks.org/euler-circuit-directed-graph/ 1) All vertices with nonzero degree belong to a single strongly connected component. -> Kosaraju's algo 2) In degree is equal to the out degree for every vertex. --> out = adjList size, in = array/vertice property O(E+V) */
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,937
KotlinAlgs
MIT License
numbertheory/ChineseRemainderTheorem.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
/** * To solve ax + by = gcd(a, b) */ object ExtendedEuclidean { data class Answer( val gcd: Long, val x: Long, val y: Long, ) fun solve(a: Long, b: Long): Answer { if (b == 0L) return Answer(a, 1, 0) val (gcd, x, y) = solve(b, a % b) return Answer(gcd, y, x - a / b * y) } } /** * To solve ax = 1 (mod m) * * A solution exists if and only if gcd(a, m) = 1 */ object ModularMultiplicativeInverse { fun solve(a: Long, m: Long): Long? { val (gcd, x) = ExtendedEuclidean.solve(a, m) if (gcd != 1L) return null return x.mod(m) } } /** * The Chinese remainder theorem asserts that if the modulus are pairwise coprime, * and if 0 ≤ remainder < modulus for every congruence, then there is one and only * one answer in `[0, product of all modulus)`. */ object ChineseRemainderTheorem { data class Congruence( val remainder: Long, val modulus: Long, ) fun solve(congruences: List<Congruence>): Long { val productOfAllModulus = congruences.fold(1L) { product, congruence -> Math.multiplyExact(product, congruence.modulus) } return congruences.fold(0L) { acc, (remainder, modulus) -> val m = productOfAllModulus / modulus val mInverse = ModularMultiplicativeInverse.solve(m, modulus)!! (acc + (remainder * m * mInverse).mod(productOfAllModulus)).mod(productOfAllModulus) } } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
1,490
kotlin-lib
Apache License 2.0
src/main/kotlin/days/Day14.kt
butnotstupid
433,717,137
false
{"Kotlin": 55124}
package days class Day14 : Day(14) { override fun partOne(): Any { val init = inputList[0] val to = inputList.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] } return (1..10).fold(init) { str, _ -> str[0] + str.zipWithNext().map { (c, next) -> to.getOrDefault(String(charArrayOf(c, next)), "") + next }.joinToString("") } .groupBy { it }.mapValues { (_, value) -> value.size }.entries.sortedBy { it.value } .let { it.last().value - it.first().value } } override fun partTwo(): Any { val init = inputList[0] val to = inputList.drop(2).map { it.split(" -> ") }.associate { (it[0][0] to it[0][1]) to it[1][0] } val charFreq = init.groupBy { it }.mapValues { (_, value) -> value.size.toLong() }.toMutableMap() val pairCount = init.zipWithNext().groupBy { it }.mapValues { (_, value) -> value.size.toLong() } (1..40).fold(pairCount) { pairs, _ -> val newPairs = mutableMapOf<Pair<Char, Char>, Long>() pairs.forEach { (pair, count) -> if (pair !in to.keys) { newPairs[pair] = count + (newPairs[pair] ?: 0) } else { val left = pair.first to to[pair]!! val right = to[pair]!! to pair.second newPairs[left] = count + (newPairs[left] ?: 0) newPairs[right] = count + (newPairs[right] ?: 0) charFreq[to[pair]!!] = count + (charFreq[to[pair]!!] ?: 0) } } newPairs } return charFreq.entries.sortedBy { it.value } .let { it.last().value - it.first().value } } }
0
Kotlin
0
0
a06eaaff7e7c33df58157d8f29236675f9aa7b64
1,771
aoc-2021
Creative Commons Zero v1.0 Universal
src/Day09.kt
Jintin
573,640,224
false
{"Kotlin": 30591}
import kotlin.math.abs fun main() { fun buildSnack(input: List<String>, length: Int): Int { val list = mutableListOf<Pair<Int, Int>>() repeat(length) { list.add(Pair(0, 0)) } val visit = mutableSetOf<Pair<Int, Int>>() visit.add(Pair(0, 0)) input.forEach { val command = it.split(" ") val count = command[1].toInt() repeat(count) { list[0] = when (command[0]) { "R" -> Pair(list[0].first + 1, list[0].second) "L" -> Pair(list[0].first - 1, list[0].second) "U" -> Pair(list[0].first, list[0].second + 1) "D" -> Pair(list[0].first, list[0].second - 1) else -> list[0] } for (i in 1 until list.size) { val h = list[i - 1] var t = list[i] if (abs(h.first - t.first) + abs(h.second - t.second) > 2) { t = Pair( t.first - if (h.first < t.first) 1 else -1, t.second - if (h.second < t.second) 1 else -1 ) } else if (abs(h.first - t.first) > 1) { t = Pair(t.first - if (h.first < t.first) 1 else -1, t.second) } else if (abs(h.second - t.second) > 1) { t = Pair(t.first, t.second - if (h.second < t.second) 1 else -1) } list[i] = t } visit.add(list[list.size - 1]) } } return visit.size } fun part1(input: List<String>): Int { return buildSnack(input, 2) } fun part2(input: List<String>): Int { return buildSnack(input, 10) } val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
4aa00f0d258d55600a623f0118979a25d76b3ecb
1,946
AdventCode2022
Apache License 2.0
src/Day02.kt
wgolyakov
572,463,468
false
null
fun main() { fun part1(input: List<String>): Int { return input.sumBy { when (it) { "A X" -> 1 + 3 // Rock, Rock, Draw "A Y" -> 2 + 6 // Rock, Paper, Won "A Z" -> 3 + 0 // Rock, Scissors, Lose "B X" -> 1 + 0 // Paper, Rock, Lose "B Y" -> 2 + 3 // Paper, Paper, Draw "B Z" -> 3 + 6 // Paper, Scissors, Won "C X" -> 1 + 6 // Scissors, Rock, Won "C Y" -> 2 + 0 // Scissors, Paper, Lose "C Z" -> 3 + 3 // Scissors, Scissors, Draw else -> 0 } } } fun part2(input: List<String>): Int { return input.sumBy { when (it) { "A X" -> 3 + 0 // Rock, Scissors, Lose "A Y" -> 1 + 3 // Rock, Rock, Draw "A Z" -> 2 + 6 // Rock, Paper, Won "B X" -> 1 + 0 // Paper, Rock, Loss "B Y" -> 2 + 3 // Paper, Paper, Draw "B Z" -> 3 + 6 // Paper, Scissors, Won "C X" -> 2 + 0 // Scissors, Paper, Lose "C Y" -> 3 + 3 // Scissors, Scissors, Draw "C Z" -> 1 + 6 // Scissors, Rock, Won else -> 0 } } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
789a2a027ea57954301d7267a14e26e39bfbc3c7
1,161
advent-of-code-2022
Apache License 2.0
src/Day02.kt
naturboy
572,742,689
false
{"Kotlin": 6452}
enum class Selection { ROCK, PAPER, SCISSOR; fun getSelectionScore(): Int { return this.ordinal + 1 } fun getWinningSelection(): Selection { return Selection.values()[(ordinal + 2) % 3] } fun getLoosingSelection(): Selection { return Selection.values()[(ordinal + 1) % 3] } } fun main() { data class Entry(val first: Int, val second: Int) data class Game(val playerOne: Selection, val playerTwo: Selection) fun Selection.getScoreVs(selection: Selection): Int { if (this == selection) { return 3 } val loosingAgainstSelection = this.getWinningSelection() if (selection == loosingAgainstSelection) { return 6 } return 0 } fun Int.toSelection(): Selection { return Selection.values()[this] } fun parseEntries(input: List<String>): List<Entry> { val entries = input.map { gameInput -> val selectionOne = gameInput.first() - 'A' val selectionTwo = gameInput.last() - 'X' Entry(selectionOne, selectionTwo) } return entries } fun calculateScore(games: List<Game>): Int { return games.sumOf { it.playerTwo.getScoreVs(it.playerOne) + it.playerTwo.getSelectionScore() } } fun part1(input: List<String>): Int { val entries = parseEntries(input) val games = entries.map { Game(it.first.toSelection(), it.second.toSelection()) } return calculateScore(games) } fun part2(input: List<String>): Int { fun Entry.toGameWithStrategy(): Game { val firstSelection = this.first.toSelection() val selectionByStrategy = if (this.second == 1) { firstSelection } else { if (this.second == 2) { firstSelection.getLoosingSelection() } else { firstSelection.getWinningSelection() } } return Game(firstSelection, selectionByStrategy) } val entries = parseEntries(input) val games = entries.map { it.toGameWithStrategy() } return calculateScore(games) } val testInput = readInputLineByLine("Day02_test") check(part1(testInput) == 15) val input = readInputLineByLine("Day02") println(part1(input)) check(part2(testInput) == 12) println(part2(input)) }
0
Kotlin
0
0
852871f58218d80702c3b49dd0fd453096e56a43
2,451
advent-of-code-kotlin-2022
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/PalindromicSubsequence.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
/* Longest Palindromic Subsequence: The longestPalindromicSubsequence function calculates the length of the longest palindromic subsequence in a given string using a 2D array to store intermediate results. Minimum Deletions in a String to Make it a Palindrome: The minDeletionsToMakePalindrome function uses the result of the Longest Palindromic Subsequence approach to find the minimum deletions needed to make the string a palindrome. */ //1. Longest Palindromic Subsequence fun longestPalindromicSubsequence(s: String): Int { val n = s.length // Create a 2D array to store the length of the longest palindromic subsequence val dp = Array(n) { IntArray(n) } // Initialize the diagonal elements with 1 (each character is a palindromic subsequence of length 1) for (i in 0 until n) { dp[i][i] = 1 } // Populate the array using the Palindromic Subsequence approach for (len in 2..n) { for (i in 0 until n - len + 1) { val j = i + len - 1 if (s[i] == s[j] && len == 2) { dp[i][j] = 2 } else if (s[i] == s[j]) { dp[i][j] = dp[i + 1][j - 1] + 2 } else { dp[i][j] = maxOf(dp[i][j - 1], dp[i + 1][j]) } } } return dp[0][n - 1] } fun main() { // Example usage val s = "bbbab" val result = longestPalindromicSubsequence(s) println("Length of the Longest Palindromic Subsequence: $result") } //2. Minimum Deletions in a String to Make it a Palindrome fun minDeletionsToMakePalindrome(s: String): Int { val n = s.length // Use the Longest Palindromic Subsequence approach to find the length of the LPS val lpsLength = longestPalindromicSubsequence(s) // The minimum deletions needed is the difference between the string length and the LPS length return n - lpsLength } fun main() { // Example usage val s = "abca" val result = minDeletionsToMakePalindrome(s) println("Minimum Deletions to Make the String a Palindrome: $result") }
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,061
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/Day07/Day07.kt
AllePilli
572,859,920
false
{"Kotlin": 47397}
package Day07 import checkAndPrint import measureAndPrintTimeMillis import readInput fun main() { val cdCommandRgx = """\$ cd (.*)""".toRegex() val fileRgx = """(\d+) (.*)""".toRegex() val dirRgx = """dir (.*)""".toRegex() fun prepareInput(input: List<String>): List<Directory> { val root = Directory(cdCommandRgx.matchEntire(input.first())!!.groupValues[1], null) var currentDir = root val directories = mutableListOf(root) input.drop(1).forEach { line -> cdCommandRgx.matchEntire(line)?.groupValues?.last()?.let { dirName -> currentDir = when (dirName) { ".." -> currentDir.parent!! "/" -> root else -> currentDir.children.filterIsInstance<Directory>().find { it.name == dirName }!! } } ?: fileRgx.matchEntire(line)?.groupValues?.drop(1)?.let { (size, fileName) -> if (!currentDir.containsFile(fileName)) currentDir + File(fileName, size.toInt()) } ?: dirRgx.matchEntire(line)?.groupValues?.drop(1)?.let { (dirName) -> if (!currentDir.containsDirectory(dirName)) directories += Directory(dirName, currentDir).also(currentDir::plus) } } return directories.toList() } fun part1(directories: List<Directory>): Int = directories.mapNotNull { directory -> directory.totalSize.takeUnless { it > 100000 } }.sum() fun part2(directories: List<Directory>): Int { val totalSpace = 70000000 val neededSpace = 30000000 val totalUsedSpace = directories.first().totalSize val totalAvailableSpace = totalSpace - totalUsedSpace val toFreeUpSpace = neededSpace - totalAvailableSpace return directories.mapNotNull { directory -> directory.totalSize.takeUnless { it < toFreeUpSpace } }.min() } val testInput = prepareInput(readInput("Day07_test")) check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = prepareInput(readInput("Day07")) measureAndPrintTimeMillis { print("part1: ") checkAndPrint(part1(input), 1350966) } measureAndPrintTimeMillis { print("part2: ") checkAndPrint(part2(input), 6296435) } } private open class File(val name: String, val size: Int) { open val totalSize: Int get() = size override fun equals(other: Any?): Boolean = name == (other as? Directory)?.name && size == other.size override fun toString(): String = "Day07.File($name, $size)" } private class Directory(name: String, val parent: Directory?, val children: MutableList<File> = mutableListOf()): File(name, -1) { override val totalSize: Int get() = children.sumOf(File::totalSize) val directories: List<Directory> = children.filterIsInstance<Directory>() val files: List<File> = children.filterNot { it is Directory } fun containsDirectory(directoryName: String) = directories.find { it.name == directoryName } != null fun containsFile(fileName: String) = files.find { it.name == fileName } != null operator fun plus(file: File) = children.add(file) operator fun get(name: String) = children.find { it.name == name } override fun equals(other: Any?): Boolean = name == (other as? Directory)?.name override fun toString(): String = "Dir($name, $totalSize, $children)" }
0
Kotlin
0
0
614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643
3,472
AdventOfCode2022
Apache License 2.0
src/Day02.kt
sgc109
576,491,331
false
{"Kotlin": 8641}
fun main() { val fightScore = mapOf( "A" to mapOf( "X" to 3, "Y" to 6, "Z" to 0, ), "B" to mapOf( "X" to 0, "Y" to 3, "Z" to 6, ), "C" to mapOf( "X" to 6, "Y" to 0, "Z" to 3, ) ) val singleScore = mapOf("X" to 1, "Y" to 2, "Z" to 3) val trans = mapOf( "A" to mapOf( "X" to "Z", "Y" to "X", "Z" to "Y", ), "B" to mapOf( "X" to "X", "Y" to "Y", "Z" to "Z", ), "C" to mapOf( "X" to "Y", "Y" to "Z", "Z" to "X", ) ) fun calcScore(you: String, me: String) = fightScore[you]!![me]!! + singleScore[me]!! fun part1(input: List<String>): Long { return input.sumOf { val (you, me) = it.split(" ") calcScore(you, me) }.toLong() } fun part2(input: List<String>): Long { return input.sumOf { val (you, me) = it.split(" ") calcScore(you, trans[you]!![me]!!) }.toLong() } val testInput = readLines("Day02_test") check(part1(testInput) == 15L) val input = readLines("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
03e4e85283d486430345c01d4c03419d95bd6daa
1,373
aoc-2022-in-kotlin
Apache License 2.0
gcj/y2020/round3/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.round3 private fun solve(): String { val (s, t) = readStrings() val way = generateSequence(t) { x -> prev(s, x) }.toList() return way[way.size / 2] } private fun prev(s: String, t: String): String? { if (s == t) return null val d = List(s.length + 1) { IntArray(t.length + 1) } for (i in s.indices) d[i + 1][0] = i + 1 for (j in t.indices) d[0][j + 1] = j + 1 for (i in s.indices) for (j in t.indices) { if (s[i] == t[j]) { d[i + 1][j + 1] = d[i][j] continue } d[i + 1][j + 1] = minOf(d[i][j], d[i + 1][j], d[i][j + 1]) + 1 } var i = s.length var j = t.length val ansLast = StringBuilder() while (i > 0 && j > 0 && s[i - 1] == t[j - 1]) { ansLast.append(s[i - 1]) i--; j-- } val ans: String ans = if (i == 0) t.substring(1, j) else if (j == 0) s.substring(0, 1) else { if (d[i][j] == d[i - 1][j - 1] + 1) { t.substring(0, j - 1) + s[i - 1] } else if (d[i][j] == d[i - 1][j] + 1) { t.substring(0, j) + s[i - 1] } else { t.substring(0, j - 1) } } return ans + ansLast.toString().reversed() } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ")
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,262
competitions
The Unlicense
src/main/kotlin/com/briarshore/aoc2022/day08/TreeTopTreeHousePuzzle.kt
steveswing
579,243,154
false
{"Kotlin": 47151}
package com.briarshore.aoc2022.day08 import println import readInput @ExperimentalStdlibApi fun main() { fun scenicScore(trees: List<Int>): Int { var count = 0 for (height in trees.drop(1)) { if (height < trees.first()) { count++ } if (height >= trees.first()) { count++ break } } return count } fun visibleFromEdge(trees: List<Int>): Boolean { val treesToEdge = trees.drop(1) return treesToEdge.takeWhile { trees.first() > it }.count() == treesToEdge.size } fun transpose(matrix: List<List<Int>>): List<List<Int>> { val width = matrix.size val height = matrix.first().size if (matrix.any { it.size != height }) { throw IllegalArgumentException("All nested lists must have the same size, but sizes were ${matrix.filter { it.size != height }}") } return (0 until width).map { col -> (0 until height).map { row -> matrix[row][col] } } } fun innerTreesBF(lines: List<String>): Int { val heights = lines.map { s -> s.map { it.digitToInt() } } val rowCount = heights.size val columnCount = heights.first().size var visible = Array(rowCount) { BooleanArray(columnCount) } (0 until rowCount).map { r -> var height = -1 (0 until columnCount).map { c -> if (heights[r][c] > height) { height = heights[r][c] visible[r][c] = true } } height = -1 (columnCount - 1 downTo 0).map { c -> if (heights[r][c] > height) { height = heights[r][c] visible[r][c] = true } } } (0 until columnCount).map { c -> var height = -1 (0 until rowCount).map { r -> if (heights[r][c] > height) { height = heights[r][c] visible[r][c] = true } height = -1 (rowCount - 1 downTo 0).map { r -> if (heights[r][c] > height) { height = heights[r][c] visible[r][c] = true } } } } return visible.sumOf { c -> c.count { it } } } fun innerTrees(lines: List<String>): Int { val grid: List<List<Int>> = lines.map { it.map { c -> c.digitToInt() }.toList() }.toList() val columnWiseGrid: List<List<Int>> = transpose(grid) var visible = mutableSetOf<Pair<Int, Int>>() (1 until grid.size - 1).map { r -> (1 until grid[r].size - 1).map { c -> if (visibleFromEdge(grid[r].drop(c)) || visibleFromEdge(grid[r].reversed().drop(grid[r].size - 1 - c))) { visible.add(Pair(r, c)) } else if (visibleFromEdge(columnWiseGrid[c].drop(r)) || visibleFromEdge(columnWiseGrid[c].reversed().drop(columnWiseGrid[c].size - 1 - r))) { visible.add(Pair(r, c)) } else { } } } return visible.size } fun viewingScores(lines: List<String>): Int { val grid: List<List<Int>> = lines.map { it.map { c -> c.digitToInt() }.toList() }.toList() val columnWiseGrid: List<List<Int>> = transpose(grid) val scores = mutableMapOf<Pair<Int, Int>, Int>() (1 until grid.size - 1).map { r -> (1 until grid[r].size - 1).map { c -> val score = scenicScore(grid[r].drop(c)) * scenicScore(grid[r].reversed().drop(grid[r].size - 1 - c)) * scenicScore(columnWiseGrid[c].drop(r)) * scenicScore(columnWiseGrid[c].reversed().drop(columnWiseGrid[c].size - 1 - r)) scores.put(Pair(r, c), score) } } return scores.values.maxOf { it } } fun outerTrees(lines: List<String>): Int = (lines.size - 1) * 4 fun part1(lines: List<String>): Int { return outerTrees(lines) + innerTrees(lines) } fun part2(lines: List<String>): Int { return viewingScores(lines) } check(scenicScore(listOf(5, 4, 9)) == 2) check(scenicScore(listOf(5, 3)) == 1) check(scenicScore(listOf(5, 5)) == 1) check(scenicScore(listOf(5, 1, 2)) == 2) check(scenicScore(listOf(5, 5, 2)) == 1) check(scenicScore(listOf(5, 3, 3)) == 2) check(scenicScore(listOf(5, 3, 5, 3)) == 2) check(scenicScore(listOf(5, 3)) == 1) check(!visibleFromEdge(listOf(5, 5, 1, 2))) check(visibleFromEdge(listOf(5, 1, 2))) check(!visibleFromEdge(listOf(1, 2))) check(visibleFromEdge(listOf(5, 3, 3, 2))) check(!visibleFromEdge(listOf(3, 3, 2))) check(visibleFromEdge(listOf(3, 2))) check(!visibleFromEdge(listOf(3, 5, 4, 9))) check(!visibleFromEdge(listOf(5, 4, 9))) check(!visibleFromEdge(listOf(4, 9))) check(!visibleFromEdge(listOf(1, 5, 5, 2))) check(!visibleFromEdge(listOf(5, 5, 2))) check(visibleFromEdge(listOf(5, 2))) check(!visibleFromEdge(listOf(3, 3, 5, 6))) check(!visibleFromEdge(listOf(3, 5, 6))) check(!visibleFromEdge(listOf(5, 6))) check(visibleFromEdge(listOf(9, 4, 5, 3))) check(!visibleFromEdge(listOf(4, 5, 3))) check(visibleFromEdge(listOf(5, 3))) check(!visibleFromEdge(listOf(5, 5, 3, 5))) check(!visibleFromEdge(listOf(5, 3, 5))) check(!visibleFromEdge(listOf(3, 5))) check(!visibleFromEdge(listOf(5, 3, 5, 3))) check(!visibleFromEdge(listOf(3, 5, 3))) check(visibleFromEdge(listOf(5, 3))) check(!visibleFromEdge(listOf(1, 3, 4, 9))) check(!visibleFromEdge(listOf(3, 4, 9))) check(!visibleFromEdge(listOf(4, 9))) check(!visibleFromEdge(listOf(3, 5, 5, 0))) check(!visibleFromEdge(listOf(5, 5, 0))) check(visibleFromEdge(listOf(5, 0))) check(!visibleFromEdge(listOf(5, 3, 5, 3))) check(!visibleFromEdge(listOf(3, 5, 3))) check(visibleFromEdge(listOf(5, 3))) check(!visibleFromEdge(listOf(4, 3, 1, 7))) check(!visibleFromEdge(listOf(3, 1, 7))) check(!visibleFromEdge(listOf(1, 7))) val sampleInput = readInput("d8p1-sample") check(outerTrees(sampleInput) == 16) check(innerTreesBF(sampleInput) == 21) check(part1(sampleInput) == 21) check(part2(sampleInput) == 8) val input = readInput("d8p1-input") val part1 = part1(input) check(outerTrees(input) == 98*4) "part1 $part1".println() check(part1 == 1792) val innerTreesBF = innerTreesBF(input) "innerTreesBF $innerTreesBF".println() check(innerTreesBF == 1537) val part2 = part2(input) "part2 $part2".println() check(part2 == 334880) }
0
Kotlin
0
0
a0d19d38dae3e0a24bb163f5f98a6a31caae6c05
6,884
2022-AoC-Kotlin
Apache License 2.0
src/Day09.kt
psy667
571,468,780
false
{"Kotlin": 23245}
import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign fun main() { val id = "09" data class Pos(val y: Int, val x: Int) { operator fun plus(b: Pos): Pos { return Pos(this.y + b.y, this.x + b.x) } override fun toString(): String { return "${this.y} ${this.x}" } } fun parse(input: List<String>): List<Pair<Pos, Int>> { return input.map { val (dir, timesStr) = it.split(" ") val times = timesStr.toInt() when(dir) { "U" -> Pos(-1, 0) "D" -> Pos(1, 0) "R" -> Pos(0, 1) "L" -> Pos(0, -1) else -> Pos(0, 0) } to times } } fun moveTail(head: Pos, tail: Pos): Pos { val diff = (tail.y - head.y) to (tail.x - head.x) if(max(diff.first.absoluteValue, diff.second.absoluteValue) <= 1) { return tail } return Pos(tail.y + diff.first.sign * -1, tail.x + diff.second.sign * -1) } fun part1(input: List<String>): Int { var head = Pos(0, 0) var tail = Pos(0, 0) val visited = mutableSetOf(Pos(0, 0)) parse(input).forEach { val (vec, times) = it repeat(times) { head += vec tail = moveTail(head, tail) visited.add(tail) } } return visited.size } fun part2(input: List<String>): Int { var head = Pos(0, 0) val tail = MutableList(9) {_ -> Pos(0, 0)} val visited = mutableSetOf(Pos(0, 0)) parse(input).forEach { val (vec, times) = it repeat(times) { head += vec var prev = head tail.forEachIndexed{ idx, it -> tail[idx] = moveTail(prev, it) if(idx == tail.lastIndex) { visited.add(tail[idx]) } prev = tail[idx] } } } return visited.size } val testInput = readInput("Day${id}_test") check(part1(testInput) == 13) val input = readInput("Day${id}") println("==== DAY $id ====") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
73a795ed5e25bf99593c577cb77f3fcc31883d71
2,369
advent-of-code-2022
Apache License 2.0
src/Day02.kt
purdyk
572,817,231
false
{"Kotlin": 19066}
enum class Throw { Rock, Paper, Scissor } val Throw.worth: Int get() = when (this) { Throw.Rock -> 1 Throw.Paper -> 2 Throw.Scissor -> 3 } val Throw.beats: Throw get() = when (this) { Throw.Rock -> Throw.Scissor Throw.Paper -> Throw.Rock Throw.Scissor -> Throw.Paper } fun outcome(theirs: Throw, mine: Throw): Int { return when { theirs == mine -> 3 mine.beats == theirs -> 6 else -> 0 } } fun main() { val his = mapOf( "A" to Throw.Rock, "B" to Throw.Paper, "C" to Throw.Scissor ) val ours = mapOf( "X" to Throw.Rock, "Y" to Throw.Paper, "Z" to Throw.Scissor ) fun part1(input: List<String>): String { val rounds = input.map { val (t, m) = it.split(" ") val theirs = his[t]!! val mine = ours[m]!! mine.worth to outcome(theirs, mine) } return rounds.sumOf { it.first + it.second }.toString() } fun ours2(theirs: Throw, outcome: String): Throw { return when (outcome) { "X" -> theirs.beats "Y" -> theirs else -> Throw.values().first { it.beats == theirs } } } fun part2(input: List<String>): String { val rounds = input.map { val (t, m) = it.split(" ") val theirs = his[t]!! val mine = ours2(theirs, m) mine.worth to outcome(theirs, mine) } return rounds.sumOf { it.first + it.second }.toString() } val day = "02" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test").split("\n") check(part1(testInput) == "15") check(part2(testInput) == "12") println("Test: ") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day${day}").split("\n") println("\nProblem: ") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
02ac9118326b1deec7dcfbcc59db8c268d9df096
2,093
aoc2022
Apache License 2.0
src/Day04.kt
Xacalet
576,909,107
false
{"Kotlin": 18486}
/** * ADVENT OF CODE 2022 (https://adventofcode.com/2022/) * * Solution to day 4 (https://adventofcode.com/2022/day/4) * */ fun main() { fun part1(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.count { (elf1, elf2) -> (elf1.first >= elf2.first && elf1.last <= elf2.last) || (elf2.first >= elf1.first && elf2.last <= elf1.last) } } fun part2(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.count { (elf1, elf2) -> (elf1.first >= elf2.first && elf1.first <= elf2.last) || (elf2.first >= elf1.first && elf2.first <= elf1.last) } } val assignments = readInputLines("day04_dataset").map { line -> line.split(",").map { assignment -> assignment.split("-").let { (start, end) -> start.toInt()..end.toInt() } }.let { (a1, a2) -> Pair(a1, a2) } } part1(assignments).println() part2(assignments).println() }
0
Kotlin
0
0
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
1,045
advent-of-code-2022
Apache License 2.0
LeetCode/Range Sum Query - Mutable/main.kt
thedevelopersanjeev
112,687,950
false
null
class SegmentTree(nums: IntArray) { private var treeSize = 1 private var tree: LongArray init { while (this.treeSize < nums.size) { this.treeSize = this.treeSize.shl(1) } this.tree = LongArray(this.treeSize.shl(1)) this.build(nums, 0, 0, this.treeSize) } private fun build(nums: IntArray, x: Int, lx: Int, rx: Int) { if (rx - lx == 1) { if (lx < nums.size) this.tree[x] = nums[lx].toLong() return } val mx = lx + (rx - lx).shr(1) build(nums, x.shl(1) + 1, lx, mx) build(nums, x.shl(1) + 2, mx, rx) this.tree[x] = this.tree[x.shl(1) + 1] + this.tree[x.shl(1) + 2] } private fun update(i: Int, v: Int, x: Int, lx: Int, rx: Int) { if (rx - lx == 1) { this.tree[x] = v.toLong() return } val mx = lx + (rx - lx).shr(1) if (i < mx) { update(i, v, x.shl(1) + 1, lx, mx) } else { update(i, v, x.shl(1) + 2, mx, rx) } this.tree[x] = this.tree[x.shl(1) + 1] + this.tree[x.shl(1) + 2] } private fun query(l: Int, r: Int, x: Int, lx: Int, rx: Int): Long { if (lx >= r || rx <= l) return 0L if (lx >= l && rx <= r) return tree[x] val mx = lx + (rx - lx).shr(1) return query(l, r, x.shl(1) + 1, lx, mx) + query(l, r, x.shl(1) + 2, mx, rx) } fun update(i: Int, v: Int) = update(i, v, 0, 0, this.treeSize) fun query(left: Int, right: Int) = query(left, right, 0, 0, this.treeSize) } class NumArray(nums: IntArray) { private var tree = SegmentTree(nums) fun update(i: Int, v: Int) = tree.update(i, v) fun sumRange(left: Int, right: Int) = tree.query(left, right + 1).toInt() }
0
C++
58
146
610520cc396fb13a03c606b5fb6739cfd68cc444
1,839
Competitive-Programming
MIT License
codeforces/round901/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round901 private fun precalc(n: Int = 5000): List<DoubleArray> { val p = List(n + 1) { DoubleArray(it) } for (i in 1..n) { p[i][0] = 1.0 / i for (j in 1 until i) { if (j >= 2) p[i][j] = (j - 1.0) / i * p[i - 2][j - 2] if (j < i - 1) p[i][j] += (i - j - 1.0) / i * p[i - 2][j - 1] } } return p } private val precalc = precalc() private fun solve(): Double { val (n, m) = readInts() val nei = List(n) { mutableListOf<Int>() } repeat(m) { val (a, b) = readInts().map { it - 1 } nei[a].add(b) } val p = DoubleArray(n) p[n - 1] = 1.0 for (i in n - 2 downTo 0) { val ps = nei[i].map { p[it] }.sortedDescending() p[i] = ps.indices.sumOf { j -> ps[j] * precalc[ps.size][j] } } return p[0] } fun main() = repeat(readInt()) { println(solve()) } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
940
competitions
The Unlicense
src/main/kotlin/Day16.kt
akowal
434,506,777
false
{"Kotlin": 30540}
import Day16.Packet.Literal import Day16.Packet.Operator fun main() { println(Day16.solvePart1()) println(Day16.solvePart2()) } object Day16 { private val input = readInput("day16").single() fun solvePart1(): Int { fun Packet.sumVersions(): Int = when (this) { is Literal -> version is Operator -> version + subpackets.sumOf { it.sumVersions() } } return Bits.fromHex(input).readPacket().sumVersions() } fun solvePart2() = Bits.fromHex(input).readPacket().eval() private fun Bits.readPacket(): Packet { val version = read(3) return when (val type = read(3)) { 4 -> Literal(version, readLiteral()) else -> Operator(version, readSubpackets(), operatorFn(type)) } } private fun operatorFn(type: Int): (List<Packet>) -> Long = when (type) { 0 -> { pkts -> pkts.sumOf { it.eval() } } 1 -> { pkts -> pkts.fold(1) { acc, pkt -> acc * pkt.eval() } } 2 -> { pkts -> pkts.minOf { it.eval() } } 3 -> { pkts -> pkts.maxOf { it.eval() } } 5 -> { (a, b) -> if (a.eval() > b.eval()) 1 else 0 } 6 -> { (a, b) -> if (a.eval() < b.eval()) 1 else 0 } 7 -> { (a, b) -> if (a.eval() == b.eval()) 1 else 0 } else -> error("xoxoxo") } private fun Bits.readLiteral(): Long { var n = 0L var last: Boolean do { last = read(1) == 0 n = (n shl 4) + read(4) } while (!last) return n } private fun Bits.readSubpackets(): List<Packet> { val result = mutableListOf<Packet>() val lenType = read(1) if (lenType == 0) { val numOfBits = read(15) val bits = readBits(numOfBits) while (bits.hasNext()) { result += bits.readPacket() } } else { val numOfPackets = read(11) repeat(numOfPackets) { result += readPacket() } } return result } private sealed interface Packet { val version: Int fun eval(): Long data class Literal( override val version: Int, val value: Long, ) : Packet { override fun eval() = value } data class Operator( override val version: Int, val subpackets: List<Packet>, private val eval: (List<Packet>) -> Long ) : Packet { override fun eval() = eval(subpackets) } } class Bits(private val bits: String) { private var i = 0 fun hasNext() = i < bits.lastIndex fun read(nbits: Int): Int { val result = bits.substring(i until i + nbits).toInt(2) i += nbits return result } fun readBits(nbits: Int): Bits { val result = Bits(bits.substring(i until i + nbits)) i += nbits return result } companion object { fun fromHex(hex: String) = hex.asSequence() .map { it.digitToInt(16) } .map { it.toString(2) } .map { it.padStart(4, '0') } .joinToString(separator = "") .let { Bits(it) } } } }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
3,352
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
src/Day08.kt
khongi
572,983,386
false
{"Kotlin": 24901}
fun main() { fun buildMatrix(input: List<String>): List<List<Int>> { val mtx: MutableList<MutableList<Int>> = mutableListOf() input.forEach { line -> val row = mutableListOf<Int>() line.forEach { row.add(it.digitToInt()) } mtx.add(row) } return mtx } fun List<List<Int>>.buildCol(colIndex: Int): List<Int> { val col = mutableListOf<Int>() for (element in this) { col.add(element[colIndex]) } return col } fun List<List<Int>>.isVisible(rowIndex: Int, colIndex: Int): Boolean { val height = this[rowIndex][colIndex] val row = this[rowIndex] val col = buildCol(colIndex) val leftCheck = row.subList(0, colIndex + 1).count { it >= height } == 1 val rightCheck = row.subList(colIndex, row.size).count { it >= height } == 1 val topCheck = col.subList(0, rowIndex + 1).count { it >= height } == 1 val bottomCheck = col.subList(rowIndex, col.size).count { it >= height } == 1 return leftCheck || rightCheck || topCheck || bottomCheck } fun calculateScore(subList: List<Int>, height: Int, edgeValue: Int): Int { val closestTall = subList.indexOfFirst { it >= height } return if (closestTall == -1) { edgeValue } else { closestTall + 1 } } fun List<List<Int>>.scenicScore(rowIndex: Int, colIndex: Int): Int { val height = this[rowIndex][colIndex] val row = this[rowIndex] val col = buildCol(colIndex) val leftScore = calculateScore(row.subList(0, colIndex).reversed(), height, colIndex) val rightScore = calculateScore(row.subList(colIndex + 1, row.size), height, row.size - colIndex - 1) val topScore = calculateScore(col.subList(0, rowIndex).reversed(), height, rowIndex) val bottomScore = calculateScore(col.subList(rowIndex + 1, col.size), height, col.size - rowIndex - 1) return leftScore * rightScore * topScore * bottomScore } fun part1(input: List<String>): Int { val rows = input[0].length val cols = input.size val mtx = buildMatrix(input) var visibleCount = 0 repeat(rows) { row -> repeat(cols) { col -> if (mtx.isVisible(row, col)) { visibleCount++ } } } return visibleCount } fun part2(input: List<String>): Int { val rows = input[0].length val cols = input.size val mtx = buildMatrix(input) var max = 0 for (r in 1 until rows - 1) { for (c in 1 until cols - 1) { val score = mtx.scenicScore(r, c) if (score > max) { max = score } } } return max } 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
9cc11bac157959f7934b031a941566d0daccdfbf
3,061
adventofcode2022
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day18.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import adventofcode.util.collections.takeWhileDistinct object Day18 : AdventSolution(2018, 18, "Settlers of The North Pole") { override fun solvePartOne(input: String) = generateSequence(ConwayGrid(input), ConwayGrid::next) .drop(10) .first() .resourceValue() override fun solvePartTwo(input: String): Int { val (steps, state) = generateSequence(ConwayGrid(input), ConwayGrid::next) .takeWhileDistinct() .withIndex() .last() val cycleLength = generateSequence(state, ConwayGrid::next) .takeWhileDistinct() .count() val remainingSteps = (1_000_000_000 - steps) % cycleLength return generateSequence(state, ConwayGrid::next) .drop(remainingSteps) .first() .resourceValue() } } private data class ConwayGrid(private val grid: List<List<Char>>) { constructor(input: String) : this(input.lines().map(String::toList)) fun resourceValue() = count('|') * count('#') private fun count(ch: Char) = grid.flatten().count { it == ch } fun next() = grid.indices.map { y -> grid[0].indices.map { x -> typeInNextGeneration(x, y) } }.let(::ConwayGrid) private fun typeInNextGeneration(x: Int, y: Int): Char = when (grid[y][x]) { '.' -> if (countNear(x, y, '|') >= 3) '|' else '.' '|' -> if (countNear(x, y, '#') >= 3) '#' else '|' '#' -> if (countNear(x, y, '|') == 0 || countNear(x, y, '#') <= 1) '.' else '#' else -> throw IllegalStateException() } private fun countNear(x: Int, y: Int, c: Char): Int { var count = 0 for (j in y - 1..y + 1) for (i in x - 1..x + 1) if (grid.getOrNull(j)?.getOrNull(i) == c) count++ return count } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,059
advent-of-code
MIT License
src/main/kotlin/adventofcode2020/solution/Day7.kt
lhess
320,667,380
false
null
package adventofcode2020.solution import adventofcode2020.Solution import adventofcode2020.resource.PuzzleInput class Day7(puzzleInput: PuzzleInput<String>) : Solution<String, Int>(puzzleInput) { private val bags = puzzleInput.intoBags() override fun runPart1() = bags .findParents() .size.run { this - 1 } .apply { check(this == 197) } override fun runPart2() = bags .findCosts() .run { this - 1 } .apply { check(this == 85324) } private fun Set<Bag>.findCosts(bag: String = "shiny gold"): Int = let { bags -> bags.filter { it.parent == bag }.sumBy { it.cost * bags.findCosts(it.child) } + 1 } private fun Set<Bag>.findParents(bag: String = "shiny gold"): Set<String> = filter { it.child == bag }.flatMap { findParents(it.parent) }.toSet() + bag private fun List<String>.intoBags(): Set<Bag> = filterNot { it.contains("no other") } .map { it.replace("""bags?|contain|,|\.""".toRegex(), "").trimEnd() .replace("""\s{2,}""".toRegex(), " ") } .flatMap { line -> line.split("""\s(?=[0-9?])""".toRegex()).run { first() to drop(1) }.let { (parent, others) -> others.map { it.split("""\s""".toRegex(), 2).let { (cost, child) -> Bag(parent, child, cost.toInt()) } } } }.toSet() private data class Bag(val parent: String, val child: String, val cost: Int) }
0
null
0
1
cfc3234f79c27d63315994f8e05990b5ddf6e8d4
1,634
adventofcode2020
The Unlicense
2023/src/day12/day12.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day12 import GREEN import RESET import printTimeMillis import readInput data class Arrangement( val str: String, val records: List<Int> ) { fun isValid() : Boolean { val chunks = str.split(".") .filter { it.contains("#") } .map { it.length } return chunks == records } } private fun nbWays(arr: Arrangement): Int { val toReplace = arr.str.indexOfFirst { it == '?' } if (toReplace == -1) return if (arr.isValid()) 1 else 0 val withDot = arr.str.toCharArray().also { it[toReplace] = '.' } val withDieze = arr.str.toCharArray().also { it[toReplace] = '#' } return nbWays(Arrangement(withDot.concatToString(), arr.records)) + nbWays(Arrangement(withDieze.concatToString(), arr.records)) } fun part1(input: List<String>): Int { val springs = input.map { Arrangement(it.split(" ")[0], it.split(" ")[1].split(",").map { it.toInt() }) } return springs.map { nbWays(it) }.sum() } fun part2(input: List<String>): Int { return 2 } fun main() { val testInput = readInput("day12_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day12.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } // printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,502
advent-of-code
Apache License 2.0
src/Day18.kt
risboo6909
572,912,116
false
{"Kotlin": 66075}
val normals = arrayOf ( Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1), Vector3(-1, 0, 0), Vector3(0, -1, 0), Vector3(0, 0, -1), ) fun main() { fun parse(input: List<String>): List<Vector3> { val coords = input.map{ it -> val tmp = it.split(",").map{it.toInt()} Vector3(tmp[0], tmp[1], tmp[2]) // x, y, z } return coords } fun getNeighbours(pos: Vector3, topLeft: Vector3, bottomRight: Vector3): MutableSet<Vector3> { val res = mutableSetOf<Vector3>() // left if (pos.first - 1 >= topLeft.first) { res.add(Vector3(pos.first - 1, pos.second, pos.third)) } // right if (pos.first + 1 <= bottomRight.first) { res.add(Vector3(pos.first + 1, pos.second, pos.third)) } // top if (pos.second - 1 >= topLeft.second) { res.add(Vector3(pos.first, pos.second - 1, pos.third)) } // bottom if (pos.second + 1 <= bottomRight.second) { res.add(Vector3(pos.first, pos.second + 1, pos.third)) } // z- if (pos.third - 1 >= topLeft.third) { res.add(Vector3(pos.first, pos.second, pos.third - 1)) } // z+ if (pos.third + 1 <= bottomRight.third) { res.add(Vector3(pos.first, pos.second, pos.third + 1)) } return res } fun countFaces(cubes: Set<Vector3>, cube: Vector3): Int { return getNeighbours(cube, Vector3(-100, -100, -100), Vector3(100, 100, 100)). sumOf { 1 - cubes.contains(it).toInt() } } fun part1(input: List<String>): Int { val cubes = parse(input).toSet() return cubes.sumOf { countFaces(cubes, it) } } fun allCubesInside(cubes: Set<Vector3>, topLeft: Vector3, bottomRight: Vector3): Boolean { fun isInside(cube: Vector3): Boolean { return (topLeft.first < cube.first) && (cube.first < bottomRight.first) && (topLeft.second < cube.second) && (cube.second < bottomRight.second) && (topLeft.third < cube.third) && (cube.third < bottomRight.third) } return cubes.all { isInside(it) } } fun part2(input: List<String>): Int { val cubes = parse(input).toSet() val cubesSorted = cubes.sortedWith( compareBy { it.first * it.first + it.second * it.second + it.third * it.third } ) var topLeft = cubesSorted.first() var bottomRight = cubesSorted.last() while (!allCubesInside(cubes, topLeft, bottomRight)) { topLeft = topLeft.sub(Vector3(1, 1, 1)) bottomRight = bottomRight.add(Vector3(1, 1, 1)) } var toGo = getNeighbours(topLeft, topLeft, bottomRight) val checked = mutableSetOf<Vector3>() while (toGo.isNotEmpty()) { val currentPos = toGo.last() toGo.remove(currentPos) toGo = toGo.union( getNeighbours(currentPos, topLeft, bottomRight) ).filter { !checked.contains(it) && !cubes.contains(it) }.toMutableSet() checked.add(currentPos) } return cubes.sumOf { cube -> normals.sumOf { checked.contains(cube.add(it)).toInt() } } } // test if implementation meets criteria from the description, like: 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
bd6f9b46d109a34978e92ab56287e94cc3e1c945
3,676
aoc2022
Apache License 2.0
advent-of-code-2023/src/Day04.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
private const val DAY = "Day04" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 13 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 30 measureAnswer { part2(input()) } } } private fun part1(input: List<Int>): Int = input.sumOf { matches -> if (matches > 0) powerOfTwo(matches - 1) else 0 } private fun powerOfTwo(power: Int) = 1 shl power private fun part2(input: List<Int>): Int { val cardsCount = MutableList(input.size) { 1 } for ((i, matches) in input.withIndex()) { for (diff in 1..matches) { cardsCount[i + diff] += cardsCount[i] } } return cardsCount.sum() } private val spacesRegex = Regex("\\s+") private fun readInput(name: String) = readLines(name).map { line -> val (winningNumbers, myNumbers) = line.substringAfter(":") .split("|") .map { numbers -> numbers.trim().split(spacesRegex).toSet() } (winningNumbers intersect myNumbers).size }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
1,090
advent-of-code
Apache License 2.0
src/day19/Day19.kt
gautemo
317,316,447
false
null
package day19 import shared.getText import shared.separateByBlankLine fun validMessages(input: String): Int{ val (rulesRead, messages) = separateByBlankLine(input).map { it.lines() } val rules = rulesRead.map { Rule(it) } val regex = toRegex(rules, "0") return messages.count { it.matches(Regex(regex)) } } class Rule(ruleInput: String){ val index: String val ruleset: String init{ val (indexRead, rulesRead) = ruleInput.split(':') index = indexRead ruleset = "(" + rulesRead.trim().replace("\"", "") + ")" } } fun toRegex(rules: List<Rule>, check: String): String{ val lookup = Regex("""\d+""").find(check) ?: return check.replace(" ", "") val rule = rules.find { it.index == lookup.value }!! return toRegex(rules, check.replaceRange(lookup.range, rule.ruleset)) } fun validMessagesAltered(input: String): Int{ val (rulesRead, messages) = separateByBlankLine(input).map { it.lines() } val rules = rulesRead.map { Rule(it) } val regex42 = toRegex(rules, "42") val regex31 = toRegex(rules, "31") val regex8 = "${regex42}+" var regex11 = "" repeat(5){ regex11 += "(${regex42}{${it+1}}${regex31}{${it+1}})|" } regex11 = regex11.trimEnd('|') return messages.count { it.matches(Regex("($regex8)($regex11)")) } } fun main(){ val input = getText("day19.txt") var validNr = validMessages(input) println(validNr) validNr = validMessagesAltered(input) println(validNr) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
1,533
AdventOfCode2020
MIT License
src/Day01CalorieCounting.kt
zizoh
573,932,084
false
{"Kotlin": 13370}
fun main() { val input: List<String> = readInput("input/day01") println("largest calorie: ${largestCalorie(input)}") println("sum of largest calories: ${sumOfLargestCalories(input, 3)}") } fun largestCalorie(input: List<String>): Int { var largest = 0 var currentSum = 0 input.forEach { calorie -> if (calorie.isBlank()) { largest = maxOf(largest, currentSum) currentSum = 0 } else { currentSum += calorie.toInt() } } return largest } fun sumOfLargestCalories(input: List<String>, numberOfElves: Int): Int { var currentSum = 0 val largestCalories = mutableListOf<Int>() for (index in 0..input.lastIndex) { if (index < numberOfElves) { largestCalories.add(0) } else { val calorie = input[index] if (calorie.isBlank()) { val smallest = largestCalories.min() largestCalories.remove(smallest) largestCalories.add(maxOf(currentSum, smallest)) currentSum = 0 } else { currentSum += calorie.toInt() } } } val smallest = largestCalories.min() largestCalories.remove(smallest) largestCalories.add(maxOf(currentSum, smallest)) return largestCalories.sum() }
0
Kotlin
0
0
817017369d257cca648974234f1e4137cdcd3138
1,338
aoc-2022
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2023/Day09.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2023.Day09.Direction.BACKWARDS import ru.timakden.aoc.year2023.Day09.Direction.FORWARDS /** * [Day 9: Mirage Maintenance](https://adventofcode.com/2023/day/9). */ object Day09 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day09") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Long { return input.sumOf { s -> val sequences = extractSequencesFromInput(s) for (i in sequences.lastIndex downTo 0) { val nextSequence = sequences.getOrNull(i + 1) sequences[i] = extrapolateSequence(sequences[i], nextSequence, FORWARDS) } sequences.first().last() } } fun part2(input: List<String>): Long { return input.sumOf { s -> val sequences = extractSequencesFromInput(s) for (i in sequences.lastIndex downTo 0) { val nextSequence = sequences.getOrNull(i + 1) sequences[i] = extrapolateSequence(sequences[i], nextSequence, BACKWARDS) } sequences.first().first() } } private fun extractSequencesFromInput(s: String): MutableList<List<Long>> { val sequences = mutableListOf<List<Long>>() var sequence = s.split(" ").map { it.toLong() } sequences += sequence while (sequence.any { it != 0L }) { sequence = generateNextSequence(sequence) sequences += sequence } return sequences } private fun generateNextSequence(sequence: List<Long>) = sequence.windowed(2).map { it.last() - it.first() } private fun extrapolateSequence( sequence: List<Long>, nextSequence: List<Long>?, direction: Direction ): List<Long> { return when (direction) { FORWARDS -> nextSequence?.let { sequence + (sequence.last() + it.last()) } ?: (sequence + 0L) else -> nextSequence?.let { listOf(sequence.first() - it.first()) + sequence } ?: (listOf(0L) + sequence) } } private enum class Direction { FORWARDS, BACKWARDS } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,377
advent-of-code
MIT License
src/Day04.kt
rweekers
573,305,041
false
{"Kotlin": 38747}
fun main() { fun part1(input: List<String>): Int { return input .map { it.split(",", "-") .map { s -> s.toInt() } } .map { Assignments(it[0], it[1]) to Assignments(it[2], it[3]) } .count { it.first.oneFullyOverlapsOther(it.second) } } fun part2(input: List<String>): Int { return input .map { it.split(",", "-") .map { s -> s.toInt() } } .map { Assignments(it[0], it[1]) to Assignments(it[2], it[3]) } .count { it.first.hasOverlapWith(it.second) } } // 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)) } class Assignments(private val start: Int, private val end: Int) { private fun size(): Int = end - start private fun fullyOverlaps(other: Assignments): Boolean = other.start >= this.start && other.end <= this.end fun oneFullyOverlapsOther(other: Assignments): Boolean = if (other.size() >= this.size()) { other.fullyOverlaps(this) } else { this.fullyOverlaps(other) } fun hasOverlapWith(other: Assignments): Boolean { val range = this.start..this.end val otherRange = other.start..other.end return range.any { otherRange.contains(it) } } }
0
Kotlin
0
1
276eae0afbc4fd9da596466e06866ae8a66c1807
1,572
adventofcode-2022
Apache License 2.0
string-similarity/src/commonMain/kotlin/com/aallam/similarity/NGram.kt
aallam
597,692,521
false
null
package com.aallam.similarity import kotlin.math.max import kotlin.math.min /** * N-Gram Similarity as defined by Kondrak, "N-Gram Similarity and Distance", String Processing and Information * Retrieval, Lecture Notes in Computer Science Volume 3772, 2005, pp 115-126. * * The algorithm uses affixing with special character '\n' to increase the weight of first characters. * The normalization is achieved by dividing the total similarity score the original length of the longest word. * * [N-Gram Similarity and Distance](http://webdocs.cs.ualberta.ca/~kondrak/papers/spire05.pdf) * * @param n n-gram length. */ public class NGram(private val n: Int = 2) { /** * Compute n-gram distance, in the range `[0, 1]`. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Double { if (first == second) return 0.0 val sl = first.length val tl = second.length if (sl == 0 || tl == 0) return 1.0 val special = '\n' var cost = 0 if (sl < n || tl < n) { val ni = min(sl, tl) for (i in 0..ni) { if (first[i] == second[i]) cost++ } return cost.toDouble() / max(sl, tl) } // construct `sa` with prefix val sa = CharArray(sl + n - 1) { i -> if (i < n - 1) special else first[i - n + 1] } var p = DoubleArray(sl + 1) { it.toDouble() } // 'previous' cost array, horizontally var d = DoubleArray(sl + 1) // cost array, horizontally var tj = CharArray(n) // jth n-gram of t for (j in 1..tl) { // construct tj n-gram if (j < n) { for (ti in 0..<n - j) { tj[ti] = special // add prefix } for (ti in n - j..<n) { tj[ti] = second[ti - (n - j)] } } else { tj = second.substring(j - n, j).toCharArray() } d[0] = j.toDouble() for (i in 1..sl) { cost = 0 var tn = n // compare sa to tj for (ni in 0..<n) { if (sa[i - 1 + ni] != tj[ni]) { cost++ } else if (sa[i - 1 + ni] == special) { tn-- // discount matches on prefix } } val ec = cost.toDouble() / tn // minimum of cell to the left+1, to the top+1, // diagonally left and up +cost d[i] = minOf(d[i - 1] + 1, p[i] + 1, p[i - 1] + ec) } // copy current distance counts to 'previous row' distance counts val swap = p p = d d = swap } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return p[sl] / max(tl, sl) } }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
3,081
string-similarity-kotlin
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day12.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day12 : Day("5076", "145643") { private data class Node( val id: String, val isSmall: Boolean = id.lowercase() == id, val neighbors: MutableList<Node> = mutableListOf() ) private val caves = getCaves() override fun solvePartOne(): Any { return countPathsPartOne(caves["start"]!!) } override fun solvePartTwo(): Any { return countPathsPartTwo(caves["start"]!!) } private fun getCaves(): Map<String, Node> { val caves = mutableMapOf<String, Node>() for (line in input.lines()) { val (from, to) = line.split("-") if (from !in caves) { caves[from] = Node(from) } if (to !in caves) { caves[to] = Node(to) } caves[from]!!.neighbors.add(caves[to]!!) caves[to]!!.neighbors.add(caves[from]!!) } return caves } private fun countPathsPartOne(node: Node, usedCaves: Set<String> = emptySet()): Int { if (node.id == "end") { return 1 } return node .neighbors .filter { !it.isSmall || it.id !in usedCaves } .sumOf { countPathsPartOne(it, usedCaves + node.id) } } private fun countPathsPartTwo( node: Node, path: List<String> = listOf(node.id), usedPaths: MutableSet<List<String>> = mutableSetOf(), usedCaves: Set<String> = emptySet(), duplicateSmallCave: String? = null, duplicated: Boolean = false, ): Int { if (node.id == "end") { return if (usedPaths.add(path)) 1 else 0 } return node .neighbors .filter { !it.isSmall || (it.id !in usedCaves || (it.id == duplicateSmallCave && !duplicated)) } .sumOf { val newPath = path + it.id val newUsedCaves = usedCaves + node.id val newDuplicated = if (it.id == duplicateSmallCave) true else duplicated var paths = countPathsPartTwo(it, newPath, usedPaths, newUsedCaves, duplicateSmallCave, newDuplicated) if (it.isSmall && duplicateSmallCave == null) { paths += countPathsPartTwo(it, newPath, usedPaths, newUsedCaves, it.id, false) } paths } } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,415
advent-of-code-2021
MIT License
src/main/kotlin/net/voldrich/aoc2023/Day02.kt
MavoCz
434,703,997
false
{"Kotlin": 119158}
package net.voldrich.aoc2023 import net.voldrich.BaseDay // https://adventofcode.com/2023/day/2 fun main() { Day02().run() } class Day02 : BaseDay() { override fun task1(): Int { val marbleCounts = mapOf( "red" to 12, "green" to 13, "blue" to 14 ) return input.lines() .filter { it.isNotBlank() } .map { parseGame(it) } .filter { hasAtLeast(it, marbleCounts) } .sumOf { it.number } } private fun hasAtLeast(game: Game, marbleCounts: Map<String, Int>): Boolean { for ((color, count) in game.colors) { if (marbleCounts.getOrDefault(color, 0) < count) { return false } } return true } override fun task2(): Int { return input.lines() .filter { it.isNotBlank() } .map { parseGame(it) } .map { findMaxPerColorPower(it) } .sumOf { it } } private fun findMaxPerColorPower(game: Game): Int { val max = mutableMapOf<String, Int>() for ((color, count) in game.colors) { if (!max.containsKey(color)) { max[color] = count } else if (max.getOrDefault(color,0) < count) { max[color] = count } } return max.values.reduce { a, b -> a * b } } data class Game(val number: Int, val colors: List<Pair<String, Int>>) fun parseGame(line: String): Game { val parts = line.split(": ", ", ", "; ") val colors = mutableListOf<Pair<String, Int>>() var gameNumber = 0 for (i in parts.indices) { when { parts[i].startsWith("Game") -> gameNumber = parts[i].split(" ")[1].toInt() else -> { val colorParts = parts[i].split(" ") val color = colorParts[1].trim() val count = colorParts[0].toInt() colors.add(Pair(color, count)) } } } return Game(gameNumber, colors) } }
0
Kotlin
0
0
0cedad1d393d9040c4cc9b50b120647884ea99d9
2,124
advent-of-code
Apache License 2.0
Graph.kt
Abijeet123
351,862,917
false
null
import java.util.* private fun readLn() = readLine()!! // string line private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles var n : Int = 1024 var visited = BooleanArray(n) { false } var adj = Array(n) { mutableListOf<Pair<Int,Int>>() } fun toLeaf(root : Int) : Int { if(adj[root].size == 0) return 0 var max = 0 for (i in adj[root]){ max = maxOf(max, 1 + toLeaf(i.first)) } return max } fun diameter() : Int{ var dia = 0 for (i in 0 until n){ var max1 = 0 var max2 = 0 for (j in adj[0]){ var t = 1 + toLeaf(j.first) if (t > max1){ max2 = max1 max1 = t } dia = maxOf(dia, max1 + max2) } } return dia } fun dfs(root : Int){ if (visited[root]) return visited[root] = true println(root) for(i in adj[root]){ dfs(i.first) } } fun dikstra(root : Int) : Array<Int> { var distance = Array(n) { Int.MAX_VALUE } var processed = BooleanArray(n) { false } distance[root] = 0 val compareByDistance: Comparator<Pair<Int,Int>> = compareBy { it.first } var Pq = PriorityQueue<Pair<Int,Int>>(compareByDistance) Pq.add(Pair(0,root)) while (Pq.isNotEmpty()){ var a = Pq.peek().second Pq.remove() if(processed[a]) continue processed[a] = true for( u in adj[a]){ var b = u.first var w = u.second if(distance[a] + w < distance[b]){ distance[b] = distance[a] + w Pq.add(Pair(-distance[b],b)) } } } return distance } fun main(){ n = readInt() var q = readInt() for (i in 0 until q){ val (a,b,c) = readInts() adj[a - 1].add(Pair(b - 1,c)) //adj[b - 1].add(Pair(a-1,c)) } // val distance = dikstra(0) // for (i in distance) // println(i) println(diameter()) }
0
Kotlin
0
0
902adc3660caee6b69a13ac169bb8a7b51245163
2,376
KotlinAlgorithmsImplementations
MIT License
kotlin/src/2022/Day16_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
import kotlin.math.max private val r = Regex("Valve (..) has flow rate=([0-9]+); .* valves? (.*)") private typealias EdgeList = List<Pair<Int, String>> fun main() { val rates = mutableMapOf<String, Int>() val neighs = mutableMapOf<String, List<String>>() readInput(16).trim().lines() .forEach {s -> val groups = r.matchEntire(s)!!.groupValues val node = groups[1] val rate = groups[2].toInt() val neigh = groups[3].split(", ") rates[node] = rate neighs[node] = neigh } // compress the graph: all nodes with rate=0 and only two edges are transient: // e.g: 5 --- 0 ---- 0 ---- 9 // transformed to: 5 --- 9 with an edge length of 3 // most nodes are actually transient in the input val e = mutableMapOf<String, EdgeList>() val transientNodes = rates.filter {it.value == 0 && neighs[it.key]!!.size <= 2}.map {it.key} for ((node, neigh) in neighs) { if (node in transientNodes) continue val dist = mutableMapOf<String, Int>() for (n in neigh) { var (xnode, length) = n to 1 var prev = node while (xnode in transientNodes) { val next = neighs[xnode]!!.first {it != prev} prev = xnode xnode = next length += 1 } dist[xnode] = length } e[node] = dist.map {it.value to it.key} } val idx = e.keys.withIndex().associate { it.value to it.index } // memoize the search function data class CacheEntry(val node: String, val t: Int, val valves: Int, val rep: Int) val cache = mutableMapOf<CacheEntry, Int>() fun returnStore(entry: CacheEntry, ret: Int): Int { cache[entry] = ret return ret } var (initNode, initTime) = "AA" to 30 fun search(node: String, t: Int, valves: Int, rep: Int=0): Int { val cacheEntry = CacheEntry(node, t, valves, rep-1) if (t <= 1) { if (rep > 0) returnStore(cacheEntry, search(initNode, initTime, valves, rep-1)) return 0 } if (cacheEntry in cache) return cache[cacheEntry]!! val g = e[node]!! val (rate, i) = rates[node]!! to idx[node]!! var best = 0 if (rate > 0 && (valves and (1 shl i) == 0)) { val valv = valves or (1 shl i) val plus = (t-1) * rate // check other nodes `n` reached by an edge of length `w` for ((w, n) in g) { if (w >= t - 2) continue // no time for opening the valve after moving best = max(best, search(n, t - w - 1, valv, rep) + plus) } // no other moves, just open valve here, and stop best = max(best, plus) } // check moves to other nodes without opening the valve here for ((w, n) in g) { if (w >= t - 1) continue best = max(best, search(n, t - w, valves, rep)) } // if absolutely no other moves can be made, and we have repetitions left, check the next rep if (g.all {it.first >= t - 1} && rep > 0) return returnStore(cacheEntry, best + search(initNode, initTime, valves, rep-1)) return returnStore(cacheEntry, best) } // part1 println(search(initNode, initTime, 0, 0)) // part2 initTime = 26 println(search(initNode, initTime, 0, 1)) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
3,473
adventofcode
Apache License 2.0
src/Day14.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
fun main() { val lines = readInput("day14_input") val (sandStart, cols) = 500 to 1000 var (ans1, ans2) = 0 to 0 // mapping each point p to an integer k where p_x = k%cols and p_y = k/cols val paths: List<List<Int>> = lines.map { it.split(" -> ").map { it.split(",").map { it.toInt() }.let { it.first() + cols*it.last() } } } val rows = paths.flatten().max()/cols + 2 val points = BooleanArray((rows + 1)*(cols + 1)) paths.forEach { it.windowed(2).forEach { val (l, h) = it.sorted() val range = if (l%cols != h%cols) l..h else l..h step cols range.forEach { points[it] = true } } } val last = points.indices.filter { points[it] }.max() val bottom = (rows*cols until (rows + 1)*cols) bottom.forEach { points[it] = true } while (true) { var k = sandStart while (k < cols*rows) { k += when { !points[k + cols] -> cols !points[k + cols - 1] -> cols - 1 !points[k + cols + 1] -> cols + 1 else -> { points[k] = true; break } } } if (k > last && ans1 == 0) ans1 = ans2 if (points[sandStart]) break ans2++ } println(ans1) println(++ans2) }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
1,309
advent22
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch4/Problem43.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch4 import dev.bogwalk.util.combinatorics.permutations /** * Problem 43: Substring Divisibility * * https://projecteuler.net/problem=43 * * Goal: Find the sum of all 0 to N pandigital numbers that have their 3-digit substrings, * starting from d_2, being divisible by sequential primes. * * Constraints: 3 <= N <= 9 * * Substring Divisibility: The 0 to 9 pandigital, 1_406_357_289 -> * d_2 .. d_4 = 406 % 2 == 0 * d_3 .. d_5 = 063 % 3 == 0 * d_4 .. d_6 = 635 % 5 == 0 * d_5 .. d_7 = 357 % 7 == 0 * d_6 .. d_8 = 572 % 11 == 0 * d_7 .. d_9 = 728 % 13 == 0 * d_8 .. d_10 = 289 % 17 == 0 * * e.g.: N = 3 * sum = 22212 */ class SubstringDivisibility { private val primes = listOf(0, 2, 3, 5, 7, 11, 13, 17) /** * Solution uses built-in function, windowed(), to create a new list of all 3-digit subStrings. * * SPEED (WORST) 6.33s for N = 9 */ fun sumOfPandigitalSubstrings(n: Int): Long { var sum = 0L val digits = '0'..('0' + n) next@for (perm in permutations(digits)) { val pandigital = perm.joinToString("") val subs = pandigital.windowed(3).drop(1) for ((i, sub) in subs.withIndex()) { if (sub.toInt() % primes[i + 1] != 0) continue@next } sum += pandigital.toLong() } return sum } /** * Solution optimised by replacing windowed() with a loop that slides over the permutation, * checking each new subString & breaking early if invalid. * * SPEED (BETTER) 4.85s for N = 9 */ fun sumOfPandigitalSubstringsImproved(n: Int): Long { var sum = 0L val digits = '0'..('0' + n) next@for (perm in permutations(digits)) { val pandigital = perm.joinToString("") for (i in 1 until n - 1) { val sub = pandigital.substring(i..i+2) if (sub.toInt() % primes[i] != 0) continue@next } sum += pandigital.toLong() } return sum } /** * Project Euler specific implementation that only requires the sum of all 0 to 9 pandigital * numbers that have substring divisibility. * * Filtering the generated permutations through a sequence allowed the performance speed to * be improved compared to the previous solution above. * * Filters pandigital permutations based on the following: * * - [d_2, d_4] must be divisible by 2 so d_4 must be an even number. * * - [d_4, d_6] must be divisible by 5 so d_6 must be '0' or '5', which is narrowed down to * '5' as [d_6, d_8] must be divisible by 11 and '0' would not allow pandigital options. * * - [d_3, d_5] must be divisible by 3, so [d_3, d_5].sum() must be also so. * * - If eligible numbers are narrowed down manually, it is proven that d_1 and d_2 are * either '1' or '4' and d_10 is either '7' or '9'. * * SPEED (BEST) 3.24s for N = 9 */ fun sumOf9PandigitalSubstrings(): Long { return permutations('0'..'9') .filter { perm -> perm.first() in "14" && perm.last() in "79" && perm[3].digitToInt() % 2 == 0 && perm[5] == '5' && perm.slice(2..4).sumOf(Char::digitToInt) % 3 == 0 } .sumOf { perm -> var num = perm.joinToString("") for (i in 1..7) { if (num.substring(i..i+2).toInt() % primes[i] != 0) { num = "0" break } } num.toLong() } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,796
project-euler-kotlin
MIT License
src/main/kotlin/days/Day14.kt
hughjdavey
433,597,582
false
{"Kotlin": 53042}
package days import util.Utils.toPair class Day14 : Day(14) { private val template = inputList.first() private val rules = inputList.drop(2).map { it.split(" -> ").toPair() } override fun partOne(): Any { val polymer = pairInsertion(10) return polymer.maxOf { polymer.count { c -> c == it } } - polymer.minOf { polymer.count { c -> c == it } } } override fun partTwo(): Any { val letterCounts = pairInsertionMap(40).filterKeys { it.length == 1 } return letterCounts.values.maxOf { it } - letterCounts.values.minOf { it } } fun pairInsertion(steps: Int, template: String = this.template, rules: List<Pair<String, String>> = this.rules): String { return (1..steps).fold(template) { polymer, _ -> polymer.first() + polymer.windowed(2).map { pair -> val maybeRule = rules.find { it.first == pair } if (maybeRule != null) "${maybeRule.second}${pair[1]}" else pair[1] }.joinToString("") } } fun pairInsertionMap(steps: Int, template: String = this.template, rules: List<Pair<String, String>> = this.rules): Map<String, Long> { val initial = toPolymerMap(template) template.forEach { initial.merge(it.toString(), 1, Long::plus) } return (1..steps).fold(toPolymerMap(template)) { map, _ -> map.filterKeys { map.getOrDefault(it, 0) > 0 }.forEach { (k, v) -> val rule = rules.find { it.first == k } if (rule != null) { map[rule.first] = map[rule.first]?.minus(v) ?: 0 map.merge("${rule.first[0]}${rule.second}", v, Long::plus) map.merge("${rule.second}${rule.first[1]}", v, Long::plus) map.merge(rule.second, v, Long::plus) } } map } } // map containing count of all pairs but also counts of all individual letters // e.g. the NNCB example would yield {NN=1, NC=1, CB=1, N=2, C=1, B=1} fun toPolymerMap(template: String): MutableMap<String, Long> { val map = mutableMapOf<String, Long>() template.windowed(2).forEach { map.merge(it, 1, Long::plus) } template.forEach { map.merge(it.toString(), 1, Long::plus) } return map } }
0
Kotlin
0
0
a3c2fe866f6b1811782d774a4317457f0882f5ef
2,314
aoc-2021
Creative Commons Zero v1.0 Universal
src/Day02.kt
Ajimi
572,961,710
false
{"Kotlin": 11228}
fun main() { fun part1(input: List<Pair<Int, Int>>) = input.sumOf { (opponent, me) -> me + 1 + when (me) { (opponent + 1) % 3 -> 6 opponent -> 3 else -> 0 } } fun part2(input: List<Pair<Int, Int>>): Int = input.sumOf { (opponent, me) -> me * 3 + when (me) { 0 -> (opponent + 2) % 3 1 -> opponent else -> (opponent + 1) % 3 } + 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test").parse() check(part1(testInput) == 15) val input = readInput("Day02").parse() println(part1(input)) println(part2(input)) } private fun List<String>.parse(): List<Pair<Int, Int>> = map { it.split(" ") }.map { (first, second) -> first.first() - 'A' to second.first() - 'X' }
0
Kotlin
0
0
8c2211694111ee622ebb48f52f36547fe247be42
869
adventofcode-2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/Day11.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
//Day 11: Monkey in the Middle //https://adventofcode.com/2022/day/11 import java.io.File import java.math.BigInteger data class Monkey( val id: Int, val items: MutableList<BigInteger>, val operation: (BigInteger) -> BigInteger, val test: (BigInteger) -> Boolean, val monkeyWhenTrue: () -> Int, val monkeyWhenFalse: () -> Int ) { var inspections: Int = 0 companion object { fun fromNote(notes: List<String>): Monkey { return Monkey( notes[0].substringAfter("Monkey ").substringBefore(":").toInt(), notes[1].substringAfter("Starting items: ").split(", ").map { it.toBigInteger() }.toMutableList(), { old -> val operator = notes[2].substringAfter(" new = old ").first() val otherNumber = notes[2].substringAfter("$operator ") val operand = if (otherNumber == "old") old else otherNumber.toBigInteger() return@Monkey when (operator) { '*' -> old.multiply(operand) '+' -> old.add(operand) else -> old } }, { worryLevel -> val divisibleBy = notes[3].substringAfter("by ") return@Monkey BigInteger.ZERO.equals(worryLevel.mod(divisibleBy.toBigInteger())) }, { return@Monkey notes[4].substringAfter("monkey ").toInt() }, { return@Monkey notes[5].substringAfter("monkey ").toInt() } ) } } } fun main() { val input = File("src/main/resources/Day11.txt").readLines().chunked(7) findMonkeyBusiness(input.map { Monkey.fromNote(it) }, 20, true) // findMonkeyBusiness(input.map { Monkey.fromNote(it) }, 10_000, false) } private fun findMonkeyBusiness(monkeys: List<Monkey>, rounds: Int, shouldWorry: Boolean) { (1..rounds).forEach { _ -> monkeys.forEach { monkey: Monkey -> val worries = monkey.items.toMutableList().listIterator() while (worries.hasNext()) { val old = worries.next() val worry = if (shouldWorry) monkey.operation(old).div(BigInteger.valueOf(3L)) else monkey.operation(old) if (monkey.test(worry)) { monkeys[monkey.monkeyWhenTrue()].items.add(worry) } else { monkeys[monkey.monkeyWhenFalse()].items.add(worry) } monkey.items.remove(old) monkey.inspections++ } } } val topMonkeys = monkeys.sortedByDescending { it.inspections }.take(2) println(topMonkeys.first().inspections * topMonkeys.last().inspections) }
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
2,856
advent-of-code
Apache License 2.0
src/main/aoc2022/Day16.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import Search /** * Main idea: * - Reduce the map to traverse by creating an optimized search graph where only the significant nodes * are included. Nodes without valves are not included * - Also include opening a valve in the action. That is each action is move to another valve and open it. * So it's not possible to move to a valve and not open it. You may of cause move past valves in the * original map, but in the optimized search graph that's included in the distance to the destination valve. * - Do a* search on the optimized graph to find the best path to maximize the amount of pressure vented. * Some notes on how this is done and what to keep in mind: * + To avoid negative costs, use amount of pressure not being vented as cost * + Goal state is unknown, so use a goal function instead (stop searching when time is up regardless * of which valves are open and where in the graph the actors are). * + As a cost heuristic move to the closest valve and open the most valuable valve each time. * + The order of in which the valves are opened is important * - Use the same logic for both part 1 (one actor) and part 2 (two actors). * + With one actor, the second actor is stuck at location "Done" all the time and doesn't help out. * + With two actors it's important that they don't move to the same valves * + Having one actor go to A and the other go to B is the same as the first goes to B and the second to A. */ class Day16(input: List<String>) { private data class Valve(val name: String, val flowRate: Int, val leadsTo: List<String>) private val nodes = input.map { line -> val regex = "Valve ([\\w]{2}) has flow rate=(\\d+); tunnels? leads? to valves? (.*)".toRegex() val (valve, rate, leadTo) = regex.find(line)!!.destructured Valve(valve, rate.toInt(), leadTo.split(", ")) } private val nameToValve = nodes.associateBy { it.name } /** * The distances from every significant node to every other significant node. */ private val allDistances = distances() /** * A simple graph over the input just as it's given without any modifications. Used for BFS to find * the shortest paths between significant nodes which is used for the real graph where the main * pathfinding takes place. */ private class VolcanoMap(private val nodes: Map<String, Valve>) : Search.Graph<String> { override fun neighbours(id: String) = nodes[id]!!.leadsTo } /** * The time it takes to go from any valve to any other valve and open that valve. */ private fun distances(): Map<String, Map<String, Int>> { val map = VolcanoMap(nameToValve) val significantNodes = nodes.filter { it.name == "AA" || it.flowRate > 0 } return significantNodes.associate { from -> val res = Search.bfs(map, from.name, null) from.name to significantNodes.filter { it != from && it.name != "AA" } .associate { to -> to.name to res.getPath(to.name).size + 1 } } } /** * Used for the different states while searching. * Time and pressure released needs to be tracked, but it's not used for comparisons between states. * @param pos List of the current positions for the actors, has either one or two values. * @param dist List of remaining distance until the actor reaches the position indicated in pos. * Has either one or two values, at least one value is always 0. * @param openValves The valves that have been opened so far, in the order they were opened. */ private data class State(val pos: List<String>, val dist: List<Int>, val openValves: List<String>) { var timeLeft = 0 var pressureReleased = 0 } /** * An optimized graph representing the volcano and actions that can be taken. The only actions that can be taken * is to walk to an unvisited valve and open the valve there. There is no need to track any intermediate valves * as you always walk the shortest path to the next valve you want to open. * @param distances The time it takes to go from one valve to another and open it (for all combinations of valves) * @param valves A map between valve names and valves. */ private class Graph(val distances: Map<String, Map<String, Int>>, val valves: Map<String, Valve>) : Search.WeightedGraph<State> { val maximumFlowRate = valves.values.sumOf { it.flowRate } // todo: better name val numValves = valves.values.count { it.flowRate > 0 } override fun neighbours(id: State): List<State> { if (id.openValves.size == numValves) { // All valves are open, fast-forward to the end return listOf( State(listOf("Done", "Done"), listOf(0, 0), id.openValves).apply { timeLeft = 0 pressureReleased = id.pressureReleased + id.timeLeft * maximumFlowRate } ) } // Don't walk to valves that the other player is going to val closedValves = valves.values.filter { it.flowRate > 0 && it.name !in id.openValves + id.pos } // moves is a list with two elements: List of all moves for p1 and list of all moves for p2 // Each move is name + time it takes to go there val moves = (id.pos zip id.dist).map { (pos, dist) -> if (dist != 0) { // Continue the move in progress listOf(pos to dist) } else { // Start moving toward a new valve if (closedValves.isEmpty() || pos == "Done") { // Everything open, or already done (elephant is always in done state in part 1): do nothing. listOf("Done" to id.timeLeft) } else { closedValves.map { it.name to distances[pos]!![it.name]!! } } } } // Set of all possible moves pairs, each move pair is a set of my move and the elephant move // Each move is in turn a destination-time pair. val toVisit = mutableSetOf<Set<Pair<String, Int>>>() moves.first().forEach { me -> moves.last().forEach { elephant -> // Never have both go to the same node at once if (me.first != elephant.first) { toVisit.add(setOf(me, elephant)) } } } // Create all the neighbouring states from the move sets. return toVisit.map { moveSet -> val (me, elephant) = moveSet.toList() // Fast-forward to when the next move is done for either actor or to when time is up. val nextTimeLeft = listOf(0, id.timeLeft - me.second, id.timeLeft - elephant.second).max() val timeTaken = id.timeLeft - nextTimeLeft val currentlyVenting = id.openValves.sumOf { valves[it]!!.flowRate } val openValves = id.openValves.toMutableList().apply { // open a valve when time to destination reaches 0 if (me.second - timeTaken == 0) add(me.first) if (elephant.second - timeTaken == 0) add(elephant.first) } State( listOf(me.first, elephant.first), listOf(me.second - timeTaken, elephant.second - timeTaken), openValves ).apply { timeLeft = id.timeLeft - timeTaken pressureReleased = id.pressureReleased + timeTaken * currentlyVenting } } } /** * The cost to move between two states is the amount of pressure that is not being released * during the time it takes to move. */ override fun cost(from: State, to: State): Float { val notVenting = maximumFlowRate - from.openValves.sumOf { valves[it]!!.flowRate } return (notVenting * (from.timeLeft - to.timeLeft)).toFloat() } } /** * Estimate remaining cost by assuming that the distance all actors have to walk to reach a valve is * the shortest distance to any open valve, including from the current position of a player that's * on its way to a valve already. Also assume that all players will open the best valves possible * every time. * * This never overestimates and is fairly close with my input (88% of the real cost when estimating * on the first node on part 2). */ private fun costHeuristic(currentState: State): Float { var timeLeft = currentState.timeLeft var estimatedCost = 0 // Closed valves ordered by the most useful first val closedValves = nodes.filter { it.flowRate > 0 && it.name !in currentState.openValves } .sortedBy { -it.flowRate } .toMutableList() if (closedValves.isEmpty()) { return 0f } val timeLeftToFinishStartedAction = currentState.dist.sum() // at least one is always zero val minDistanceBetweenValves = closedValves.minOf { node -> allDistances[node.name]!!.values.min() } val minDistanceToAValve = if (timeLeftToFinishStartedAction in 1 until minDistanceBetweenValves) { timeLeftToFinishStartedAction } else { minDistanceBetweenValves } var timeToNextOpen = minDistanceToAValve while (timeLeft > 0 && closedValves.isNotEmpty()) { if (timeToNextOpen == 0) { // Each actor that's not done can open a valve repeat(currentState.pos.filter { it != "Done" }.size) { closedValves.removeFirstOrNull() } timeToNextOpen = closedValves.minOfOrNull { node -> allDistances[node.name]!!.values.min() } ?: 0 } else { timeToNextOpen-- } estimatedCost += closedValves.sumOf { it.flowRate } timeLeft-- } return estimatedCost.toFloat() } /** * Find the best path using A* */ private fun solveGeneric(start: State): Int { val res = Search.aStar( graph = Graph(distances(), nameToValve), start = start, goalFn = { node -> node.timeLeft == 0 }, heuristic = ::costHeuristic ) return res.first.pressureReleased } fun solvePart1(): Int { return solveGeneric(State(listOf("AA", "Done"), listOf(0, 0), listOf()).apply { timeLeft = 30 }) } fun solvePart2(): Int { return solveGeneric(State(listOf("AA", "AA"), listOf(0, 0), listOf()).apply { timeLeft = 26 }) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
11,001
aoc
MIT License
src/day02/Day02.kt
Klaus-Anderson
572,740,347
false
{"Kotlin": 13405}
package day02 import readInput import java.rmi.UnexpectedException import java.util.* fun main() { fun part1(input: List<String>): Int { return input.sumOf { string -> returnHumanPlayerMatchOutCome(string[0].toRpsMove(), string[2].toRpsMove()) } } fun part2(input: List<String>): Int { return input.sumOf { string -> val elfPlayerMove = string[0].toRpsMove() returnHumanPlayerMatchOutCome(elfPlayerMove, string[2].getHumanMove(elfPlayerMove)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day02", "Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02", "Day02") println(part1(input)) println(part2(input)) } private fun Char.getHumanMove(elfPlayerMove: RpsMove): RpsMove { return when (this.toString().lowercase()) { "x" -> when (elfPlayerMove) { RpsMove.ROCK -> RpsMove.SCISSORS RpsMove.PAPER -> RpsMove.ROCK RpsMove.SCISSORS -> RpsMove.PAPER } "y" -> when (elfPlayerMove) { RpsMove.ROCK -> RpsMove.ROCK RpsMove.PAPER -> RpsMove.PAPER RpsMove.SCISSORS -> RpsMove.SCISSORS } "z" -> when (elfPlayerMove) { RpsMove.ROCK -> RpsMove.PAPER RpsMove.PAPER -> RpsMove.SCISSORS RpsMove.SCISSORS -> RpsMove.ROCK } else -> throw Exception() } } private fun Char.toRpsMove(): RpsMove { return when (this.toString().lowercase()) { "a", "x" -> RpsMove.ROCK "b", "y" -> RpsMove.PAPER "c", "z" -> RpsMove.SCISSORS else -> throw Exception() } } private fun returnHumanPlayerMatchOutCome(elfPlayerMove: RpsMove, humanPlayerMove: RpsMove) : Int { return when(humanPlayerMove){ RpsMove.ROCK -> 1 + when (elfPlayerMove) { RpsMove.ROCK -> 3 RpsMove.PAPER -> 0 RpsMove.SCISSORS -> 6 } RpsMove.PAPER -> 2 + when (elfPlayerMove) { RpsMove.ROCK -> 6 RpsMove.PAPER -> 3 RpsMove.SCISSORS -> 0 } RpsMove.SCISSORS -> 3 + when (elfPlayerMove) { RpsMove.ROCK -> 0 RpsMove.PAPER -> 6 RpsMove.SCISSORS -> 3 } } } enum class RpsMove { ROCK, PAPER, SCISSORS }
0
Kotlin
0
0
faddc2738011782841ec20475171909e9d4cee84
2,453
harry-advent-of-code-kotlin-template
Apache License 2.0
src/Day08.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
enum class Direction { LEFT, RIGHT, DOWN, UP } fun main() { fun getNextPosition(position: Pair<Int, Int>, direction: Direction): Pair<Int, Int> { val (x, y) = position return when (direction) { Direction.UP -> Pair(x, y - 1) Direction.DOWN -> Pair(x, y + 1) Direction.LEFT -> Pair(x - 1, y) Direction.RIGHT -> Pair(x + 1, y) } } fun isValidPosition(grid: List<String>, position: Pair<Int, Int>): Boolean { return position.first >= 0 && position.first < grid[0].length && position.second >= 0 && position.second < grid.size } fun getHeight(grid: List<String>, position: Pair<Int, Int>): Char { return grid[position.first][position.second] } fun addToSetWhenHigher(grid: List<String>, start: Pair<Int, Int>, direction: Direction, result: MutableSet<Pair<Int, Int>>) { result.add(start) var maxHeight = getHeight(grid, start) var currentPosition = getNextPosition(start, direction) while (isValidPosition(grid, currentPosition)) { val height = getHeight(grid, currentPosition) if (height > maxHeight) { result.add(currentPosition) maxHeight = height } currentPosition = getNextPosition(currentPosition, direction) } } fun part1(input: List<String>): Int { var result = mutableSetOf<Pair<Int, Int>>() val rows = input.size val cols = input[0].length for (y in 0 until rows) { addToSetWhenHigher(input, Pair(0, y), Direction.RIGHT, result) addToSetWhenHigher(input, Pair(cols - 1, y), Direction.LEFT, result) } for (x in 0 until cols) { addToSetWhenHigher(input, Pair(x, 0), Direction.DOWN, result) addToSetWhenHigher(input, Pair(x, rows - 1), Direction.UP, result) } return result.size } fun visibleTrees(grid: List<String>, start: Pair<Int, Int>, direction: Direction): Int { val startHeight = getHeight(grid, start) var trees = 0 var currentPosition = getNextPosition(start, direction) while(isValidPosition(grid, currentPosition)) { trees += 1 if (getHeight(grid, currentPosition) >= startHeight) { break } else { currentPosition = getNextPosition(currentPosition, direction) } } return trees } fun getScenicScore(grid: List<String>, position: Pair<Int, Int>): Int { var score = 1 for (direction in listOf(Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP)) { score *= visibleTrees(grid, position, direction) } return score } fun part2(input: List<String>): Int { var bestScore = 1 for (y in 0 until input.size) { for (x in 0 until input[0].length) { bestScore = Math.max(bestScore, getScenicScore(input, Pair(x, y))) } } return bestScore } 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
77795045bc8e800190f00cd2051fe93eebad2aec
3,307
adventofcode2022
Apache License 2.0
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day15Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith import kotlin.math.abs private const val LEFT = 'L' private const val RIGHT = 'R' private fun solution1(y: Long) = { input: String -> val sensors = parseSensors(input) sensors.impossiblePositions(y) - sensors.beaconsAtY(y).count() } private fun solution2(maxXY: Long) = { input: String -> val (x, y) = parseSensors(input).findDistressBeacon(maxXY) x * 4000000L + y } private fun parseSensors(input: String) = "-?\\d+".toRegex().findAll(input) .map { it.value.toLong() }.windowed(4, step = 4) .map { Sensor(it[0], it[1], it[2], it[3]) }.toList() private fun List<Sensor>.impossiblePositions(y: Long): Long { val positions = sortedEndpoints(y) var lr = 0 var start = 0L var count = 0L positions.forEach { (side, x) -> if (lr == 0) start = x if (side == LEFT) lr++ else lr-- if (lr == 0) count += x - start + 1 } return count } private fun List<Sensor>.beaconsAtY(y: Long) = asSequence().filter { it.beaconY == y }.map { it.beaconX to it.beaconY }.distinct() private fun List<Sensor>.findDistressBeacon(maxXY: Long) = (0..maxXY).asSequence() .map { y -> firstPossibleX(y, maxXY) to y } .first { (x, _) -> x < maxXY } private fun List<Sensor>.firstPossibleX(y: Long, maxX: Long): Long { val positions = sortedEndpoints(y) var lr = 0 var end = 0L positions.forEach { (side, x) -> if (lr == 0 && x > end) return end + 1 if (side == LEFT) lr++ else lr-- if (lr == 0) end = x } return maxX + 1 } private fun List<Sensor>.sortedEndpoints(y: Long) = asSequence().map { it.xsAt(y) } .filter { it != LongRange.EMPTY } .flatMap { listOf(LEFT to it.first, RIGHT to it.last) } .sortedWith { a, b -> if (a.second != b.second) a.second.compareTo(b.second) else a.first.compareTo(b.first) } private class Sensor(private val x: Long, private val y: Long, val beaconX: Long, val beaconY: Long) { private val distanceToBeacon = abs(x - beaconX) + abs(y - beaconY) fun xsAt(sy: Long): LongRange { val q = distanceToBeacon - abs(sy - y) return if (q >= 0) x - q..x + q else LongRange.EMPTY } } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 15 class Day15Test : StringSpec({ "example part 1" { solution1(10) invokedWith exampleInput shouldBe 26L } "part 1 solution" { solution1(2000000) invokedWith input(YEAR, DAY) shouldBe 4724228L } "example part 2" { solution2(20) invokedWith exampleInput shouldBe 56000011L } "part 2 solution" { solution2(4000000) invokedWith input(YEAR, DAY) shouldBe 13622251246513L } }) private val exampleInput = """ Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,828
adventofcode-kotlin
MIT License
AdventOfCode/Challenge2023Day07.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.test.assertEquals class Challenge2023Day07 { private fun solve1(lines: List<String>): Int { val valueMap = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2, ) val hands = mutableListOf<Hand>() lines.forEach { line -> val (currentCardsRaw, winningAmountRaw) = line.split(" ") val currentCards = currentCardsRaw.map { valueMap[it]!! } val winningAmount = winningAmountRaw.toInt() val numberCounts = currentCards.groupingBy { it }.eachCount() val classification = classifyHand(numberCounts) val currentHand = Hand( currentCards, winningAmount, numberCounts, classification, ) hands.add(currentHand) } val sortedHands = hands.sortedWith( compareBy<Hand> { it.classification } .then { h1, h2 -> Hand.compare.compare(h1, h2) }, ) var winningSum = 0 sortedHands.forEachIndexed { index, hand -> winningSum += hand.winningAmount * (index + 1) } return winningSum } data class Hand( val currentCards: List<Int>, val winningAmount: Int, val numberCounts: Map<Int, Int>, val classification: Int, ) { companion object { val compare = Comparator { h1: Hand, h2: Hand -> val minHandSize = minOf(h1.currentCards.size, h2.currentCards.size) for (cardNum in 0 until minHandSize) { val compareResult = h1.currentCards[cardNum].compareTo(h2.currentCards[cardNum]) if (compareResult != 0) return@Comparator compareResult } h1.currentCards.size.compareTo(h2.currentCards.size) } } } private fun classifyHand(numberCounts: Map<Int, Int>): Int { // For simplicity I will map the different types of hands to simple integers, this makes compares straight forward return when { // Five of a kind numberCounts.containsValue(5) -> 7 // Four of a kind numberCounts.containsValue(4) -> 6 // Full house numberCounts.containsValue(3) && numberCounts.containsValue(2) -> 5 // Three of a kind numberCounts.containsValue(3) -> 4 // Two pairs numberCounts.filter { it.value == 2 }.size == 2 -> 3 // One pair numberCounts.filter { it.value == 2 }.size == 1 -> 2 // No matches else -> 1 } } @Test fun test() { val lines = File("./AdventOfCode/Data/Day07-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(6440, exampleSolution1) val realLines = File("./AdventOfCode/Data/Day07-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(realLines) println("Solution 1: $solution1") assertEquals(249748283, solution1) } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
3,703
KotlinCodeJourney
MIT License
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day06/Day06.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day06 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun part1(input: String): Long { var fish = input.split(",").map { it.toInt() } val days = 80 for (i in 1 .. days) { val numberOfZeros = fish.count { it == 0 } val nextFish = fish.map { if (it == 0) 7 else it }.map { it - 1 } fish = nextFish.let { it.plus(IntArray(numberOfZeros) { 8 }.toList()) } } return fish.size.toLong() } fun part2(input: String): Long { val fish = input.split(",").map { it.toInt() } var fishCount = fish.groupBy { it }.map { it.key.toLong() to it.value.count().toULong() }.toMap().toSortedMap() val days = 256 for (i in 1 .. days) { val numberOfZeros = fishCount.getOrDefault(0, 0u) fishCount = fishCount.map { it.key - 1L to it.value }.toMap().toMutableMap().let { it[8] = numberOfZeros it[6] = it.getOrDefault(6, 0u).plus(numberOfZeros) it }.filterKeys { it >= 0 }.toSortedMap() } println(fishCount) return fishCount.values.sum().toLong() } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day06_test") check(part1(testInput.first()) == 5934L) check(part2(testInput.first()) == 26984457539L) val input = Input.readInput("Day06") println(measureTime { println(part1(input.first())) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input.first())) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
1,691
AOC
Apache License 2.0
src/Day03.kt
paul-griffith
572,667,991
false
{"Kotlin": 17620}
private fun String.splitInHalf(): Pair<String, String> { return Pair(this.substring(0, length / 2), this.substring(length / 2)) } private val Char.score: Int get() { val base = this.lowercase().first().code - 96 return if (isUpperCase()) { base + 26 } else { base } } fun main() { fun part1(input: Sequence<String>): Int { return input.sumOf { line -> val (first, second) = line.splitInHalf() // println("$first $second") val intersection = first.toSet().intersect(second.toSet()).first() // println(intersection) val result = intersection.score // println(result) result } } fun part2(input: Sequence<String>): Int { return input.chunked(3).sumOf { group -> // println(group) val common = group.map(String::toSet).reduce { acc, next -> acc intersect next }.first() // println(common) common.score } } // val sample = sequenceOf( // "vJrwpWtwJgWrhcsFMMfFFhFp", // "<KEY>", // "<KEY>", // "w<KEY>", // "ttgJtRGJQctTZtZT", // "CrZsJsPPZsGzwwsLwLmpwMDw", // ) println(part1(readInput("day03"))) println(part2(readInput("day03"))) }
0
Kotlin
0
0
100a50e280e383b784c3edcf65b74935a92fdfa6
1,433
aoc-2022
Apache License 2.0
src/Day01.kt
kkaptur
573,511,972
false
{"Kotlin": 14524}
fun main() { fun part1(input: List<String>): Int { var sum = 0 var highestSum = 0 input.forEach { if (it.isNotBlank()) sum += it.toInt() if (sum > highestSum) highestSum = sum if (it.isBlank()) sum = 0 } return highestSum } fun part2(input: List<String>): Int { val highestSums = mutableListOf(0, 0, 0) var currentSum = 0 var minOfHighestSums = 0 var minOfHighestSumsIndex = 0 var isLastLine = false input.forEachIndexed { index, it -> if (it.isNotBlank()) currentSum += it.toInt() isLastLine = index == input.lastIndex if (it.isBlank() || isLastLine) { minOfHighestSums = highestSums.min() .also { minSum -> minOfHighestSumsIndex = highestSums.indexOf(minSum) } if (currentSum > minOfHighestSums) highestSums[minOfHighestSumsIndex] = currentSum currentSum = 0 } } return highestSums.sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
055073b7c073c8c1daabbfd293139fecf412632a
1,274
AdventOfCode2022Kotlin
Apache License 2.0
src/Day2/Day2.kt
tomashavlicek
571,148,715
false
{"Kotlin": 23780}
package Day2 import CircularList import readInput val shapes = CircularList(listOf(Shape.ROCK, Shape.PAPER, Shape.SCISSORS)) enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun from(s: String): Shape { return when(s) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> ROCK } } } } fun main() { fun part1(input: List<String>): Int { return input.sumOf { val (opponent, me) = it.split(' ') var roundScore = 0 val opponentShape = Shape.from(opponent) val myShape = Shape.from(me) roundScore += myShape.score if (opponentShape == shapes[shapes.indexOf(myShape) -1]) { roundScore += 6 // Win } else if (opponentShape == myShape) { roundScore += 3 // Draw } roundScore } } fun part2(input: List<String>): Int { return input.sumOf { var roundScore = 0 val (opponent, round) = it.split(' ') val opponentShape = Shape.from(opponent) shapes.indexOf(opponentShape) when (round) { "X" -> { roundScore += shapes[shapes.indexOf(opponentShape) - 1].score } "Y" -> { roundScore += 3 roundScore += shapes[shapes.indexOf(opponentShape)].score } "Z" -> { roundScore += 6 roundScore += shapes[shapes.indexOf(opponentShape) + 1].score } } roundScore } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day2/Day2_test") println(part2(testInput)) check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day2/Day2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
899d30e241070903fe6ef8c4bf03dbe678310267
2,098
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val (directories) = scanFs(input) return directories.map { it.getSize() }.filter { it <= 100000 }.sum().toInt() } private fun part2(input: List<String>): Int { val (directories, root) = scanFs(input) val freeSpace = 70000000 - root.getSize() val spaceNeeded = 30000000 - freeSpace val directoryToDeleteSize = directories.map { it.getSize() }.sorted().first { it >= spaceNeeded } return directoryToDeleteSize.toInt() } private fun scanFs( input: List<String> ): Pair<List<FsEntry.Directory>, FsEntry.Directory> { val directories = mutableListOf<FsEntry.Directory>() val rootDirectory = FsEntry.Directory("/", null) var head: FsEntry.Directory = rootDirectory directories.add(rootDirectory) input.forEach { when (val inputParsed = parseInput(it)) { is Input.Command.Cd.In -> { head = head.entries.filterIsInstance<FsEntry.Directory>().find { directory -> directory.name == inputParsed.directory }!! } Input.Command.Cd.Out -> { head = head.parentDirectory!! } Input.Command.Cd.Root -> head = rootDirectory Input.Command.Ls -> Unit is Input.LsEntry.Directory -> { val newDirectory = FsEntry.Directory(inputParsed.name, head) head.entries.add(newDirectory) directories.add(newDirectory) } is Input.LsEntry.File -> { head.entries.add(FsEntry.File(inputParsed.name, head, inputParsed.size)) } } } return directories to rootDirectory } private fun parseInput(inputString: String): Input { val inputSegments = inputString.split(" ") return when { inputSegments[0] == "\$" && inputSegments[1] == "cd" -> { when (inputSegments[2]) { "/" -> Input.Command.Cd.Root ".." -> Input.Command.Cd.Out else -> Input.Command.Cd.In(inputSegments[2]) } } inputSegments[0] == "\$" && inputSegments[1] == "ls" -> Input.Command.Ls inputSegments[0] == "dir" -> Input.LsEntry.Directory(inputSegments[1]) else -> Input.LsEntry.File(inputSegments[1], inputSegments[0].toLong()) } } private sealed interface FsEntry { val name: String val parentDirectory: Directory? fun getSize(): Long data class Directory( override val name: String, override val parentDirectory: Directory? ) : FsEntry { val entries = mutableListOf<FsEntry>() override fun getSize(): Long = entries.sumOf { it.getSize() } } data class File( override val name: String, override val parentDirectory: Directory, val fileSize: Long ) : FsEntry { override fun getSize(): Long = fileSize } } private sealed class Input { sealed class Command : Input() { sealed class Cd : Command() { object Root : Cd() object Out : Cd() data class In(val directory: String) : Cd() } object Ls : Command() } sealed class LsEntry : Input() { abstract val name: String data class Directory(override val name: String) : LsEntry() data class File( override val name: String, val size: Long ) : LsEntry() } }
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
3,760
aoc-2022
Apache License 2.0
src/main/kotlin/day15/Day15.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day15 import java.io.File import kotlin.math.abs fun main() { val data = parse("src/main/kotlin/day15/Day15.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 15 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Sensor( val sx: Int, val sy: Int, val bx: Int, val by: Int, ) @Suppress("SameParameterValue") private fun parse(path: String): List<Sensor> { val pattern = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") return File(path).readLines().map { line -> val (sx, sy, bx, by) = pattern.matchEntire(line)!!.groupValues .drop(1) .map { it.toInt() } Sensor(sx, sy, bx, by) } } private data class Range( val from: Int, val to: Int, ) private fun findCoverage(data: List<Sensor>, y: Int): List<Range> { val ranges = mutableListOf<Range>() for ((sx, sy, bx, by) in data) { val distance = abs(sx - bx) + abs(sy - by) val dx = distance - abs(sy - y) if (dx >= 0) { ranges += Range(sx - dx, sx + dx) } } ranges.sortWith(compareBy(Range::from, Range::to)) val mergedRanges = mutableListOf<Range>() var merged = ranges[0] for (i in 1..ranges.lastIndex) { val range = ranges[i] if (merged.to >= range.to) { continue } if (merged.to >= range.from) { merged = Range(merged.from, range.to) continue } mergedRanges += merged merged = range } mergedRanges += merged return mergedRanges } private fun part1(data: List<Sensor>, target: Int = 2_000_000): Int { val covered = findCoverage(data, target) .sumOf { (from, to) -> abs(to) + abs(from) + 1 } val beacons = data.mapTo(HashSet()) { it.by } .count { it == target } return covered - beacons } private fun part2(data: List<Sensor>, size: Int = 4_000_000): Long { for (y in 0..size) { val ranges = findCoverage(data, y) if (ranges.size > 1) { val x = ranges[0].to + 1 return x.toLong() * 4_000_000L + y.toLong() } } error("Beacon not found!") }
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
2,350
advent-of-code-2022
MIT License
src/Day02.kt
meierjan
572,860,548
false
{"Kotlin": 20066}
import java.lang.IllegalArgumentException private enum class Result( val points: Int ) { WIN(6), DRAW(3), LOSE(0); companion object { fun parse(char: Char) = when (char) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> throw IllegalArgumentException("Unknown RESULT $char") } } } private enum class Weapon( val points: Int ) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun parse(char: Char): Weapon = when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("Unknown WEAPON $char") } } fun fight(other: Weapon) = when { this.weakness == other -> Result.LOSE this.strength == other -> Result.WIN else -> Result.DRAW } val weakness: Weapon get() = when (this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } val strength: Weapon get() = when (this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } } fun day2_part1(input: List<String>): Int = input.map { val (opponentWeapon, yourWeapon) = it.split(" ") .map { Weapon.parse(it.first()) } val matchResult = yourWeapon.fight(opponentWeapon) matchResult.points + yourWeapon.points }.sum() fun day2_part2(input: List<String>): Int = input.map { val (weaponChar, resultChar) = it.split(" ") val opponentWeapon = Weapon.parse(weaponChar.first()) val matchResult = Result.parse(resultChar.first()) val yourWeapon = when (matchResult) { Result.DRAW -> opponentWeapon Result.WIN -> opponentWeapon.weakness Result.LOSE -> opponentWeapon.strength } matchResult.points + yourWeapon.points }.sum() fun main() { val testInput = readInput("Day02_1_test") check(day2_part1(testInput) == 15) val input = readInput("Day02_1") println(day2_part1(input)) check(day2_part2(testInput) == 12) println(day2_part2(input)) }
0
Kotlin
0
0
a7e52209da6427bce8770cc7f458e8ee9548cc14
2,254
advent-of-code-kotlin-2022
Apache License 2.0
stepik/sportprogramming/ContuneousBagProblemGreedyAlgorithm.kt
grine4ka
183,575,046
false
{"Kotlin": 98723, "Java": 28857, "C++": 4529}
package stepik.sportprogramming private val things = mutableListOf<Thing>() fun main() { val (n, maxWeight) = readPair() repeat(n) { things.add(readThing()) } println("Maximum value of all things is ${solution(maxWeight)}") } private fun solution(maxWeight: Int): Int { val sortedByValue = things.sortedDescending() var sum = 0 var sumWeight: Int = maxWeight for (i in 0 until sortedByValue.size) { if (sumWeight <= 0) { break } val thing = sortedByValue[i] if (sumWeight >= thing.weight) { sumWeight -= thing.weight sum += thing.cost } else { sum += (sumWeight * thing.getValue()) sumWeight -= thing.weight } } return sum } private class Thing(val weight: Int, val cost: Int) : Comparable<Thing> { override fun compareTo(other: Thing): Int { return getValue() - other.getValue() } fun getValue(): Int { return cost / weight } } private fun readPair(): Pair<Int, Int> { val conditions = readLine()!!.split(" ").map(String::toInt).toIntArray() return Pair(conditions[0], conditions[1]) } private fun readThing(): Thing { val thing = readLine()!!.split(" ").map(String::toInt).toIntArray() return Thing(thing[0], thing[1]) }
0
Kotlin
0
0
c967e89058772ee2322cb05fb0d892bd39047f47
1,335
samokatas
MIT License
src/aoc2023/Day17.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput import java.util.* fun main() { val (year, day) = "2023" to "Day17" fun minHeatLoss(map: List<String>, minSteps: Int, maxSteps: Int): Int { val input = map.map { line -> line.map { it.digitToInt() } } val rows = input.size val cols = input.first().size val hitLossForPos = Array(rows) { row -> IntArray(cols) { col -> if (row == 0 && col == 0) 0 else Int.MAX_VALUE } } val visitedState = mutableSetOf<MoveState>() val stateQueue = PriorityQueue<MoveState>() stateQueue.add(MoveState()) while (stateQueue.isNotEmpty()) { val state = stateQueue.remove() if (state in visitedState) continue visitedState.add(state) val (row, col, avoidDir) = state for (dir in listOf(Right, Left, Up, Down)) { var (moveRow, moveCol) = row to col var hitLoss = state.hitLoss if (!(row == 0 && col == 0 || dir != avoidDir && dir != avoidDir.inv())) continue for (move in 1..maxSteps) { moveRow += dir.dr moveCol += dir.dc if (moveRow !in 0..<rows || moveCol !in 0..<cols) continue hitLoss += input[moveRow][moveCol] if (move !in minSteps..maxSteps) continue hitLossForPos[moveRow][moveCol] = minOf(hitLoss, hitLossForPos[moveRow][moveCol]) val movedState = MoveState(moveRow, moveCol, dir).apply { this.hitLoss = hitLoss } stateQueue.add(movedState) } } } return hitLossForPos.last().last() } fun part1(input: List<String>) = minHeatLoss(map = input, minSteps = 1, maxSteps = 3) fun part2(input: List<String>) = minHeatLoss(map = input, minSteps = 4, maxSteps = 10) val testInput1 = readInput(name = "${day}_test1", year = year) val testInput2 = readInput(name = "${day}_test2", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput1), 102) println(part1(input)) checkValue(part2(testInput1), 94) checkValue(part2(testInput2), 71) println(part2(input)) } data class MoveState( val row: Int = 0, val col: Int = 0, val avoidDir: MoveDirection = Up, ) : Comparable<MoveState> { var hitLoss: Int = 0 override fun compareTo(other: MoveState) = hitLoss.compareTo(other.hitLoss) } sealed class MoveDirection(val dr: Int, val dc: Int) { fun inv() = when (this) { Down -> Up Left -> Right Right -> Left Up -> Down } } data object Right : MoveDirection(0, 1) data object Left : MoveDirection(0, -1) data object Up : MoveDirection(-1, 0) data object Down : MoveDirection(1, 0)
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,949
aoc-kotlin
Apache License 2.0
src/main/kotlin/day8/Day8.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day8 import execute import readAllText import kotlin.math.absoluteValue fun main() { val test = """ 30373 25512 65332 33549 35390 """.trimIndent() val input = readAllText("local/day8_input.txt") execute(::part1, test) execute(::part1, input) execute(::part2, test) execute(::part2, input) } fun part1(input: String) = input.lineSequence().filterNot(String::isBlank).toList().let { rows -> rows.indices.sumOf { y -> rows.first().indices.count { x -> val c = rows[y][x] val u = (y - 1 downTo 0).all { i -> rows[i][x] < c } val d = (y + 1..rows.lastIndex).all { i -> rows[i][x] < c } val l = (x - 1 downTo 0).all { i -> rows[y][i] < c } val r = (x + 1..rows.first().lastIndex).all { i -> rows[y][i] < c } u || d || l || r } } } fun IntProgression.distanceTo(op: (Int) -> Boolean): Int = asSequence().takeWhile { !op(it) }.lastOrNull() ?.let { (it - first).absoluteValue + if (it == last) 1 else 2 } ?: 0 fun part2(input: String) = input.lines().filterNot(String::isBlank).let { rows -> rows.indices.maxOf { y -> rows.first().indices.maxOf { x -> val c = rows[y][x] val u = (y - 1 downTo 0).distanceTo { i -> rows[i][x] >= c } val d = (y + 1..rows.lastIndex).distanceTo { i -> rows[i][x] >= c } val l = (x - 1 downTo 0).distanceTo { i -> rows[y][i] >= c } val r = (x + 1..rows.first().lastIndex).distanceTo { i -> rows[y][i] >= c } u * d * l * r } } }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
1,625
advent-of-code-2022
MIT License
src/main/kotlin/com/sk/topicWise/monotonicStack/907. Sum of Subarray Minimums.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.topicWise.monotonicStack import kotlin.math.abs class Solution907 { fun sumSubarrayMins(arr: IntArray): Int { val MAX = 1_000_000_007 val M = 3_000_1 var ans = 0 val dp = Array(arr.size) { IntArray(arr.size) { M } } for (i in arr.indices) { for (j in 0..i) { if (j == i) { dp[j][i] = arr[i] } else { dp[j][i] = minOf(dp[j][i - 1], arr[i]) } ans = ((ans + dp[j][i]) % MAX).toInt() //println("j=$j, i=$i, min=${dp[j][i]}") } } return ans } fun sumSubarrayMins2(A: IntArray): Int { val stack = ArrayDeque<Int>() val dp = IntArray(A.size + 1) stack.addLast(-1) var result = 0 val M = 1e9.toInt() + 7 for (i in A.indices) { while (stack.last() != -1 && A[stack.last()] >= A[i] ) { // monotone increasing stack stack.removeLast() } dp[i + 1] = (dp[stack.last() + 1] + (i - stack.last()) * A[i]) % M stack.addLast(i) result += dp[i + 1] result %= M } return result } fun minimumPushes(word: String): Int { val list = word.groupBy { it }.map { it.value.size } // val arr = IntArray(26) // for(ch in word.toCharArray()) { // arr[ch-'a']++ // } // val list = arr.sorted().reversed().toList() val q = list.size/8 val r = list.size % 8 var ans = 0 for (i in 1..q) { ans += (i*8) } ans += (r*8) return ans } fun countOfPairs(n: Int, x: Int, y: Int): IntArray { val mat = Array(n+1) { IntArray(n+1) } for (i in 1.. mat.lastIndex) { for (j in 1.. mat[0].lastIndex) { mat[i][j] = abs(i-j) mat[j][i] = abs(i-j) } } mat[x][y] = 1 mat[y][x] = 1 for (i in 1..minOf(x, y)) { for (j in maxOf(x, y) .. n) { mat[i][j] = mat[i][j] - abs(x-y) mat[j][i] = mat[j][i] - abs(x-y) } } val ans = IntArray(n) for (i in 1.. mat.lastIndex) { for (j in 1.. mat[0].lastIndex) { ans[mat[i][j]-1]++ ans[mat[j][i]-1]++ } } return ans } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,478
leetcode-kotlin
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day06/day6.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day06 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val line = inputFile.bufferedReader().readLines().first() val initialFish = createFish(line) val fishAfter80Days = (1..80).fold(initialFish) { acc, _ -> simulateDay(acc) } println("Fish count after 80 days: ${fishAfter80Days.size}") val fishAfter256Days = (1..256).fold(convertV1StateToV2(initialFish)) { acc, _ -> simulateDayV2(acc) } println("Fish count after 256 days: ${countFish(fishAfter256Days)}") } data class Fish(val timer: Int) fun createFish(line: String): List<Fish> { return line.split(',') .map { Fish(timer = it.toInt()) } } fun simulateDay(fish: List<Fish>): List<Fish> { return fish.flatMap { when (it.timer) { 0 -> listOf(Fish(timer = 6), Fish(timer = 8)) else -> listOf(Fish(timer = it.timer.dec())) } } } fun convertV1StateToV2(fish: List<Fish>): Map<Int, Long> { return fish.groupingBy { it.timer }.fold(0L) { acc, _ -> acc.inc() } } fun simulateDayV2(fishGroups: Map<Int, Long>): Map<Int, Long> { return buildMap { fishGroups.forEach { when (it.key) { 0 -> { merge(6, it.value, Long::plus) merge(8, it.value, Long::plus) } else -> merge(it.key.dec(), it.value, Long::plus) } } } } fun countFish(fishGroups: Map<Int, Long>): Long = fishGroups.values.reduce(Long::plus)
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,587
advent-of-code
MIT License
src/Day03.kt
tigerxy
575,114,927
false
{"Kotlin": 21255}
fun main() { fun part1(input: List<String>): Int { return input .mapNotNull { backpack -> val chars = backpack.toCharArray().toList() val compartments = chars.chunked(chars.size / 2) compartments.first().find { compartments.last().contains(it) } } .sumOf { it.toPriority() } } fun part2(input: List<String>): Int { return input .map { backpack -> backpack.toCharArray().toList() } .chunked(3) .mapNotNull { elfs -> elfs[0].find { elfs[1].contains(it) && elfs[2].contains(it) } } .sumOf { it.toPriority() } } val day = "03" // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") val testOutput1 = part1(testInput) println("part1_test=$testOutput1") assert(testOutput1 == 13140) val testOutput2 = part2(testInput) println("part2_test=$testOutput2") assert(testOutput2 == 70) val input = readInput("Day$day") println("part1=${part1(input)}") println("part2=${part2(input)}") } private fun Char.toPriority() = when { code < 96 -> code - 38 else -> code - 96 }
0
Kotlin
0
1
d516a3b8516a37fbb261a551cffe44b939f81146
1,343
aoc-2022-in-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/MinCostConnectPoints.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode import kotlin.math.abs /** * 1584. 连接所有点的最小费用 * * 给你一个points 数组,表示 2D 平面上的一些点,其中 points[i] = [xi, yi] 。 * * 连接点 [xi, yi] 和点 [xj, yj] 的费用为它们之间的 曼哈顿距离 :|xi - xj| + |yi - yj| ,其中 |val| 表示 val 的绝对值。 * * 请你返回将所有点连接的最小总费用。只有任意两点之间 有且仅有 一条简单路径时,才认为所有点都已连接。 * */ class MinCostConnectPoints { companion object { @JvmStatic fun main(args: Array<String>) { // 输入:points = [[0,0],[2,2],[3,10],[5,2],[7,0]] // 输出:20 println(MinCostConnectPoints().solution(arrayOf( intArrayOf(0, 0), intArrayOf(2, 2), intArrayOf(3, 10), intArrayOf(5, 2), intArrayOf(7, 0) ))) // 输入:points = [[3,12],[-2,5],[-4,1]] // 输出:18 println(MinCostConnectPoints().solution(arrayOf( intArrayOf(3, 12), intArrayOf(-2, 5), intArrayOf(-4, 1) ))) } } fun solution(points: Array<IntArray>): Int { val n = points.size var result = 0 val edgeList = arrayListOf<Edge>() val union = DisJoinSetUnion(n) var i = 0 while (i < n) { var j = i + 1 while (j < n) { edgeList.add(Edge(dis(points[i], points[j]), i, j)) j++ } i++ } // 贪心 edgeList.sortWith(Comparator { o1, o2 -> o1.len - o2.len }) var count = 1 for (edge in edgeList) { if (union.setUnion(edge.x, edge.y)) { result += edge.len count++ if (count == n) { break } } } return result } private fun dis(pointA: IntArray, pointB: IntArray): Int { return abs(pointA[0] - pointB[0]) + abs(pointA[1] - pointB[1]) } // 并查集 class DisJoinSetUnion(n: Int) { private val parent: IntArray = IntArray(n) private val rank: IntArray = IntArray(n) init { var i = 0 while (i < n) { parent[i] = i rank[i] = 1 i++ } } private fun find(index: Int): Int = if (parent[index] == index) index else find(parent[index]) fun setUnion(x: Int, y: Int): Boolean { var pX = find(x) var pY = find(y) if (pX == pY) return false if (rank[pX] < rank[pY]) { val temp = pX pX = pY pY = temp } // y 合并到 x rank[pX] += rank[pY] parent[pY] = pX return true } } data class Edge(val len: Int, val x: Int, val y: Int) }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,144
daily_algorithm
Apache License 2.0
src/Day09.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
import kotlin.math.abs private operator fun String.component1() = when (this.substringBefore(' ')) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT else -> Direction.RIGHT } private operator fun String.component2() = this.substringAfter(' ').toInt() private enum class Direction { UP, DOWN, LEFT, RIGHT } private data class RopePosition(val x: Int = 0, val y: Int = 0) { fun move(direction: Direction): RopePosition = when (direction) { Direction.UP -> RopePosition(this.x, this.y + 1) Direction.DOWN -> RopePosition(this.x, this.y - 1) Direction.LEFT -> RopePosition(this.x - 1, this.y) Direction.RIGHT -> RopePosition(this.x + 1, this.y) } fun follow(other: RopePosition): RopePosition { if (this.distanceFrom(other) <= 1) return this var (x, y) = this if (this.x != other.x) x += if (this.x < other.x) 1 else -1 if (this.y != other.y) y += if (this.y < other.y) 1 else -1 return RopePosition(x, y) } private fun distanceFrom(other: RopePosition) = maxOf(abs(other.x - this.x), abs(other.y - this.y)) override fun equals(other: Any?): Boolean = (other is RopePosition) && this.x == other.x && this.y == other.y override fun toString(): String = "(${this.x}, ${this.y})" } private class Rope(size: Int) { private val knots = Array(size) { RopePosition() } fun move(direction: Direction): RopePosition { knots[0] = knots[0].move(direction) // Depois de mover a cabeça, todos os outros nós devem seguir o movimento do nó à frente for ( (head, tail) in knots.indices.zipWithNext()) { val newPos = knots[tail].follow(knots[head]) if (knots[tail] == newPos) break knots[tail] = newPos } return knots.last() } } fun main() { fun executeMoves(input: List<String>, sizeOfRope: Int): Int { val rope = Rope(sizeOfRope) val uniquePoints = mutableSetOf<RopePosition>() for ((direction, times) in input) { repeat(times) { val tail = rope.move(direction) uniquePoints.add(tail) } } return uniquePoints.size } // Testar os casos básicos val testInput1 = readInput("../inputs/Day09_test") sanityCheck(executeMoves(testInput1, 2), 13) sanityCheck(executeMoves(testInput1, 10), 1) val testInput2 = readInput("../inputs/Day09_test2") sanityCheck(executeMoves(testInput2, 10), 36) val input = readInput("../inputs/Day09") println("Parte 1 = ${executeMoves(input, 2)}") println("Parte 2 = ${executeMoves(input, 10)}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
2,734
advent_of_code_2022_kotlin
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2017/Day03.kt
tginsberg
112,672,087
false
null
/* * Copyright (c) 2017 by <NAME> */ package com.ginsberg.advent2017 import java.lang.Math.abs import kotlin.math.ceil import kotlin.math.sqrt /** * AoC 2017, Day 3 *s * Problem Description: http://adventofcode.com/2017/day/3 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day3/ */ class Day03(input: String) { private val target = input.toInt() fun solvePart1(): Int { val sideLength = lengthOfSideWith(target) val stepsToRingFromCenter = (sideLength - 1) / 2 val midpoints = midpointsForSideLength(sideLength) return stepsToRingFromCenter + midpoints.map { abs(target - it) }.min()!! } fun solvePart2(): Int = Grid(lengthOfSideWith(target)) .generateSpots() .first { it > target } private fun lengthOfSideWith(n: Int): Int = ceil(sqrt(n.toDouble())).toInt().let { if (it.isOdd()) it else it + 1 } private fun midpointsForSideLength(sideLength: Int): List<Int> { val highestOnSide = sideLength * sideLength val offset = ((sideLength - 1) / 2.0).toInt() return (0..3).map { highestOnSide - (offset + (it * sideLength.dec())) } } } class Grid(size: Int) { private var pointer: Pair<Int, Int> = Pair(size / 2, size / 2) private var direction: Direction = Direction.East private val grid: List<IntArray> = (0 until size).map { IntArray(size) }.apply { this[pointer.first][pointer.second] = 1 } fun generateSpots(): Sequence<Int> = generateSequence(1) { pointer = direction.move(pointer) grid[pointer.first][pointer.second] = sumNeighbors() // Turn if we can. direction = if (atSpot(direction.turn.move(pointer)) == 0) direction.turn else direction atSpot(pointer) } private fun sumNeighbors(): Int = (pointer.first - 1..pointer.first + 1).map { x -> (pointer.second - 1..pointer.second + 1).map { y -> atSpot(x, y) } }.flatten() .filterNotNull() .sum() private fun atSpot(spot: Pair<Int, Int>): Int? = atSpot(spot.first, spot.second) private fun atSpot(x: Int, y: Int): Int? = if (x in (0 until grid.size) && y in (0 until grid.size)) grid[x][y] else null sealed class Direction { abstract fun move(point: Pair<Int, Int>): Pair<Int, Int> abstract val turn: Direction object East : Direction() { override fun move(point: Pair<Int, Int>): Pair<Int, Int> = Pair(point.first + 1, point.second) override val turn = North } object West : Direction() { override fun move(point: Pair<Int, Int>): Pair<Int, Int> = Pair(point.first - 1, point.second) override val turn = South } object North : Direction() { override fun move(point: Pair<Int, Int>): Pair<Int, Int> = Pair(point.first, point.second + 1) override val turn = West } object South : Direction() { override fun move(point: Pair<Int, Int>): Pair<Int, Int> = Pair(point.first, point.second - 1) override val turn = East } } }
0
Kotlin
0
15
a57219e75ff9412292319b71827b35023f709036
3,318
advent-2017-kotlin
MIT License
src/main/kotlin/com/groundsfam/advent/y2020/d09/Day09.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d09 import com.groundsfam.advent.DATAPATH import kotlin.io.path.div import kotlin.io.path.useLines private fun findInvalidNumber(nums: List<Long>, preamble: Int = 25): Long? { val counts = mutableMapOf<Long, Int>().apply { repeat(preamble) { i -> this[nums[i]] = this.getOrDefault(nums[i], 0) + 1 } } fun isTwoSum(num: Long): Boolean { counts.forEach { (n, _) -> if (num - n in counts) return true } return false } for (i in preamble until nums.size) { val num = nums[i] if (!isTwoSum(num)) return num // update counts map to reflect new window of `preamble` elements counts[nums[i]] = counts.getOrDefault(nums[i], 0) + 1 counts[nums[i - preamble]] = counts[nums[i - preamble]]!! - 1 if (counts[nums[i - preamble]] == 0) counts.remove(nums[i - preamble]) } return null } private fun findRange(nums: List<Long>, targetSum: Long): Pair<Int, Int>? { var from = 0 var to = 0 var sum = nums[0] while (from < nums.size && to < nums.size) { when { sum < targetSum -> { to++ if (to < nums.size) { sum += nums[to] } } sum > targetSum -> { sum -= nums[from] from++ } else -> return from to to } } return null } fun main() { val nums = (DATAPATH / "2020/day09.txt").useLines { lines -> lines.map { it.toLong() }.toList() } val invalidNumber = findInvalidNumber(nums) ?.also { println("Part one: $it") }!! findRange(nums, invalidNumber)?.let { (from, to) -> nums.subList(from, to).minOrNull()!! + nums.subList(from, to).maxOrNull()!! }?.also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,891
advent-of-code
MIT License
kotlin/0352-data-stream-as-disjoint-intervals.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// Using TreeSet and linear scan in getIntervals() method class SummaryRanges() { val ranges = TreeSet<Int>() fun addNum(value: Int) { ranges.add(value) } fun getIntervals(): Array<IntArray> { val res = LinkedList<IntArray>() ranges.forEach { if (res.isNotEmpty() && res.peekLast()[1] + 1 == it) res.peekLast()[1] = it else res.addLast(intArrayOf(it, it)) } return res.toTypedArray() } } // Using TreeMap and binary search scan in getIntervals() method, small optimization technically but still same time complexity as above solution class SummaryRanges() { val rgs = TreeMap<Int, IntArray>() fun addNum(v: Int) { if (rgs.containsKey(v)) return val l = rgs.lowerKey(v) val h = rgs.higherKey(v) if (l != null && h != null && rgs.get(l)!![1] + 1 == v && h == v + 1 ) { rgs.get(l)!![1] = rgs.get(h)!![1] rgs.remove(h) } else if (l != null && rgs.get(l)!![1] + 1 >= v) { rgs.get(l)!![1] = maxOf(v, rgs.get(l)!![1]) } else if (h != null && h == v + 1) { rgs.put(v, intArrayOf(v, rgs.get(h)!![1])) rgs.remove(h) } else { rgs.put(v, intArrayOf(v, v)) } } fun getIntervals() = rgs.values.toTypedArray() } // Using Union Find class SummaryRanges() { val dsu = DSU() fun addNum(v: Int) { if (dsu.exists(v)) return dsu.add(v) dsu.union(v, v - 1) dsu.union(v, v + 1) } fun getIntervals() = dsu.getIntervals() } class DSU { val parent = HashMap<Int, Int>() val intervals = TreeMap<Int, IntArray>() fun getIntervals() = intervals.values.toTypedArray() fun exists(x: Int) = x in parent fun add(x: Int) { parent[x] = x intervals[x] = intArrayOf(x, x) } fun find(x: Int): Int { parent[x]?: return -1 if (parent[x]!! != x) parent[x] = find(parent[x]!!) return parent[x]!! } fun union(x: Int, y: Int) { val px = find(x) val py = find(y) if (px == -1 || py == -1) return val newX = minOf(intervals[py]!![0], intervals[px]!![0]) val newY = maxOf(intervals[py]!![1], intervals[px]!![1]) parent[px] = py intervals[py] = intArrayOf(newX, newY) intervals.remove(px) } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,448
leetcode
MIT License
src/poyea/aoc/mmxxii/day20/Day20.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day20 import poyea.aoc.utils.readInput fun part1(input: String): Long { val original = input.split("\n") .map { it.toInt() } .mapIndexed { index, i -> Pair(index, i.toLong()) } val moved = original.toMutableList() original.forEach { p -> val index = moved.indexOf(p) moved.removeAt(index) moved.add((index + p.second).mod(moved.size), p) } return moved.map { it.second }.let { val firstIndex = it.indexOf(0) (1..3).sumOf { i -> it[(i * 1000 + firstIndex) % it.size] } } } fun part2(input: String): Long { val original = input.split("\n") .map { it.toInt() } .mapIndexed { index, i -> Pair(index, i.toLong() * 811589153) } val moved = original.toMutableList() repeat(10) { original.forEach { p -> val index = moved.indexOf(p) moved.removeAt(index) moved.add((index + p.second).mod(moved.size), p) } } return moved.map { it.second }.let { val firstIndex = it.indexOf(0) (1..3).sumOf { i -> it[(i * 1000 + firstIndex) % it.size] } } } fun main() { println(part1(readInput("Day20"))) println(part2(readInput("Day20"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
1,306
aoc-mmxxii
MIT License
src/Day12.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
data class SquareNode(val c: Char, val value: Int, val pos: Pair<Int, Int>) { override fun toString(): String { return """position=$pos repr='$c' value=[$value]""" } } class EscalationGraph(val nodes: List<SquareNode>, val edges: Map<SquareNode, List<SquareNode>>) { fun shortestPath(fromEdge: SquareNode, toSymbol: Char): MutableList<SquareNode>? { val queue = ArrayDeque<SquareNode>() queue.addLast(fromEdge) val cameFrom = mutableMapOf<SquareNode?, SquareNode?>() var current: SquareNode? = null while (!queue.isEmpty()) { current = queue.removeFirst() if (current.c == toSymbol) break for (next in edges[current]!!) { if (next in cameFrom) continue queue.addLast(next) cameFrom[next] = current } } val path = mutableListOf<SquareNode>() if (current?.c != toSymbol) return null while (current != fromEdge) { path.add(current!!) current = cameFrom[current] } return path } fun findNode(c: Char) = nodes.find { it.c == c } companion object { fun from(input: List<String>): EscalationGraph { val table = input.map { it.toCharArray() } val edges = mutableMapOf<Pair<Int, Int>, SquareNode>() for ((i, row) in table.withIndex()) { for ((j, cell) in row.withIndex()) { val value: Int = when (cell) { 'S' -> -1 'E' -> 'z' - 'a' + 1 else -> cell - 'a' } edges[(i to j)] = SquareNode(cell, value, i to j) } } val vertices = mutableMapOf<SquareNode, List<SquareNode>>() for ((i, row) in table.withIndex()) { for ((j, _) in row.withIndex()) { val edge = edges[i to j]!! val linkedToEdges = mutableListOf<SquareNode>() if (edges.contains(i - 1 to j) && (edges[i - 1 to j]!!.value - edge.value) <= 1) { linkedToEdges.add(edges[i - 1 to j]!!) } if (edges.contains(i + 1 to j) && (edges[i + 1 to j]!!.value - edge.value) <= 1) { linkedToEdges.add(edges[i + 1 to j]!!) } if (edges.contains(i to j - 1) && (edges[i to j - 1]!!.value - edge.value) <= 1) { linkedToEdges.add(edges[i to j - 1]!!) } if (edges.contains(i to j + 1) && (edges[i to j + 1]!!.value - edge.value) <= 1) { linkedToEdges.add(edges[i to j + 1]!!) } vertices[edge] = linkedToEdges } } return EscalationGraph(edges.values.toList(), vertices) } } } fun main() { fun printPath(input: List<String>, path: MutableList<SquareNode>) { val pathPositions = path.map { it.pos } val red = "\u001b[31m" val reset = "\u001b[0m" for ((i, row) in input.map { it.toCharArray() }.withIndex()) { for ((j, cell) in row.withIndex()) { if (i to j in pathPositions) { print(red + cell + reset) } else { print(cell) } } println() } } fun part1(input: List<String>): Int { val graph = EscalationGraph.from(input) val path = graph.shortestPath(graph.findNode('S')!!, 'E')!! printPath(input, path) return path.size - 2 } fun part2(input: List<String>): Int { val graph = EscalationGraph.from(input) val shortestPath = graph.nodes.filter { it.c == 'a' }.map { edge -> graph.shortestPath(edge, 'E') }.filter { path -> path != null && path.size > 0 }.minByOrNull { it!!.size }!! printPath(input, shortestPath) return shortestPath.size - 2 } val testInput = readInput("Day12_test") println("Test 1 - ${part1(testInput)}") println("Test 2 - ${part2(testInput)}") println() val input = readInput("Day12") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
4,386
kotlin-advent-of-code-22
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day17/day17.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day17 import kotlin.math.abs fun <T> Iterable<Iterable<T>>.cartesianProduct(other: Iterable<Iterable<T>>): List<List<T>> { return this.flatMap { lhsElem -> other.map { rhsElem -> lhsElem + rhsElem } } } fun mixRanges(vararg ranges: IntRange): List<List<Int>> { if (ranges.isEmpty()) return listOf(emptyList()) return ranges.map { range -> range.map { listOf(it) } } .reduce { acc, i -> acc.cartesianProduct(i) } } typealias Cube = List<Int> fun Cube(vararg values: Int): Cube { return values.toList() } fun Cube.sumWith(other: Cube): Cube { return zip(other).map { it.first + it.second } } class GameOfLife(private val dimensions: Int, input: List<List<Boolean>>) { companion object { const val ACTIVE = '#' const val INACTIVE = '.' } private var state = input .withIndex() .map { row -> row.value.withIndex() .filter { field -> field.value } .map { Cube(it.index, row.index, *IntArray(dimensions - 2) { 0 }) } } .flatten() .toSet() private var ranges = List(dimensions) { dim -> when (dim) { 0 -> 0..(state.maxByOrNull { it[dim] }?.get(dim) ?: throw RuntimeException("Wrong input")) 1 -> 0..(state.maxByOrNull { it[dim] }?.get(dim) ?: throw RuntimeException("Wrong input")) else -> 0..0 } } var neighbourhood = mixRanges(*Array(dimensions) { (-1..1) }) .filterNot { it.all { v -> v == 0 } } private fun countNeighbours(cube: Cube, state: Set<Cube>): Int { var count = 0 for (neighbour in neighbourhood) { if (cube.sumWith(neighbour) in state) { count += 1 } } return count } private fun IntRange.update(value: Int): IntRange { return minOf(first, value)..maxOf(last, value) } private fun IntRange.increase(): IntRange { return (first - 1)..(last + 1) } private fun iterValues() = sequence { for (cube in mixRanges(*ranges.map { it.increase() }.toTypedArray())) { yield(cube) } } fun step() { val nextCubes = HashSet<Cube>() var nextRanges = ranges for (cube in iterValues()) { val active = when (countNeighbours(cube, state)) { 2 -> cube in state 3 -> true else -> false } if (active) { nextCubes.add(cube) nextRanges = nextRanges.zip(cube).map { it.first.update(it.second) } } } ranges = nextRanges state = nextCubes } fun printState() { for (dimension in mixRanges(*ranges.subList(2, dimensions).toTypedArray())) { val names = listOf("z", "w") + List(abs(dimensions - 4)) { "dim${it + 5}" } // take z and w, fill with dimX println(names.zip(dimension).joinToString(", ") { "${it.first}=${it.second}" }) for (y in ranges[1]) { for (x in ranges[0]) { print(if (listOf(x, y) + dimension in state) ACTIVE else INACTIVE) } println() } } println() } fun activeCells(): Int { return state.count() } } fun solve(dimensions: Int, input: List<List<Boolean>>): Int { val simulation = GameOfLife(dimensions, input) for (i in 1..6) { simulation.step() } // simulation.printState() return simulation.activeCells() } fun main() { val input = {}::class.java.getResource("/day17.in") .readText() .split("\n") .map { row -> row.map { it == GameOfLife.ACTIVE } } for (dim in 2..5) { println("Answer part ${dim - 2}: ${solve(dim, input)}") } }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
3,918
advent-of-code-2020
Do What The F*ck You Want To Public License
src/problems/day3/part2/part2.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day3.part2 import java.io.File //private const val testFile = "input/day3/test.txt" private const val part_numbers = "input/day3/part_numbers.txt" fun main() { val gearRatioSum = File(part_numbers).bufferedReader().useLines { sumGearRatios(it) } println("Part Number Sum: $gearRatioSum") } private fun sumGearRatios(lines: Sequence<String>): Int { val possibleGears = mutableMapOf<Int, Map<Int, Int>>() val stars = mutableMapOf<Int, Set<Int>>() lines.forEachIndexed {row, line -> val res = parseLine(line) possibleGears[row] = res.possibleGears stars[row] = res.stars } return stars.flatMap { it.value.toRowCols(it.key) } .mapNotNull { it.gearRatio(possibleGears) } .sum() } private fun parseLine(line: String) = LineResult( accumulateNumbers(line), recordStarts(line), ) private data class LineResult(val possibleGears: Map<Int, Int>, val stars: Set<Int>) private fun accumulateNumbers(line: String): Map<Int, Int> { val accumulator = PossibleGearAccumulator() line.forEach { accumulator.nextChar(it) } return accumulator.end() } private fun recordStarts(line: String): Set<Int> { val stars = mutableSetOf<Int>() line.forEachIndexed { index, c -> if (c == '*') stars.add(index)} return stars } private fun Pair<Int, Int>.gearRatio(possibleGears: Map<Int, Map<Int, Int>>) : Int? { val adjacentNumbers = mutableSetOf<Int>() for (i in this.first-1..this.first+1) { for(j in this.second-1..this.second+1) { val number = possibleGears[i]?.get(j) if (number != null) { adjacentNumbers.add(number) } } } if (adjacentNumbers.count() != 2) { return null } return adjacentNumbers.fold(1) {acc, next -> acc * next} } private fun Set<Int>.toRowCols(row: Int): List<Pair<Int, Int>> = this.map {row to it} private class PossibleGearAccumulator() { private val possibleGears = mutableMapOf<Int,Int>() private val currentNumber = StringBuilder() private var currentCol = 0 private var currentStartCol = 0 private var currentEndCol = 0 private var currentState = State.OUT_NUMBER private enum class State { IN_NUMBER, OUT_NUMBER } fun nextChar(character: Char) { when { (character in '0'..'9') and (currentState == State.OUT_NUMBER) -> { currentState = State.IN_NUMBER currentNumber.append(character) currentStartCol = currentCol currentEndCol = currentCol } (character in '0'..'9') and (currentState == State.IN_NUMBER) -> { currentNumber.append(character) currentEndCol = currentCol } (character !in '0'..'9') and (currentState == State.IN_NUMBER) -> { currentState = State.OUT_NUMBER recordPossiblePN() currentNumber.clear() } } currentCol++ } private fun recordPossiblePN() { val number = currentNumber.toString().toInt() for (i in currentStartCol..currentEndCol) { possibleGears[i] = number } } fun end(): Map<Int, Int> { if (currentState == State.IN_NUMBER) { recordPossiblePN() } return possibleGears } }
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
3,408
aoc2023
MIT License
src/Day04.kt
lonskiTomasz
573,032,074
false
{"Kotlin": 22055}
fun main() { fun sumOfFullyContainedAssignments(input: List<String>): Int { val inputLineRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() return input.sumOf { line -> val (firstStart, firstEnd, secondStart, secondEnd) = inputLineRegex .matchEntire(line) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $line") val first = (firstStart.toInt()..firstEnd.toInt()).toList() val second = (secondStart.toInt()..secondEnd.toInt()).toList() return@sumOf when { first.containsAll(second) -> 1 second.containsAll(first) -> 1 else -> 0 }.toInt() } } fun sumOfOverlaps(input: List<String>): Int { val inputLineRegex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() return input.sumOf { line -> val (firstStart, firstEnd, secondStart, secondEnd) = inputLineRegex .matchEntire(line) ?.destructured ?: throw IllegalArgumentException("Incorrect input line $line") val first = firstStart.toInt()..firstEnd.toInt() val second = secondStart.toInt()..secondEnd.toInt() return@sumOf (if (first.intersect(second).isNotEmpty()) 1 else 0).toInt() } } val inputTest = readInput("day04/input_test") val input = readInput("day04/input") println(sumOfFullyContainedAssignments(inputTest)) println(sumOfFullyContainedAssignments(input)) println(sumOfOverlaps(inputTest)) println(sumOfOverlaps(input)) } /** * 2 * 464 * 4 * 770 */
0
Kotlin
0
0
9e758788759515049df48fb4b0bced424fb87a30
1,670
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
Daan-Gunnink
572,614,830
false
{"Kotlin": 8595}
class Day03 : AdventOfCode(157, 70) { private val characterList = "abcdefghijklmnopqrstuvwxyz" private fun getScore(items: List<String>): Int { return items.map { it.toCharArray() }.map { it.sumOf {char -> if(char.isUpperCase()) (char.code - 38) else (char.code - 96) } }.sumOf { it } } override fun part1(input: List<String>): Int { val result = input.map { val firstHalf = it.take(it.length / 2).split("") val secondHalf = it.takeLast(it.length / 2).split("") firstHalf.map { char -> if (secondHalf.any { it == char }) { char } else null }.filterNotNull().filter { it.isNotEmpty() }.distinct() } return getScore(result.flatten()) } override fun part2(input: List<String>): Int { val groupSize = 3 var totalScore = 0 for (index in 0 until (input.size / groupSize)) { val groupIndex = (groupSize * index) val rucksacks = mutableListOf<List<String>>() for (elfIndex in 0 until groupSize) { val items = input[groupIndex + elfIndex].split("") rucksacks.add(items) } val result = rucksacks[0].mapNotNull { char -> if (rucksacks[1].any { it == char }) { if (rucksacks[2].any { it == char }) { char } else null } else null }.filter { it.isNotEmpty() }.distinct() val score = getScore(result) totalScore += score } return totalScore } }
0
Kotlin
0
0
15a89224f332faaed34fc2d000c00fbefe1a3c08
1,681
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day08/Day08.kt
daniilsjb
434,765,082
false
{"Kotlin": 77544}
package day08 import java.io.File fun main() { val data = parse("src/main/kotlin/day08/Day08.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 08 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private typealias Segments = Set<Char> private typealias Entry = Pair<List<Segments>, List<Segments>> private fun parse(path: String): List<Entry> = File(path) .readLines() .map(String::toEntry) private fun String.toEntry(): Entry = this.split("|") .map { part -> part .trim() .split(" ") .map(String::toSet) } .let { (patterns, digits) -> Entry(patterns, digits) } private fun part1(entries: List<Entry>) = entries.sumOf { (_, digits) -> digits.count { digit -> digit.size in arrayOf(2, 3, 4, 7) } } private fun part2(entries: List<Entry>) = entries.sumOf { (patterns, digits) -> // The approach of this solution is to directly determine which // combinations of letters map to which digits. val mappings = Array(10) { setOf<Char>() } // First, we partition the unique digit patterns: // 1) digit '1' maps to the pattern with length 2 // 2) digit '4' maps to the pattern with length 4 // 3) digit '7' maps to the pattern with length 3 // 4) digit '8' maps to the pattern with length 7 // // Out of all digits, only 6 now remain: // - 3 of them have length 5 and may be one of '2','3','5' // - 3 of them have length 6 and may be one of '0','6','9' val patternsWithLength5 = mutableListOf<Segments>() val patternsWithLength6 = mutableListOf<Segments>() for (pattern in patterns) { when (pattern.size) { 2 -> mappings[1] = pattern 3 -> mappings[7] = pattern 4 -> mappings[4] = pattern 7 -> mappings[8] = pattern 5 -> patternsWithLength5.add(pattern) 6 -> patternsWithLength6.add(pattern) } } // Second, we can observe that there are overlaps between digit // patterns. We may use them to deduce new patterns from the // ones we already know. // 5) digit '6' maps to the pattern of length 6 that does not // contain all segments of digit '1'. mappings[6] = patternsWithLength6.first { pattern -> !pattern.containsAll(mappings[1]) } // 6) digit '9' maps to the pattern of length 6 that contains // all segments of digit '4' mappings[9] = patternsWithLength6.first { pattern -> pattern.containsAll(mappings[4]) } // 7) digit '0' maps to the last remaining pattern of length 6 mappings[0] = patternsWithLength6.first { pattern -> pattern != mappings[6] && pattern != mappings[9] } // 8) digit '3' maps to the pattern of length 5 that contains // both segments of digit '1' mappings[3] = patternsWithLength5.first { pattern -> pattern.containsAll(mappings[1]) } // Here the situation becomes trickier. I could not find a fitting // overlap to differentiate between digits 2 and 5, so we're going // to use another trick. Each pattern contains a segment initially // labelled 'f', except for digit '2'. If we find that segment, // the '2' is simply the pattern without it. val foundPatterns = mappings.filter(Set<Char>::isNotEmpty) val f = ('a'..'g').first { label -> foundPatterns.all { pattern -> pattern.contains(label) } } // 9) digit '2' maps to the pattern of length 5 that does not contain // segment initially labelled 'f' mappings[2] = patternsWithLength5.first { pattern -> !pattern.contains(f) } // 10) digit '5' maps to the last remaining pattern of length 5 mappings[5] = patternsWithLength5.first { pattern -> pattern != mappings[3] && pattern != mappings[2] } // At this point it is enough to apply the mapping to each output // digit and combine them into an integer. digits.fold(0) { acc: Int, digit -> acc * 10 + mappings.indexOfFirst { it == digit } } }
0
Kotlin
0
1
bcdd709899fd04ec09f5c96c4b9b197364758aea
4,471
advent-of-code-2021
MIT License
src/year2023/Day1.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import readLines fun main() { val input = readLines("2023", "day1") val testInputPart1 = readLines("2023", "day1_test1") val testInputPart2 = readLines("2023", "day1_test2") check(part1(testInputPart1) == 142) println("Part 1:" + part1(input)) check(part2(testInputPart2) == 281) println("Part 2:" + part2(input)) } private fun part1(input: List<String>): Int { return input.sumOf(::extractFirstAndLastDigit) } private fun extractFirstAndLastDigit(row: String): Int { return ("" + row.first { it.isDigit() } + row.last { it.isDigit() }).toInt() } private fun part2(input: List<String>): Int { return input.sumOf(::extractFirstAndLastNumber) } private fun extractFirstAndLastNumber(row: String): Int { val numbersAsWords = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val leftNumberAsAWord = row.takeWhile { it.isLetter() }.findAnyOf(numbersAsWords)?.second val left = if (leftNumberAsAWord != null) { numbersAsWords.indexOf(leftNumberAsAWord) + 1 } else { row.first { it.isDigit() }.digitToInt() } val rightNumberAsAWord = row.takeLastWhile { it.isLetter() }.findLastAnyOf(numbersAsWords)?.second val right = if (rightNumberAsAWord != null) { numbersAsWords.indexOf(rightNumberAsAWord) + 1 } else { row.last { it.isDigit() }.digitToInt() } return "$left$right".toInt() }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,509
advent_of_code
MIT License
src/Day23.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
enum class Day23Direction(val vector: Vector) { NORTH(Vector(0, -1)), SOUTH(Vector(0, 1)), EAST(Vector(1, 0)), WEST(Vector(-1, 0)), NORTHWEST(Vector(-1, -1)), NORTHEAST(Vector(1, -1)), SOUTHWEST(Vector(-1, 1)), SOUTHEAST(Vector(1, 1)) } val checks = mapOf( Day23Direction.NORTH to listOf(Day23Direction.NORTH, Day23Direction.NORTHEAST, Day23Direction.NORTHWEST), Day23Direction.SOUTH to listOf(Day23Direction.SOUTH, Day23Direction.SOUTHEAST, Day23Direction.SOUTHWEST), Day23Direction.WEST to listOf(Day23Direction.WEST, Day23Direction.NORTHWEST, Day23Direction.SOUTHWEST), Day23Direction.EAST to listOf(Day23Direction.EAST, Day23Direction.NORTHEAST, Day23Direction.SOUTHEAST), ) class SeedPlanter(var x: Int, var y: Int) { fun propose(map: MutableMap<Pair<Int, Int>, SeedPlanter>, scanDirections: List<Day23Direction>): Pair<Int,Int> { scanDirections.forEach { d -> if (checks[d]!!.none { map.containsKey(Pair(x + it.vector.x, y + it.vector.y)) }) { return Pair(x + d.vector.x, y + d.vector.y) } } return Pair(x, y) } fun moveTo(map: MutableMap<Pair<Int, Int>, SeedPlanter>, proposal: Pair<Int, Int>) { map.remove(Pair(x, y)) x = proposal.first y = proposal.second map[Pair(x, y)] = this } override fun toString(): String { return "Elf at ($x, $y)" } } fun main() { fun parseElves(input: List<String>): List<SeedPlanter> { return input.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') { SeedPlanter(x, y) } else { null } } } } fun drawMap(map: MutableMap<Pair<Int, Int>, SeedPlanter>) { val minX = map.minOf { it.key.first } - 1 val maxX = map.maxOf { it.key.first } + 1 val minY = map.minOf { it.key.second } - 1 val maxY = map.maxOf { it.key.second } + 1 for (y in minY..maxY) { for (x in minX..maxX) { if (map.containsKey(Pair(x, y))) { print("#") } else { print(".") } } println() } } fun part1(input: List<String>): Int { val elves = parseElves(input) val map = elves.associateBy { Pair(it.x, it.y) }.toMutableMap() println("== Initial State==") drawMap(map) val scanDirections = mutableListOf(Day23Direction.NORTH, Day23Direction.SOUTH, Day23Direction.WEST, Day23Direction.EAST) var round = 1 repeat(10) { val moveProposals = mutableMapOf<Pair<Int,Int>, MutableList<SeedPlanter>>() elves.filter { elf -> Day23Direction.values().any { map.containsKey(Pair(elf.x + it.vector.x, elf.y + it.vector.y)) } }.forEach { moveProposals.getOrPut(it.propose(map, scanDirections)) { mutableListOf() }.add(it) } moveProposals.filter { it.value.size == 1 }.forEach { (proposal, elf) -> elf.first().moveTo(map, proposal) } scanDirections.add(scanDirections.removeFirst()) // println("== End of Round $round ==") // drawMap(map) round++ } val minX = map.minOf { it.key.first } val maxX = map.maxOf { it.key.first } val minY = map.minOf { it.key.second } val maxY = map.maxOf { it.key.second } return (maxX - minX + 1) * (maxY - minY + 1) - elves.size } fun part2(input: List<String>): Int { val elves = parseElves(input) val map = elves.associateBy { Pair(it.x, it.y) }.toMutableMap() println("== Initial State==") drawMap(map) val scanDirections = mutableListOf(Day23Direction.NORTH, Day23Direction.SOUTH, Day23Direction.WEST, Day23Direction.EAST) var round = 1 while(true) { val moveProposals = mutableMapOf<Pair<Int,Int>, MutableList<SeedPlanter>>() elves.filter { elf -> Day23Direction.values().any { map.containsKey(Pair(elf.x + it.vector.x, elf.y + it.vector.y)) } }.forEach { moveProposals.getOrPut(it.propose(map, scanDirections)) { mutableListOf() }.add(it) } if (moveProposals.isEmpty()) { return round } moveProposals.filter { it.value.size == 1 }.forEach { (proposal, elf) -> elf.first().moveTo(map, proposal) } scanDirections.add(scanDirections.removeFirst()) // println("== End of Round $round ==") // drawMap(map) round++ } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") check(part1(testInput) == 110) println("Part 1 checked out!") check(part2(testInput) == 20) println("Part 2 checked out!") val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
5,207
advent-of-code-2022
Apache License 2.0
src/Day02.kt
arturkowalczyk300
573,084,149
false
{"Kotlin": 31119}
enum class Result { LOOSE, WIN, DRAW } fun moveStringToMoveScore(move: String, firstMoveCharacter: Char): Int { return move.toCharArray().first().code - firstMoveCharacter.code + 1 } fun stringToDesiredResult(desiredResultString: String): Result { return when (desiredResultString.toCharArray().first()) { 'X' -> Result.LOOSE 'Y' -> Result.DRAW else -> Result.WIN } } fun findMoveToAchieveDesiredResult(desiredResult: Result, elfMove: String): String { val elfMoveCode = moveStringToMoveScore(elfMove, 'A') var calculatedMoveCode: Int = 0 if (desiredResult == Result.DRAW) calculatedMoveCode = elfMoveCode else { when (elfMoveCode) { 1 -> calculatedMoveCode = if (desiredResult == Result.WIN) 2 else 3 2 -> calculatedMoveCode = if (desiredResult == Result.WIN) 3 else 1 3 -> calculatedMoveCode = if (desiredResult == Result.WIN) 1 else 2 } } return when (calculatedMoveCode) { 1 -> "X" 2 -> "Y" else -> "Z" } } fun part1(rounds: List<String>): Int { var elfScore = 0 var myScore = 0 rounds.forEach { val moves = it.split(" ") val elfMoveValue = moveStringToMoveScore(moves[0], 'A') val myMoveValue = moveStringToMoveScore(moves[1], 'X') lateinit var myResult: Result if (elfMoveValue == myMoveValue) { //draw situation myResult = Result.DRAW } else { when (myMoveValue) { 1 -> myResult = if (elfMoveValue == 2) Result.LOOSE else Result.WIN 2 -> myResult = if (elfMoveValue == 3) Result.LOOSE else Result.WIN 3 -> myResult = if (elfMoveValue == 1) Result.LOOSE else Result.WIN } } when (myResult) { Result.LOOSE -> elfScore += 6 Result.DRAW -> { elfScore += 3 myScore += 3 } Result.WIN -> myScore += 6 } elfScore += elfMoveValue myScore += myMoveValue } return myScore } fun part2(rounds: List<String>): Int { val listOfMoves = mutableListOf<String>() var elfScore = 0 var myScore = 0 rounds.forEach { val splittedString = it.split(" ") val desiredResult = stringToDesiredResult(splittedString[1]) val myMove = findMoveToAchieveDesiredResult(desiredResult, splittedString[0]) listOfMoves.add("${splittedString[0]} ${myMove}") } return part1(listOfMoves) } fun main() { val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) val secondTestInput = readInput("Day02_test_second") check(part2(secondTestInput) == 12) println(part2(input)) }
0
Kotlin
0
0
69a51e6f0437f5bc2cdf909919c26276317b396d
2,838
aoc-2022-in-kotlin
Apache License 2.0
src/year2015/day16/Day16.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day16 import readInput fun main() { val input = readInput("2015", "Day16") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val mfcsam = mapOf( "children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1, ) val possibleSues = input.associate { thingsBySue(it) }.filter { it.value.all { (k, v) -> mfcsam[k] == v } } return possibleSues.keys.first() } private fun part2(input: List<String>): Int { val mfcsam = mapOf( "children" to 3..3, "cats" to (7 + 1)..Int.MAX_VALUE, "samoyeds" to 2..2, "pomeranians" to (Int.MIN_VALUE until 3), "akitas" to 0..0, "vizslas" to 0..0, "goldfish" to (Int.MIN_VALUE until 5), "trees" to (3 + 1)..Int.MAX_VALUE, "cars" to 2..2, "perfumes" to 1..1, ) val possibleSues = input.associate { thingsBySue(it) }.filter { it.value.all { (k, v) -> v in mfcsam[k]!! } } return possibleSues.keys.first() } private fun thingsBySue(input: String): Pair<Int, Map<String, Int>> { val num = "Sue (\\d+):".toRegex().find(input)!!.groupValues[1].toInt() val things = "(\\w+): (\\d+)".toRegex().findAll(input).map { it.groupValues[1] to it.groupValues[2].toInt() }.toMap() return num to things }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,559
AdventOfCode
Apache License 2.0
src/day5/newday.kt
mrm1st3r
573,163,888
false
{"Kotlin": 12713}
package day5 import Puzzle fun part1(input: List<String>): String { val separator = input.indexOf("") check(separator > 0) val stacks = parseStacks(input.subList(0, separator)) input.subList(separator + 1, input.size) .map(::parseOperation) .forEach { executeOperation1(it, stacks) } return String(stacks .map { it.value.last() } .toCharArray()) } fun part2(input: List<String>): String { val separator = input.indexOf("") check(separator > 0) val stacks = parseStacks(input.subList(0, separator)) input.subList(separator + 1, input.size) .map(::parseOperation) .forEach { executeOperation2(it, stacks) } return String(stacks .map { it.value.last() } .toCharArray()) } fun executeOperation1(op: Operation, stacks: Map<Int, ArrayDeque<Char>>) { for (i in 1..op.amount) { val crate = stacks[op.from]!!.removeLast() stacks[op.to]!!.addLast(crate) } } fun executeOperation2(op: Operation, stacks: Map<Int, ArrayDeque<Char>>) { val crane = ArrayDeque<Char>() for (i in 1..op.amount) { val crate = stacks[op.from]!!.removeLast() crane.addLast(crate) } for (i in 1..op.amount) { val crate = crane.removeLast() stacks[op.to]!!.addLast(crate) } } data class Operation( val from: Int, val to: Int, val amount: Int ) fun parseOperation(input: String): Operation { val result = Regex("""move (\d+) from (\d) to (\d)""").matchEntire(input) checkNotNull(result) check(result.groupValues.size == 4) return Operation( from = result.groupValues[2].toInt(), to = result.groupValues[3].toInt(), amount = result.groupValues[1].toInt(), ) } fun parseStacks(input: List<String>): Map<Int, ArrayDeque<Char>> { val stacks = input.last() .filter { it.isDigit() } .map { it.digitToInt() } .associateWith<Int, ArrayDeque<Char>> { ArrayDeque() } input.subList(0, input.size - 1).forEach { fillStacks(stacks, it) } return stacks } fun fillStacks(stacks: Map<Int, ArrayDeque<Char>>, input: String) { for (i in 1..stacks.size) { val position = (i - 1) * 4 + 1 if (position <= input.length && input[position].isLetter()) { stacks[i]!!.addFirst(input[position]) } } } fun main() { Puzzle( "day5", ::part1, "CMZ", ::part2, "MCD" ).test() }
0
Kotlin
0
0
d8eb5bb8a4ba4223331766530099cc35f6b34e5a
2,485
advent-of-code-22
Apache License 2.0
src/Day05.kt
nic-dgl-204-fall-2022
564,602,480
false
{"Kotlin": 2428}
fun main() { fun part1(input: List<String>): Int { // Extension functions to check for each of the criteria fun String.hasUnwantedStrings() = this.zipWithNext().any { it.first == 'a' && it.second == 'b' } || this.zipWithNext().any { it.first == 'c' && it.second == 'd' } || this.zipWithNext().any { it.first == 'p' && it.second == 'q' } || this.zipWithNext().any { it.first == 'x' && it.second == 'y' } fun String.hasVowels() = this.count { it in "aeiou" } >= 3 fun String.hasLetterTwice() = this.zipWithNext().any { it.first == it.second } // Checks string eligibility for nice list fun isNice(str: String) = !str.hasUnwantedStrings() && str.hasVowels() && str.hasLetterTwice() var totalNiceList = 0 for(string in input) { when(isNice(string)) { true -> totalNiceList++ false -> continue } } return totalNiceList } fun part2(input: List<String>): Int { // Criteria for nice list val pattern = Regex("(..).*\\1") fun String.equalEnds() = this.windowed(3).any { it.first() == it.last() } fun String.checkForPairs() = this.windowed(2).count() > this.windowed(2).distinct().count() // Nice list check fun isNice(str: String) = pattern.containsMatchIn(str) && str.checkForPairs() && str.equalEnds() var totalNiceList = 0 for(string in input) { when(isNice(string)) { true -> totalNiceList++ false -> continue } } return totalNiceList } val input = readInput("input") println(part1(input)) println(part2(input)) }
1
Kotlin
0
0
25e14ff492cb9cbb86b98a97f1a05f956e4ac524
1,809
redjinator-aoc-2
Apache License 2.0
2022/Day11.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import java.math.BigInteger fun main() { val input = readInput("Day11") data class Monkey( val id: Int, val items: ArrayDeque<BigInteger>, val op: (BigInteger) -> BigInteger, val testDiv: BigInteger, val pass: (BigInteger) -> Int, var inspected: Long = 0, ) fun readMonkeys() = (input.indices step 7).map { i -> assert(input[i] == "Monkey ${i}:") val items = input[i+1].trim().removePrefix("Starting items: ").split(", ").map { it.toBigInteger() } val op = input[i+2].trim().removePrefix("Operation: new = old ") val testDiv = input[i+3].trim().removePrefix("Test: divisible by ").toBigInteger() val testTrue = input[i+4].trim().removePrefix("If true: throw to monkey ").toInt() val testFalse = input[i+5].trim().removePrefix("If false: throw to monkey ").toInt() Monkey( id = i, items = ArrayDeque(items), op = when { op == "* old" -> { { it * it} } op == "+ old" -> { { it + it} } op[0] == '+' -> { {it + op.removePrefix("+ ").toBigInteger()} } op[0] == '*' -> { {it * op.removePrefix("* ").toBigInteger()} } else -> error(op) }, testDiv = testDiv, pass = { if (it.mod(testDiv) == BigInteger.ZERO) testTrue else testFalse } ) } run { val monkeys = readMonkeys() repeat(20) { for (m in monkeys) { while (m.items.isNotEmpty()) { val w = m.items.removeFirst() val newW = m.op(w) / 3.toBigInteger() m.inspected++ monkeys[m.pass(newW)].items.addLast(newW) } } } val res1 = monkeys.map { it.inspected }.sortedDescending().take(2).let { it[0] * it[1] } println(res1) } run { val monkeys = readMonkeys() val lcm = monkeys.map { it.testDiv }.reduce { a, b -> a * b / a.gcd(b) } repeat(10_000) { for (m in monkeys) { while (m.items.isNotEmpty()) { val w = m.items.removeFirst() val newW = m.op(w).mod(lcm) m.inspected++ monkeys[m.pass(newW)].items.addLast(newW) } } if (it == 19 || it % 1000 == 0) println( monkeys.map { it.inspected } ) } val res2 = monkeys.map { it.inspected }.sortedDescending().take(2).let { it[0] * it[1] } println(res2) } }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
2,642
advent-of-code-kotlin
Apache License 2.0
src/day19/Day19.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
package day19 import kotlin.math.max import kotlin.math.min import readInput enum class ResourceType { ORE, CLAY, OBSIDIAN, GEODE; companion object { fun buildingResourses(): List<ResourceType> { return listOf(ORE, CLAY, OBSIDIAN) } } } data class ResourceSet(val ore: Int, val clay: Int, val obsidian: Int) { operator fun plus(other: ResourceSet): ResourceSet { return ResourceSet(ore + other.ore, clay + other.clay, obsidian + other.obsidian) } fun covers(other: ResourceSet, time: Int = 1): Boolean { return ore * time >= other.ore && clay * time >= other.clay && obsidian * time >= other.obsidian } operator fun get(type: ResourceType): Int { return when (type) { ResourceType.ORE -> ore ResourceType.CLAY -> clay ResourceType.OBSIDIAN -> obsidian ResourceType.GEODE -> throw IndexOutOfBoundsException() } } operator fun minus(other: ResourceSet): ResourceSet { return ResourceSet(ore - other.ore, clay - other.clay, obsidian - other.obsidian) } } fun robotProduction(type: ResourceType): ResourceSet { return when (type) { ResourceType.ORE -> ResourceSet(1, 0, 0) ResourceType.CLAY -> ResourceSet(0, 1, 0) ResourceType.OBSIDIAN -> ResourceSet(0, 0, 1) ResourceType.GEODE -> throw IndexOutOfBoundsException() } } data class RobotCosts( val ore: ResourceSet, val clay: ResourceSet, val obsidian: ResourceSet, val geode: ResourceSet ) { operator fun get(type: ResourceType): ResourceSet { return when (type) { ResourceType.ORE -> ore ResourceType.CLAY -> clay ResourceType.OBSIDIAN -> obsidian ResourceType.GEODE -> geode } } fun asList(): List<ResourceSet> { return listOf(ore, clay, obsidian, geode) } } operator fun <T> List<T>.component6(): T { return get(5) } operator fun <T> List<T>.component7(): T { return get(6) } data class State(val production: ResourceSet, var stock: ResourceSet, val geodes: Int) { fun asList(): List<Int> { return listOf( production.ore, production.clay, production.obsidian, stock.ore, stock.clay, stock.obsidian, geodes ) } } fun stateFromList(input: List<Int>): State { return State(ResourceSet(input[0], input[1], input[2]), ResourceSet(input[3], input[4], input[5]), input[6]) } data class Blueprint(val id: Int, val robotCosts: RobotCosts) { fun bestGeodeProduction(time: Int): Int { var states = mutableSetOf(State(ResourceSet(1, 0, 0), ResourceSet(0, 0, 0), 0)) var ans = 0 for (minute in 1..time) { val timeLeft = time - minute println("time left: $timeLeft") val nextStates = mutableSetOf<State>() for (state in states) { if (waitCanBeUseful(state, timeLeft)) { val newState = State(state.production, state.stock + state.production, state.geodes) nextStates.add(newState) } val usefulRobots = usefulRobotsPossibleNow(state) for (robot in usefulRobots) { val newState = if (robot == ResourceType.GEODE) { State( state.production, state.stock - robotCosts[robot] + state.production, state.geodes + timeLeft ) } else { State( state.production + robotProduction(robot), state.stock - robotCosts[robot] + state.production, state.geodes, ) } nextStates.add(newState) } } println("total number of states: ${nextStates.size}") val reachedMaximums = nextStates.reduce { s1, s2 -> stateFromList(s1.asList().zip(s2.asList()) { x1, x2 -> max(x1, x2) }) } val maximalStates = nextStates.filter { x -> x.asList().zip(reachedMaximums.asList()) { y, ymax -> (y >= ymax) }.any { b -> b } } println("number of maximal states: ${maximalStates.size}") if (nextStates.size < 7000) { clearUselessStates(nextStates) } else { nextStates.removeIf { x -> maximalStates.any { y -> y.isBetterThan(x, this) } } } states = nextStates println("step $minute, useful number of states: ${states.size}") println("Geodes: ${reachedMaximums.geodes}") ans = max(ans, reachedMaximums.geodes) println() println() } return ans } private fun clearUselessStates(states: MutableSet<State>): MutableSet<State> { val useless = states.filter { x -> states.any(fun(y: State): Boolean { if (y.isBetterThan(x, this)) { // println("$y is better than $x") return true } return false }) } states.removeAll(useless.toSet()) return states } private fun robotsPossibleNow(state: State): List<ResourceType> { val answer = mutableListOf<ResourceType>() for (robotType in ResourceType.values()) { if (state.stock.covers(robotCosts[robotType])) { answer.add(robotType) } } return answer } private fun robotsPossibleWithWait(state: State, waitTime: Int = 40): List<ResourceType> { val answer = mutableListOf<ResourceType>() for (robotType in ResourceType.values()) { if (state.production.covers(robotCosts[robotType], waitTime)) { answer.add(robotType) } } return answer } private fun usefulRobotsPossibleNow(state: State): Set<ResourceType> { return usefulRobots(state).toSet().intersect(robotsPossibleNow(state).toSet()) } private fun waitCanBeUseful(state: State, waitTime: Int): Boolean { val usefulRobotsPossibleWithWait = usefulRobots(state).toSet().intersect(robotsPossibleWithWait(state, waitTime + 2).toSet()) return usefulRobotsPossibleWithWait.size > usefulRobotsPossibleNow(state).size } private fun usefulRobots(state: State): List<ResourceType> { val answer = mutableListOf<ResourceType>() for (robotType in ResourceType.values()) { if (robotType == ResourceType.GEODE) { answer.add(ResourceType.GEODE) } else if (state.production[robotType] < maxNeededProduction(robotType)) { answer.add(robotType) } } return answer } fun maxNeededProduction(resourceType: ResourceType): Int { if (resourceType == ResourceType.GEODE) { throw Exception("Asking for max geode production, lol") } return robotCosts.asList().maxOf { r -> r[resourceType] } } fun qualityLevel(time: Int): Int { return id * bestGeodeProduction(time) } } fun State.isBetterThan(other: State, blueprint: Blueprint): Boolean { if (production.covers(blueprint.robotCosts.geode) && stock.covers(blueprint.robotCosts.geode) && geodes >= other.geodes ) { //println("Ultimate!") return hashCode() > other.hashCode() } for (resourseType in ResourceType.buildingResourses()) if (!resourseIsGoodEnough(blueprint, resourseType) && (production[resourseType] < other.production[resourseType] || stock[resourseType] < other.stock[resourseType]) ) { return false } return geodes > other.geodes || (geodes == other.geodes && hashCode() > other.hashCode()) } fun State.resourseIsGoodEnough(blueprint: Blueprint, resource: ResourceType): Boolean { return production[resource] >= blueprint.maxNeededProduction(resource) && stock[resource] >= blueprint.maxNeededProduction(resource) } fun parseBlueprint(input: String): Blueprint { val (id, oreOre, clayOre, obsidianOre, obsidianClay, geodeOre, geodeObsidian) = input.replace(':', ' ') .split(" ") .mapNotNull { x -> x.toIntOrNull() } val oreRobotCost = ResourceSet(oreOre, 0, 0) val clayRobotCost = ResourceSet(clayOre, 0, 0) val obsidianRobotCost = ResourceSet(obsidianOre, obsidianClay, 0) val geodeRobotCost = ResourceSet(geodeOre, 0, geodeObsidian) return Blueprint(id, RobotCosts(oreRobotCost, clayRobotCost, obsidianRobotCost, geodeRobotCost)) } fun part1(input: List<Blueprint>): Int { var totalAns = 0 for (blueprint in input) { println("Blueprint ${blueprint}:") val ans = blueprint.qualityLevel(24) println("Ans ${blueprint.id}: $ans") println() totalAns += ans } println("ANSWER: $totalAns") return totalAns } fun part2(input: List<Blueprint>): Int { var totalAns = 1 val len = min(3, input.size) for (blueprint in input.subList(0, len)) { val ans = blueprint.bestGeodeProduction(32) println("Ans for blueprint ${blueprint.id}: $ans") totalAns *= ans } println("TOTAL ANS pt 2: $totalAns") return totalAns } fun main() { val input = readInput("Day19").map(::parseBlueprint) val testInput = readInput("Day19-test").map(::parseBlueprint) val testAnsPart1 = part1(testInput) val ansPart1 = part1(input) val testAnsPart2 = part2(testInput) val ansPart2 = part2(input) println() println("ANSWERS") println("test part1: $testAnsPart1") println("real part1: $ansPart1") println("test part2: $testAnsPart2") println("real part2: $ansPart2") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
10,085
aoc-2022
Apache License 2.0
src/Day12.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
import kotlin.math.abs fun main() { val day = 12 fun Char.toHeight() = when (this) { in 'a'..'z' -> this - 'a' 'S' -> 0 'E' -> 'z' - 'a' else -> throw RuntimeException() } fun part1(input: List<String>): Int { val n = input.size val m = input.first().length val closestDistance = List(n) { MutableList(m) { Int.MAX_VALUE - 1 } } for (i in 0 until n) for (j in 0 until m) if (input[i][j] == 'E') closestDistance[i][j] = 0 repeat(n * m) { for (i in 0 until n) for (j in 0 until m) for (x in maxOf(0, i - 1) until minOf(i + 2, n)) for (y in maxOf(0, j - 1) until minOf(j + 2, m)) if (abs(x - i) + abs(y - j) == 1) if (input[i][j].toHeight() + 1 >= input[x][y].toHeight()) closestDistance[i][j] = minOf(closestDistance[i][j], closestDistance[x][y] + 1) } for (i in 0 until n) for (j in 0 until m) if (input[i][j] == 'S') return closestDistance[i][j] throw RuntimeException("No start position") } fun part2(input: List<String>): Int { val n = input.size val m = input.first().length val closestDistance = List(n) { MutableList(m) { Int.MAX_VALUE - 1 } } for (i in 0 until n) for (j in 0 until m) if (input[i][j] == 'E') closestDistance[i][j] = 0 repeat(n * m) { for (i in 0 until n) for (j in 0 until m) for (x in maxOf(0, i - 1) until minOf(i + 2, n)) for (y in maxOf(0, j - 1) until minOf(j + 2, m)) if (abs(x - i) + abs(y - j) == 1) if (input[i][j].toHeight() + 1 >= input[x][y].toHeight()) closestDistance[i][j] = minOf(closestDistance[i][j], closestDistance[x][y] + 1) } var result = Int.MAX_VALUE for (i in 0 until n) for (j in 0 until m) if (input[i][j].toHeight() == 0) result = minOf(result, closestDistance[i][j]) return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
2,649
advent-of-code-kotlin-2022
Apache License 2.0
src/Day02.kt
hnuttin
572,601,761
false
{"Kotlin": 5036}
enum class RPS(val score: Int) { A(1), X(1), B(2), Y(2), C(3), Z(3); fun fight(rps: RPS): Int { return when (this) { A -> if (rps == X) 3 else if (rps == Y) 6 else 0 B -> if (rps == X) 0 else if (rps == Y) 3 else 6 C -> if (rps == X) 6 else if (rps == Y) 0 else 3 else -> throw IllegalArgumentException() } } fun perform(rps: RPS): Int { return when (this) { A -> if (rps == X) C.score else if (rps == Y) 3 + A.score else 6 + B.score B -> if (rps == X) A.score else if (rps == Y) 3 + B.score else 6 + C.score C -> if (rps == X) B.score else if (rps == Y) 3 + C.score else 6 + A.score else -> throw IllegalArgumentException() } } } fun main() { val testInput = readInput("Day02_test") val games = testInput.map { rawGame -> rawGame.split(" ") } .map { gameChoices -> Pair(RPS.valueOf(gameChoices[0]), RPS.valueOf(gameChoices[1])) }; println(games.map { game -> game.first.fight(game.second).plus(game.second.score) }.sum()); println(games.map { game -> game.first.perform(game.second) }.sum()); }
0
Kotlin
0
0
53975ed6acb42858be56c2150e573cdbf3deedc0
1,179
aoc-2022
Apache License 2.0
src/day11/Day11.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day11 import utils.* data class Monkey( val id: Int, var items: MutableList<Int>, val operation: Char, val operationValue: Int?, val divisor: Int ) { lateinit var divisibleTargetMonkey: Monkey lateinit var indivisibleTargetMonkey: Monkey var inspections: Int = 0 private fun doOperation(item: Int): Long { val other = operationValue ?: item return when (operation) { '+' -> item.toLong() + other '-' -> item.toLong() - other '*' -> item.toLong() * other '/' -> item.toLong() / other '%' -> item.toLong() % other else -> throw Error("invalid operation $operation") } } fun throwItems(lcm: Int, inspectionDivisor: Int) { inspections += items.size items.forEach { value -> val newValue = ( doOperation(value) / inspectionDivisor % lcm ).toInt() val targetMonkey = if (newValue % divisor == 0) divisibleTargetMonkey else indivisibleTargetMonkey targetMonkey.items.add(newValue) } items = mutableListOf() } } fun readMonkeys(input: List<String>): List<Monkey> { val regex = """ \s*Monkey (\d+): \s*Starting items: ((?:\d+)?(?:, \d+)*) \s*Operation: new = old (.) (\d+|old) \s*Test: divisible by (\d+) \s*If true: throw to monkey (\d+) \s*If false: throw to monkey (\d+)""".trimIndent().toRegex() val targets = mutableMapOf<Int, Pair<Int, Int>>() val monkeys = regex.findAll(input.joinToString("\n")).map { result -> val values = result.groupValues.drop(1) val id = values[0].toInt() val items = values[1].split(", ").map(String::toInt).toMutableList() val operation = values[2].single() val operationValue = values[3].toIntOrNull() val divisor = values[4].toInt() val divisibleTargetMonkeyIdx = values[5].toInt() val indivisibleTargetMonkeyIdx = values[6].toInt() targets[id] = Pair(divisibleTargetMonkeyIdx, indivisibleTargetMonkeyIdx) Monkey(id, items, operation, operationValue, divisor) }.toList() monkeys.forEach { monkey -> val (divisibleIdx, indivisibleIdx) = targets[monkey.id]!! monkey.divisibleTargetMonkey = monkeys[divisibleIdx] monkey.indivisibleTargetMonkey = monkeys[indivisibleIdx] } return monkeys } fun tossItems(monkeys: List<Monkey>, count: Int, divisor: Int): Long { assert(monkeys.size > 1) val lcm = getLCM(*monkeys.map { it.divisor }.toIntArray()) repeat(count) { monkeys.forEach { monkey -> monkey.throwItems(lcm, divisor) } } return monkeys .map { it.inspections.toLong() } .sortedDescending() .take(2) .reduce(Long::times) } fun part1(input: List<String>): Long = tossItems(readMonkeys(input), 20, 3) fun part2(input: List<String>): Long = tossItems(readMonkeys(input), 10000, 1) fun main() { val testInput = readInput("Day11_test") expect(part1(testInput), 10605) expect(part2(testInput), 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
3,301
AOC-2022-Kotlin
Apache License 2.0
src/y2022/Day02.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput /** * A > Y * B > Z * C > X * X > B * Y > C * Z > A */ val oppMap = mapOf('A' to 0, 'B' to 1, 'C' to 2) val meMap = mapOf('X' to 0, 'Y' to 1, 'Z' to 2) fun part1(input: List<String>): Int { return input.sumOf { inputToScore(it) } } fun inputToNums(input: String): Pair<Int, Int> { return oppMap[input.first()]!! to meMap[input.last()]!! } fun score(opp: Int, me: Int): Int { return when (opp) { (me + 1) % 3 -> 0 me -> 3 else -> 6 } } fun inputToScore(input: String): Int { val (opp, me) = inputToNums(input) return me + 1 + score(opp, me) } fun part2(input: List<String>): Int { return input.sumOf { inputToScore2(it) } } fun inputToScore2(input: String): Int { val (opp, result) = inputToNums(input) val myPlay = (opp + result + 2) % 3 return result * 3 + 1 + myPlay } fun main() { val input = readInput("resources/2022/day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,005
advent-of-code
Apache License 2.0
src/main/kotlin/de/nilsdruyen/aoc/Day05.kt
nilsjr
571,758,796
false
{"Kotlin": 15971}
package de.nilsdruyen.aoc fun main() { fun part1(input: List<String>): String { return with(input.crates()) { input.instructions(size).fold(stacks()) { s, i -> val movedCrates = s[i.from - 1].takeLast(i.move).reversed() s[i.from - 1] = s[i.from - 1].dropLast(i.move) s[i.to - 1] += movedCrates s }.topChars() } } fun part2(input: List<String>): String { return with(input.crates()) { input.instructions(size).fold(stacks()) { s, i -> val movedCrates = s[i.from - 1].takeLast(i.move) s[i.from - 1] = s[i.from - 1].dropLast(i.move) s[i.to - 1] += movedCrates s }.topChars() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) } data class Instruction(val move: Int, val from: Int, val to: Int) private fun List<List<Char>>.topChars() = map { it.last() }.joinToString("") private fun List<String>.crates() = takeWhile { it.isNotBlank() } private fun List<String>.instructions(dropLines: Int): List<Instruction> = drop(dropLines + 1).map { val parts = it.split(" ") val move = parts[1].toInt() val from = parts[3].toInt() val to = parts[5].toInt() Instruction(move, from, to) } private fun List<String>.stacks(): MutableList<List<Char>> { return asSequence() .map { it.windowed(3, 4) } .flatMap { row -> row.mapIndexed { index, s -> index to s[1] } } .filter { it.second.isLetter() } .groupBy { it.first } .toSortedMap() .map { entry -> entry.value.map { it.second }.reversed() } .toMutableList() }
0
Kotlin
0
0
1b71664d18076210e54b60bab1afda92e975d9ff
1,938
advent-of-code-2022
Apache License 2.0
src/Day03.kt
achugr
573,234,224
false
null
import kotlin.math.log2 fun main() { fun part1(input: List<String>): Int { return input.map { line -> line.toList() .chunked(line.length / 2) .map { it.fold(0L) { acc, c -> acc or (1L shl (c - 'A')) } } .reduce { acc, i -> acc and i } }.map { log2(it.toDouble()).toInt() } .map { (it + 'A'.code).toChar() } .map { when (it) { in 'A'..'Z' -> it - 'A' + 27 in 'a'..'z' -> it - 'a' + 1 else -> throw IllegalArgumentException("Unexpected code") } } .sum() } fun part2(input: List<String>): Int { return input.windowed(3, 3) .map { group -> group .map { it.fold(0L) { acc, c -> acc or (1L shl (c - 'A')) } } .reduce { acc, i -> acc and i } }.map { log2(it.toDouble()).toInt() } .map { (it + 'A'.code).toChar() } .map { when (it) { in 'A'..'Z' -> it - 'A' + 27 in 'a'..'z' -> it - 'a' + 1 else -> throw IllegalArgumentException("Unexpected code") } } .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
1,797
advent-of-code-kotlin-2022
Apache License 2.0
src/Day11.kt
kecolk
572,819,860
false
{"Kotlin": 22071}
enum class Operation { ADD, MULTIPLY, SQUARE } fun main() { data class Monkey( var items: ArrayDeque<Long> = ArrayDeque(), val operation: Operation = Operation.MULTIPLY, val operand: Long = 0, val divisibleBy: Long = 1, val onTrue: Int = 0, val onFalse: Int = 0, var inspections: Long = 0, ) fun parseInput(input: List<String>): List<Monkey> { val result: MutableList<Monkey> = mutableListOf() var current = Monkey() input.forEach { line -> val parts = line.split(" ").filter { it.isNotBlank() } when { parts.isEmpty() -> {} parts.first() == "Starting" -> { parts.forEach { it.split(",").first().toLongOrNull()?.let { item -> current.items.add(item) } } } parts.first() == "Operation:" -> { val operation = when { parts.last() == "old" -> Operation.SQUARE parts.any { it == "+" } -> Operation.ADD else -> Operation.MULTIPLY } current = if (operation == Operation.SQUARE) { current.copy(operation = operation) } else { val operand = parts.last().toLong() current.copy(operation = operation, operand = operand) } } parts.first() == "Test:" -> { current = current.copy(divisibleBy = parts.last().toLong()) } parts[1] == "true:" -> { current = current.copy(onTrue = parts.last().toInt()) } parts[1] == "false:" -> { current = current.copy(onFalse = parts.last().toInt()) result.add(current) current = Monkey() } else -> {} } } return result } fun doRound(monkeys: List<Monkey>, handleWorry: Long.() -> Long) { monkeys.forEach { monkey -> while (monkey.items.isNotEmpty()) { var item = monkey.items.removeFirst() when (monkey.operation) { Operation.ADD -> item += monkey.operand Operation.MULTIPLY -> item *= monkey.operand Operation.SQUARE -> item *= item } item = item.handleWorry() val moveTo = if (item % monkey.divisibleBy == 0L) monkey.onTrue else monkey.onFalse monkeys[moveTo].items.add(item) monkey.inspections += 1 } } } fun monkeyBusiness(monkeys: List<Monkey>, rounds: Int, advancedWorry: Boolean): Long { val globalModulo = monkeys.map { it.divisibleBy }.reduce { acc, item -> acc * item } val worryHandler: Long.() -> Long = if (advancedWorry) { { this % globalModulo } } else { { this / 3 } } for (round in 1..rounds) doRound(monkeys, worryHandler) return monkeys .map { it.inspections } .sortedDescending() .take(2) .reduce { acc, inspections -> inspections * acc } } val testInput = readTextInput("Day11_test") val input = readTextInput("Day11") check(monkeyBusiness(parseInput(testInput), 20, false) == 10605L) println(monkeyBusiness(parseInput(input), 20, false)) check(monkeyBusiness(parseInput(testInput), 10000, true) == 2713310158) println(monkeyBusiness(parseInput(input), 10000, true)) }
0
Kotlin
0
0
72b3680a146d9d05be4ee209d5ba93ae46a5cb13
3,851
kotlin_aoc_22
Apache License 2.0
src/Day02.kt
Tiebe
579,377,778
false
{"Kotlin": 17146}
fun main() { fun checkRPSWin(input: List<String>): Boolean { return (input[0] == "A" && input[1] == "B") || (input[0] == "B" && input[1] == "C") || (input[0] == "C" && input[1] == "A") } fun String.mapXtoA(): String { return when (this) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> this } } fun String.mapAtoX(): String { return when (this) { "A" -> "X" "B" -> "Y" "C" -> "Z" else -> this } } fun calculateRPSScore(pair: List<String>): Int { var score = 0 if (pair[1] == "A") score += 1 if (pair[1] == "B") score += 2 if (pair[1] == "C") score += 3 if (pair[0] == pair[1]) score += 3 if (checkRPSWin(pair)) score += 6 return score } fun part1(input: List<String>): Int { var score = 0 input.forEach { inputString -> val pair = inputString.split(" ").map { when (it) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> it } } score += calculateRPSScore(pair) } return score } fun part2(input: List<String>): Int { val newList = mutableListOf<String>() input.forEach { inputString -> val pair = inputString.split(" ").map { when (it) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> it } } if (pair[1] == "A") { newList.add("${pair[0]} ${ when (pair[0]) { "A" -> "C" "B" -> "A" "C" -> "B" else -> "Z" } }") } else if (pair[1] == "B") { newList.add("${pair[0]} ${pair[0].mapAtoX()}") } else if (pair[1] == "C") { newList.add("${pair[0]} ${ when (pair[0]) { "A" -> "B" "B" -> "C" "C" -> "A" else -> "Z" } }") } } return part1(newList) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") part1(input).println() part2(input).println() }
1
Kotlin
0
0
afe9ac46b38e45bd400e66d6afd4314f435793b3
2,727
advent-of-code
Apache License 2.0
src/day05/day06.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day05 import println import readInput import kotlin.math.abs import kotlin.math.max data class Point(val x: Int, val y: Int) data class Line(val start: Point, val end: Point) fun main() { fun String.toCoords() = this.split(",").let { coords -> Point(coords[0].toInt(), coords[1].toInt()) } fun Line.isDiagonal() = this.start.x != this.end.x && this.start.y != this.end.y fun Line.addPoints(points: MutableMap<Point, Int>) { val distX = end.x - start.x val distY = end.y - start.y val steps = max(abs(distX), abs(distY)) for (inc in 0..steps) { val x = start.x + distX * inc / steps val y = start.y + distY * inc / steps points[Point(x, y)] = points.getOrDefault(Point(x, y), 0) + 1 } } fun dangerPoints(input: List<String>, predicate: (Line) -> Boolean = { true }): Int { val lines = input.map { line -> line.split(" -> ").let { Line(it[0].toCoords(), it[1].toCoords()) } } val points = mutableMapOf<Point, Int>() lines.filter(predicate).forEach { it.addPoints(points) } return points.values.count { it > 1 } } fun part1(input: List<String>) = dangerPoints(input) { !it.isDiagonal() } fun part2(input: List<String>) = dangerPoints(input) val testInput = readInput("day05/Day05_test") check(part1(testInput) == 5) check(part2(testInput) == 12) val input = readInput("day05/Day05") part1(input).println() part2(input).println() }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
1,511
advent-of-code-2021
Apache License 2.0
src/aoc2015/kot/Day16.kt
Tandrial
47,354,790
false
null
package aoc2015.kot import itertools.intoPairs import java.nio.file.Files import java.nio.file.Paths object Day16 { data class Sue(val num: Int, val stats: HashMap<String, Int>) fun parseAunts(lines: List<String>): List<Sue> { return lines.map { val attrs = hashMapOf<String, Int>() var num = 0 for ((k, v) in it.split(" ").intoPairs()) { val key = k.filter { it != ':' && it != ',' } val value = Integer.valueOf(v?.filter { it != ':' && it != ',' }) if (key == "Sue") num = value else attrs[key] = value } Sue(num, attrs) } } fun solve(aunts: List<Sue>, foundAttrs: HashMap<String, Int>, filter: (String, Int, Int) -> Boolean): Int { return aunts.first { it.stats.all { (k, v) -> filter(k, foundAttrs[k]!!, v) } }.num } } fun main(args: Array<String>) { val s = Files.readAllLines(Paths.get("./input/2015/Day16_input.txt")) val sues = Day16.parseAunts(s) val foundAttrs = hashMapOf("after" to 3, "cats" to 7, "samoyed" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1) println("Part One = ${Day16.solve(sues, foundAttrs) { _: String, fv: Int, v: Int -> fv == v }}") fun filter(key: String, fv: Int, v: Int): Boolean { if (key == "cats" || key == "trees") return fv <= v if (key == "pomeranians" || key == "goldfish") return fv > v return fv == v } println("Part Two = ${Day16.solve(sues, foundAttrs, ::filter)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
1,500
Advent_of_Code
MIT License
src/Day09.kt
freszu
573,122,040
false
{"Kotlin": 32507}
import kotlin.math.sign /** * All adjacent including diagonals + self */ private fun Position.adjacent() = sequenceOf( this, x - 1 to y, x + 1 to y, x to y - 1, x to y + 1, x - 1 to y - 1, x + 1 to y - 1, x - 1 to y + 1, x + 1 to y + 1 ) fun main() { fun headPositions(lines: List<String>): List<Position> = lines.map { val (direction, moveBy) = it.split(" ") direction to moveBy.toInt() } .fold((0 to 0) to emptyList<Pair<Int, Int>>()) { (h, moves), (direction, moveBy) -> val headPositions = (1..moveBy).map { when (direction) { "U" -> h.x to h.y + it "D" -> h.x to h.y - it "L" -> h.x - it to h.y "R" -> h.x + it to h.y else -> error("Unknown direction $direction") } } (headPositions.last()) to (moves + headPositions) }.second fun List<Position>.follow() = scan(0 to 0) { t, h -> if (h in t.adjacent()) t else t.x + (h.x - t.x).sign to t.y + (h.y - t.y).sign } fun part1(lines: List<String>) = headPositions(lines) .follow() .toSet().size // ( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°)( ͡° ͜ʖ ͡°) fun part2(lines: List<String>) = headPositions(lines) .follow().follow().follow().follow().follow().follow().follow().follow().follow() .toSet().size val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") val input = readInput("Day09") check(part1(testInput) == 13) println(part1(input)) check(part2(testInput) == 1) check(part2(testInput2) == 36) println(part2(input)) }
0
Kotlin
0
0
2f50262ce2dc5024c6da5e470c0214c584992ddb
1,823
aoc2022
Apache License 2.0
2022/src/day14/day14.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day14 import GREEN import RESET import printTimeMillis import readInput import kotlin.math.* data class Point(val x: Int, val y: Int) { fun below() = copy(x = x, y = y + 1) fun leftDiago() = copy(x = x - 1, y = y + 1) fun rightDiago() = copy(x = x + 1, y = y + 1) } // "498,4 -> 498,6 -> 496,6" => setOf([498, 4], [498, 5], [498, 6], [497, 6], [496, 6])) fun List<String>.toPoints() = map { val ret = mutableSetOf<Point>() it.split(" -> ").windowed(2, 1) { val a = it[0].split(",").let { Point(it[0].toInt(), it[1].toInt()) } val b = it[1].split(",").let { Point(it[0].toInt(), it[1].toInt()) } val res = when { a.x == b.x -> (min(a.y, b.y)..max(a.y, b.y)).map { Point(a.x, it) } a.y == b.y -> (min(a.x, b.x)..max(a.x, b.x)).map { Point(it, a.y) } else -> throw IllegalStateException("Not a line") } ret.addAll(res) } ret }.fold(mutableSetOf<Point>()) { set, points -> set.also { set.addAll(points) } } fun findNextPos(start: Point, points: Set<Point>, abyssesY: Int? = null): Point? { if (abyssesY != null && start.y >= abyssesY) return null // We reached the abysses :( if (points.contains(start.below())) { // there's an obstacle down return if (points.contains(start.leftDiago())) { // there's an obstacle left if (points.contains(start.rightDiago())) { // there's an obstacle right, we sit here start } else { findNextPos(start.rightDiago(), points, abyssesY) // continue right } } else { findNextPos(start.leftDiago(), points, abyssesY) // continue left } } return findNextPos(start.below(), points, abyssesY) // continue down } fun part1(input: List<String>) = input.toPoints().let { points -> val startSize = points.size val abysses = points.maxBy { it.y }.y val fallOrigin = Point(500, 0) var nextPos = findNextPos(fallOrigin, points, abysses) while (nextPos != null) { points.add(nextPos) nextPos = findNextPos(fallOrigin, points, abysses) } points.size - startSize } fun part2(input: List<String>) = input.toPoints().let { points -> val start = points.size val fallOrigin = Point(500, 0) val lowest = points.maxBy { it.y }.y + 2 val maxY = abs(0 - lowest) val bottomLine = ((fallOrigin.x - maxY)..(fallOrigin.x + maxY)).map { Point(it, lowest) }.toSet() points.addAll(bottomLine) var nextPos = findNextPos(fallOrigin, points)!! while (nextPos != fallOrigin) { points.add(nextPos) nextPos = findNextPos(fallOrigin, points)!! } (points.size - start - bottomLine.size) + 1 // hop petit +1 pour fix } fun main() { val testInput = readInput("day14_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day14.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
3,180
advent-of-code
Apache License 2.0
src/Day05.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
fun main() { data class Command(val amount: Int, val from: Int, val to: Int) data class Input(val stacks: List<MutableList<String>>, val commands: List<Command>) fun input(input: List<String>): Input { val stacks = mutableListOf<MutableList<String>>() var at = 0 while ('[' in input[at]) { for (i in 0 until Int.MAX_VALUE) { val p = 1 + i * 4 if (p !in input[at].indices) break if (stacks.size == i) stacks.add(mutableListOf()) if (input[at][p] != ' ') { stacks[i].add(input[at][p].toString()) } } at++ } at += 2 val commands = mutableListOf<Command>() while (at < input.size) { val ways = input[at].split(" ").map { it.toIntOrNull() }.filterNotNull() commands.add(Command(ways[0], ways[1] - 1, ways[2] - 1)) at++ } return Input(stacks, commands) } fun part1(input: List<String>): String { val (stacks, commands) = input(input) for (c in commands) { repeat(c.amount) { val x = stacks[c.from].removeFirst() stacks[c.to].add(0, x) } } return stacks.joinToString("") { it.first() } } fun part2(input: List<String>): String { val (stacks, commands) = input(input) for (c in commands) { val p = c.amount - 1 repeat(c.amount) { val x = stacks[c.from].removeAt(p - it) stacks[c.to].add(0, x) } } mutableListOf<Int>().sortedWith { a, b -> a.compareTo(b) } return stacks.joinToString("") { it.first() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") println("P1 test " + part1(testInput)) println("P1 test " + part2(testInput)) val input = readInput("Day05") println("P1 " + part1(input)) println("P2 " + part2(input)) }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
2,086
advent-of-code-2022
Apache License 2.0
src/aoc2022/Day11.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList data class Monkey( val items: MutableList<Long>, val op: String, val opVal: Long?, val test: Int, val ifTrue: Int, val ifFalse: Int, var inspections: Long = 0L ) fun main() { fun monkeys(input: List<String>): List<Monkey> { return input.windowed(6, 7).map { line -> Monkey( items = line[1].drop(" Starting items: ".length).split(", ").map { it.toLong() }.toMutableList(), op = if (line[2].contains("*")) "multiply" else "add", opVal = line[2].split(" ").last().toLongOrNull(), test = line[3].split(" ").last().toInt(), ifTrue = line[4].split(" ").last().toInt(), ifFalse = line[5].split(" ").last().toInt(), ) } } fun part1(input: List<String>) : Long { val monkeys = monkeys(input) repeat(20) { for(monkey in monkeys){ for(item in monkey.items.toList()){ val newItemWorry = if (monkey.op == "add") { item + (monkey.opVal ?: item) } else { item * (monkey.opVal ?: item) } / 3 if (newItemWorry % monkey.test == 0L) { monkeys[monkey.ifTrue].items.add(newItemWorry) } else { monkeys[monkey.ifFalse].items.add(newItemWorry) } monkey.inspections++ } monkey.items.clear() } } return monkeys.map { it.inspections}.maxOf{ it } * monkeys.map {it.inspections}.sortedDescending()[1] } fun part2(input: List<String>): Long { val monkeys = monkeys(input) val commonMultiple = monkeys.map { it.test }.fold(1L) { x, y -> x * y } repeat(10000) { for(monkey in monkeys){ for(item in monkey.items.toList()){ val newItemWorry = if (monkey.op == "add") { item + (monkey.opVal ?: item) } else { item * (monkey.opVal ?: item) } % commonMultiple if (newItemWorry % (monkey.test.toLong()) == 0L) { monkeys[monkey.ifTrue].items.add(newItemWorry) } else { monkeys[monkey.ifFalse].items.add(newItemWorry) } monkey.inspections++ } monkey.items.clear() } } return monkeys.map { it.inspections}.maxOf{ it } * monkeys.map {it.inspections}.sortedDescending()[1] } val input = readInputAsList("Day11", "2022") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
2,870
AOC-2022-Kotlin
Apache License 2.0
src/Day12.kt
mrugacz95
572,881,300
false
{"Kotlin": 102751}
import java.util.PriorityQueue import kotlin.math.min private data class Vertex( var height: Char, var steps: Int = Int.MAX_VALUE, val x: Int, val y: Int, ) : Comparable<Vertex> { var prev: Vertex? = null val neighbours: MutableList<Vertex> = mutableListOf() override fun compareTo(other: Vertex): Int { return this.steps - other.steps } override fun toString(): String { return "Vertex(x=$x, y=$y, height=$height, steps=$steps)" } } private data class Graph(val vertices: List<List<Vertex>>, val start: List<Vertex>, val end: Vertex) private val COLORS = (231 downTo 226).toList() + (190 downTo 46 step 36).toList() + (47..51).toList() + (87..195 step 36).toList() + (194 downTo 191).toList() + listOf(155, 119) private fun Graph.print() { val result = Array(vertices.size) { Array(vertices[it].size) { "." } } var vertex = end while (true) { val prev = vertex.prev ?: break val c = when { prev.x - 1 == vertex.x -> "<" prev.x + 1 == vertex.x -> ">" prev.y - 1 == vertex.y -> "^" prev.y + 1 == vertex.y -> "V" else -> throw Exception("Unknown") } result[prev.y][prev.x] = "\u001b[38;5;${167}m\u001B[1m$c\u001b[0m" vertex = prev } result[end.y][end.x] = "\u001b[38;5;${167}m" + "E" vertices.flatten().map { val h = it.height - 'a' result[it.y][it.x] = "\u001b[48;5;${COLORS[h]}m" + result[it.y][it.x] + "\u001b[0m" } println(result.joinToString("\n") { it.joinToString("") }) } private fun Graph.dijkstra() { val queue = PriorityQueue<Vertex>() val visited = HashSet<Vertex>() queue.addAll(this.start) this.start.map { it.steps = 0 } while (queue.isNotEmpty()) { val current = queue.poll() if (current in visited) continue visited.add(current) for (neighbour in current.neighbours) { if (neighbour in visited) continue neighbour.steps = min(neighbour.steps, current.steps + 1) neighbour.prev = current queue.add(neighbour) } } } fun main() { fun List<String>.parse(): Graph { val neighbours = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, 1), Pair(0, -1)) val vertices = mapIndexed { y, line -> line.mapIndexed { x, c -> Vertex(c, x = x, y = y) } } val start: Vertex = vertices.flatten().firstOrNull { it.height == 'S' } ?: throw Exception("No start node found") val end: Vertex = vertices.flatten().firstOrNull { it.height == 'E' } ?: throw Exception("No start node found") start.height = 'a' end.height = 'z' for (y in this.indices) { val line = get(y) for (x in line.indices) { val v = vertices[y][x] for ((ny, nx) in neighbours) { if (ny + y >= 0 && ny + y < this.size && nx + x >= 0 && nx + x < line.length && v.height >= vertices[y + ny][x + nx].height - 1 ) { v.neighbours.add(vertices[y + ny][x + nx]) } } } } return Graph(vertices, listOf(start), end) } fun part1(input: List<String>): Int { val graph = input.parse() graph.dijkstra() graph.print() return graph.end.steps } fun part2(input: List<String>): Int { val graph = input.parse().let { val aVertices = it.vertices.flatten().filter { v -> v.height == 'a' } it.copy(start = aVertices) } graph.dijkstra() return graph.end.steps } val testInput = readInput("Day12_test") val input = readInput("Day12") assert(part1(testInput), 31) println(part1(input)) assert(part2(testInput), 29) println(part2(input)) } // Time: 01:35
0
Kotlin
0
0
29aa4f978f6507b182cb6697a0a2896292c83584
4,032
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day3/Diagnostics.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package day3 import utils.Binary import utils.read fun main() { solve().forEach { println(it) } } fun solve(): List<Long> { val data = read("./src/main/resources/day3Input.txt") .map { Binary.from(it) } var mostCommonBits = mostCommonBits(data) val gamma = mostCommonBits.asLong() val epsilon = mostCommonBits.invert().asLong() val oxygen = solve(data, 0, true) val co2 = solve(data, 0,false) return listOf( gamma * epsilon, oxygen.asLong()*co2.asLong()) } fun solve(data: List<Binary>, i: Int, mostCommon: Boolean): Binary { if (data.size == 1) { return data.first() } else { val commonBits = mostCommonBits(data) val bitsToLook = if (mostCommon) commonBits else commonBits.invert() val filtered = data.filter { it.bit(i) == bitsToLook.bit(i) } return solve(filtered, i + 1, mostCommon); } } private fun mostCommonBits(data: List<Binary>): Binary { // All rows have same amount of bits val mostCommon = (0 until data[0].bits().size) // Gives us the vertical bit rows .map { index -> data.map { it.bit(index) } } // Lets change 0 to -1 .map { it.map { bit -> if (bit == 0) -1 else 1 } } // And finally if we take sum, we know did we have more 1's than 0's .map { if (it.sum() < 0) 0 else 1 } return Binary.from(mostCommon) }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
1,445
adventOfCode2021
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2021/Day21.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 21 - <NAME> * Problem Description: http://adventofcode.com/2021/day/21 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day21/ */ package com.ginsberg.advent2021 class Day21(input: List<String>) { private val player1Start: Int = input.first().substringAfterLast(" ").toInt() private val player2Start: Int = input.last().substringAfterLast(" ").toInt() private val initialGameState = GameState(PlayerState(player1Start), PlayerState(player2Start)) private val quantumDieFrequency: Map<Int, Long> = mapOf(3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1) private val stateMemory: MutableMap<GameState, WinCounts> = mutableMapOf() fun solvePart1(): Int { var game = initialGameState val die = DeterministicDie() while (!game.isWinner()) { game = game.next(die.roll()) } return game.minScore() * die.rolls } fun solvePart2(): Long = playQuantum().max() private fun playQuantum(state: GameState = initialGameState): WinCounts = when { state.isWinner(21) -> if (state.player1.score > state.player2.score) WinCounts(1, 0) else WinCounts(0, 1) state in stateMemory -> stateMemory.getValue(state) else -> quantumDieFrequency.map { (die, frequency) -> playQuantum(state.next(die)) * frequency }.reduce { a, b -> a + b }.also { stateMemory[state] = it } } private class DeterministicDie(var value: Int = 0, var rolls: Int = 0) { fun roll(): Int { rolls += 3 value += 3 return 3 * value - 3 } } private class WinCounts(val player1: Long, val player2: Long) { operator fun plus(other: WinCounts): WinCounts = WinCounts(player1 + other.player1, player2 + other.player2) operator fun times(other: Long): WinCounts = WinCounts(player1 * other, player2 * other) fun max(): Long = maxOf(player1, player2) } private data class GameState(val player1: PlayerState, val player2: PlayerState, val player1Turn: Boolean = true) { fun next(die: Int): GameState = GameState( if (player1Turn) player1.next(die) else player1, if (!player1Turn) player2.next(die) else player2, player1Turn = !player1Turn ) fun isWinner(scoreNeeded: Int = 1000): Boolean = player1.score >= scoreNeeded || player2.score >= scoreNeeded fun minScore(): Int = minOf(player1.score, player2.score) } private data class PlayerState(val place: Int, val score: Int = 0) { fun next(die: Int): PlayerState { val nextPlace = (place + die - 1) % 10 + 1 return PlayerState( place = nextPlace, score = score + nextPlace ) } } }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
3,080
advent-2021-kotlin
Apache License 2.0
src/main/kotlin/net/dilius/daily/coding/problem/n00x/002.kt
diliuskh
298,020,928
false
null
package net.dilius.daily.coding.problem.n00x import net.dilius.daily.coding.problem.Problem /* Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? */ class ProductsExceptCurrent : Problem<IntArray, IntArray> { override fun solve(input: IntArray): IntArray { val product = input.reduce { acc, i -> acc * i } return input.map { product / it }.toIntArray() } } class ProductsExceptCurrentNoDivision : Problem<IntArray, IntArray> { override fun solve(input: IntArray): IntArray { val product = input.reduce { acc, i -> acc * i } return input.map { divide(product, it) }.toIntArray() } private fun divide(a: Int, b: Int): Int { val sign = if ((a < 0) xor (b < 0)) -1 else 1 var i = 0 var n = a while (n >= b) { n -= b i++ } if (sign == -1) i = -i return i } } class ProductsExceptCurrentNoDivisionPrefixSuffix: Problem<IntArray, IntArray> { override fun solve(input: IntArray): IntArray { val prefixProducts = IntArray(input.size) val suffixProducts = IntArray(input.size) for (i in input.indices) { prefixProducts[i] = input[i] * if (i == 0) 1 else prefixProducts[i-1] } for (i in input.indices.reversed()) { suffixProducts[i] = input[i] * if (i == input.size - 1) 1 else suffixProducts[i+1] } return input.indices.map { when (it) { 0 -> suffixProducts[it+1] input.size -1 -> prefixProducts[it -1] else -> prefixProducts[it -1] * suffixProducts[it+1] } }.toIntArray() } }
0
Kotlin
0
0
7e5739f87dbce2b56d24e7bab63b6cee6bbc54bc
2,014
dailyCodingProblem
Apache License 2.0
y2019/src/main/kotlin/adventofcode/y2019/Day18.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import adventofcode.util.vector.Direction import adventofcode.util.vector.Vec2 import adventofcode.util.vector.neighbors fun main() = Day18.solve() object Day18 : AdventSolution(2019, 18, "Many-Worlds Interpretation") { private val alphabet = 'a'..'z' override fun solvePartOne(input: String): Int? { val (floor, objectAtLocation) = readMaze(input) return solve(floor, objectAtLocation, "@".toSet()) } override fun solvePartTwo(input: String): Any? { val (floor: MutableSet<Vec2>, objectAtLocation: MutableMap<Vec2, Char>) = readMaze(input) val center = objectAtLocation.asSequence().first { it.value == '@' }.key floor.apply { remove(center) Direction.values().map { it.vector + center }.forEach { remove(it) } } objectAtLocation.remove(center) objectAtLocation[center + Vec2(-1, -1)] = '1' objectAtLocation[center + Vec2(1, -1)] = '2' objectAtLocation[center + Vec2(-1, 1)] = '3' objectAtLocation[center + Vec2(1, 1)] = '4' return solve(floor, objectAtLocation, "1234".toSet()) } private fun solve(floor: Set<Vec2>, objectAtLocation: Map<Vec2, Char>, startSymbols: Set<Char>): Int? { val distancesWithClosedDoors: Map<Char, Map<Char, Int>> = generateDistanceMap(floor, objectAtLocation) val keyDistancesWithOpenDoors: Map<Char, Map<Char, Int>> = generateDistanceMap(floor + objectAtLocation.keys, objectAtLocation.filterValues { it in alphabet || it in startSymbols }) val keysNeededFor: Map<Char, Set<Char>> = requiredKeysForKey(distancesWithClosedDoors, startSymbols) return memoizedPath(keysNeededFor, keyDistancesWithOpenDoors, startSymbols) } private fun readMaze(input: String): Pair<MutableSet<Vec2>, MutableMap<Vec2, Char>> { val floor = mutableSetOf<Vec2>() val objectAtLocation = mutableMapOf<Vec2, Char>() input.lines().forEachIndexed { y, line -> line.forEachIndexed { x, ch -> when (ch) { '.' -> floor += Vec2(x, y) '#' -> { } else -> objectAtLocation[Vec2(x, y)] = ch } } } return Pair(floor, objectAtLocation) } private fun generateDistanceMap(floor: Set<Vec2>, objectAtLocation: Map<Vec2, Char>): Map<Char, Map<Char, Int>> { val neighbors = Direction.values().map { it.vector } fun Vec2.openNeighbors() = neighbors.map { this + it }.filter { it in floor } fun findOpenPaths(startObj: Char, start: Vec2): Map<Char, Int> { var open = setOf(start) val closed = mutableSetOf(start) val objects = mutableMapOf(startObj to 0) var distance = 0 while (open.isNotEmpty()) { distance++ open = open.flatMap { it.openNeighbors() }.filter { it !in closed }.toSet() closed += open open.forEach { target -> target.neighbors().mapNotNull { objectAtLocation[it] } .forEach { objects.putIfAbsent(it, distance + 1) } } } return objects.toSortedMap() } return objectAtLocation.asSequence().associate { it.value to findOpenPaths(it.value, it.key) } } private fun requiredKeysForKey(directDistances: Map<Char, Map<Char, Int>>, start: Set<Char>): Map<Char, Set<Char>> { val requiredKeysForKey = start.associateWith { emptySet<Char>() }.toMutableMap() var open = start while (open.isNotEmpty()) { val new = mutableSetOf<Char>() open.forEach { from -> directDistances[from]?.keys.orEmpty() .filter { it !in requiredKeysForKey.keys } .forEach { to -> requiredKeysForKey[to] = requiredKeysForKey[from].orEmpty() + from.lowercaseChar() new += to } } open = new } return requiredKeysForKey .mapValues { (_, reqs)-> reqs.filter { it in alphabet }.toSet() } .filterKeys { it in alphabet } } private fun memoizedPath(keysNeededFor: Map<Char, Set<Char>>, keyDistancesWithOpenDoors: Map<Char, Map<Char, Int>>, startSymbols: Set<Char>): Int? { val bestPaths = mutableMapOf<Pair<Set<Char>, Set<Char>>, Int?>() fun bestPaths(from: Set<Char>, collected: Set<Char>): Int? = bestPaths.getOrPut(from to collected) { if (collected.size == alphabet.last - alphabet.first + 1) 0 else alphabet.asSequence() .filter { it !in collected } .filter { new -> keysNeededFor[new].orEmpty().all { it in collected } } .mapNotNull { to -> val toRemove = from.intersect(keyDistancesWithOpenDoors.getValue(to).keys).single() bestPaths(from - toRemove + to, collected + to)?.let { it + keyDistancesWithOpenDoors.getValue( toRemove ).getValue(to) } } .minOrNull() } return bestPaths(startSymbols, emptySet()) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
5,454
advent-of-code
MIT License