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
advent-of-code2015/src/main/kotlin/day1/Advent1.kt
REDNBLACK
128,669,137
false
null
package day1 import parseInput /** --- Day 1: Not Quite Lisp --- Santa was hoping for a white Christmas, but his weather machine's "snow" function is powered by stars, and he's fresh out! To save Christmas, he needs you to collect fifty stars by December 25th. Collect stars by helping Santa solve puzzles. Two puzzles will be made available on each day in the advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Here's an easy puzzle to warm you up. Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? Your puzzle answer was 138. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character position 1. ()()) causes him to enter the basement at character position 5. What is the position of the character that causes Santa to first enter the basement? */ fun main(args: Array<String>) { println(findFloor("(())") == 0) println(findFloor("()()") == 0) println(findFloor("(((") == 3) println(findFloor("(()(()(") == 3) println(findFloor("())") == -1) println(findFloor("))(") == -1) println(findFloor(")))") == -3) println(findFloor(")())())") == -3) val input = parseInput("day1-input.txt") println(findFloor(input)) println(findFloor(input, true)) } fun findFloor(input: String, second: Boolean = false): Int { val tokens = mapOf('(' to 1, ')' to -1) tailrec fun loop(pos: Int, counter: Int): Int { if (pos == input.length) return counter if (second && counter == -1) return pos return loop(pos + 1, counter + (tokens[input[pos]] ?: 0)) } return loop(0, 0) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
2,658
courses
MIT License
2021/src/day25/Day25.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day25 import readInput import java.lang.IllegalStateException import java.text.SimpleDateFormat import java.util.* typealias Table = Array<CharArray> fun List<String>.toTable(): Table { val ret = Array<CharArray>(this.size) { CharArray(0) } for (y in indices) ret[y] = this[y].toCharArray() return ret } fun Table.print(stepNb: Int) { val nb = stepNb.toString() println(nb + ")" + "=".repeat(this[0].size - nb.length - 1)) for (c in this) println(c) println("=".repeat(this[0].size)) } fun Table.getPos(x: Int, y: Int): Char { if (y < 0) return this[lastIndex][x] if (x < 0) return this[y][this[y].lastIndex] if (y >= size) return this[0][x] if (x >= this[y].size) return this[y][0] return this[y][x] } fun Table.setPos(x: Int, y: Int, c: Char) { when { y < 0 -> this[lastIndex][x] = c x < 0 -> this[y][this[y].lastIndex] = c y >= size -> this[0][x] = c x >= this[y].size -> this[y][0] = c else -> this[y][x] = c } } fun runStep(table: Table): Boolean { // Occupy any '>' that moved with 'E' (new pos) // and replace the current pos by 'R' to avoid any '>' to take its place for (y in table.indices) { for (x in table[y].indices) { val current = table[y][x] if (current == '>' && table.getPos(x + 1, y) == '.') { table.setPos(x + 1, y, 'E') table[y][x] = 'R' } } } // Occupy any 'v' that moved with 'T' (new pos) // and replace the current pos by 'S' to avoid any 'v' to take its place for (x in table[0].indices) { for (y in table.indices) { val current = table[y][x] if ((current == '.' || current == 'R') && table.getPos(x, y - 1) == 'v') { table.setPos(x, y, 'S') table.setPos(x, y - 1, 'T') } } } var replaced = false for (y in table.indices) { for (x in table[y].indices) { when (table[y][x]) { 'E' -> table[y][x] = '>' 'S' -> table[y][x] = 'v' 'T', 'R' -> { table[y][x] = '.' replaced = true } } } } return replaced } fun part1(lines: List<String>): Int { val table = lines.toTable() table.print(0) var stepNb = 0 do { val replaced = runStep(table) stepNb++ table.print(stepNb) } while (replaced) return stepNb } fun part2(lines: List<String>): Int { return 2 } fun main() { val test = readInput("day25/test") println("part1(test) => " + part1(test)) // println("part2(test) => " + part2(test)) val input = readInput("day25/input") println("part1(input) => " + part1(input)) // println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,881
advent-of-code
Apache License 2.0
src/day2/Day02.kt
MatthewWaanders
573,356,006
false
null
package day2 import utils.readInput const val rockValue = 1 const val paperValue = 2 const val scissorValue = 3 const val winValue = 6 const val drawValue = 3 const val lossValue = 0 val partOneChoiceValueMap = mapOf( "X" to rockValue, "Y" to paperValue, "Z" to scissorValue ) val partOneMatchResultsMatrix = mapOf( "A" to mapOf( "X" to drawValue, "Y" to winValue, "Z" to lossValue, ), "B" to mapOf( "X" to lossValue, "Y" to drawValue, "Z" to winValue, ), "C" to mapOf( "X" to winValue, "Y" to lossValue, "Z" to drawValue, ), ) val partTwoMatchResultValueMap = mapOf( "X" to lossValue, "Y" to drawValue, "Z" to winValue, ) val partTwoChoiceMatrix = mapOf( "A" to mapOf( "X" to scissorValue, "Y" to rockValue, "Z" to paperValue, ), "B" to mapOf( "X" to rockValue, "Y" to paperValue, "Z" to scissorValue, ), "C" to mapOf( "X" to paperValue, "Y" to scissorValue, "Z" to rockValue, ), ) fun main() { val testInput = readInput("Day02_test", "day2") check(part1(testInput) == 15) val input = readInput("Day02", "day2") println(part1(input)) println(part2(input)) } fun part1(input: List<String>) = input.sumOf { val (opponent, me) = it.split(" ") partOneMatchResultsMatrix[opponent]!![me]!! + partOneChoiceValueMap[me]!! } fun part2(input: List<String>) = input.sumOf { val (opponent, me) = it.split(" ") partTwoChoiceMatrix[opponent]!![me]!! + partTwoMatchResultValueMap[me]!! }
0
Kotlin
0
0
f58c9377edbe6fc5d777fba55d07873aa7775f9f
1,637
aoc-2022
Apache License 2.0
src/Day20.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { infix fun Long.modulo(modulus: Long): Long { val remainder = this % modulus if (this >= modulus) return this % (modulus-1) if ((kotlin.math.abs(this) >= modulus)&&(this < 0)) return (this % (modulus-1)) + modulus - 1 return if (remainder >= 0) remainder else remainder + modulus - 1 } fun part1(input:List<String>){ val initList = input.map { it.toInt() } var currentList = initList.mapIndexed { index, i -> mapOf(index to i) }.toMutableList() var elem: Map<Int, Int> var elemId: Int println(initList) initList.forEachIndexed { index, i -> elem = currentList.first { it.keys.first() == index } elemId = currentList.indexOfFirst{it.keys.first() == index} currentList.removeIf { it.keys.first() == index } var newIndexCycle = elemId+elem.values.first().toLong() modulo (initList.size.toLong()) currentList.add(index=newIndexCycle.toInt(), elem) } // println(currentList.map { it.values.take(1) }) var idxsZero = currentList.indexOfFirst { it.values.first() == 0 } // println("base $idxsZero") println(currentList[(idxsZero+1000) % initList.size].values.first()+ currentList[(idxsZero+2000) % initList.size].values.first()+ currentList[(idxsZero+3000) % initList.size].values.first()) } fun part2(input:List<String>){ var key = 811589153.toLong() val initList = input.map { it.toLong()*key } var currentList = initList.mapIndexed { index, i -> mapOf(index to i) }.toMutableList() var elem: Map<Int, Long> var elemId: Int println(initList) repeat(10) { initList.forEachIndexed { index, i -> elem = currentList.first { it.keys.first() == index } elemId = currentList.indexOfFirst { it.keys.first() == index } currentList.removeIf { it.keys.first() == index } var newIndexCycle = elemId + elem.values.first() modulo (initList.size.toLong()) currentList.add(index = newIndexCycle.toInt(), elem) }} println(currentList.map { it.values.take(1) }) // } var idxsZero = currentList.indexOfFirst { it.values.first() == 0.toLong() } // println("base $idxsZero") println(currentList[(idxsZero+1000) % initList.size].values.first()+ currentList[(idxsZero+2000) % initList.size].values.first()+ currentList[(idxsZero+3000) % initList.size].values.first()) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day20") part2(testInput) // 6919 is too low // part2(testInput) }
0
Kotlin
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
2,817
aoc22
Apache License 2.0
src/main/kotlin/com/eric/leetcode/SatisfiabilityOfEqualityEquations.kt
wanglikun7342
163,727,208
false
{"Kotlin": 172132, "Java": 27019}
package com.eric.leetcode class SatisfiabilityOfEqualityEquations { private class UnionFind(n: Int) { private val parent: Array<Int> = Array(n) { it } fun find(input: Int): Int { var x = input while (x != parent[x]) { parent[x] = parent[parent[x]] x = parent[x] } return x } fun union(x:Int, y:Int) { val rootX = find(x) val rootY = find(y) parent[rootX] = rootY } fun isConnected(x: Int, y: Int): Boolean { return find(x) == find(y) } } fun equationsPossible(equations: Array<String>): Boolean { val unionFind = UnionFind(26) for (equation in equations) { if (equation[1] == '=') { val index1 = equation[0] - 'a' val index2 = equation[3] - 'a' unionFind.union(index1, index2) } } for (equation in equations) { if (equation[1] == '!') { val index1 = equation[0] - 'a' val index2 = equation[3] - 'a' if (unionFind.isConnected(index1, index2)) { // 如果合并失败,表示等式有矛盾,根据题意,返回 false return false } } } // 如果检查了所有不等式,都没有发现矛盾,返回 true return true } } fun main(args: Array<String>) { val equations = arrayOf("a==c","c==d","d!=a") val satisfiabilityOfEqualityEquations = SatisfiabilityOfEqualityEquations() println(satisfiabilityOfEqualityEquations.equationsPossible(equations)) }
0
Kotlin
2
8
d7fb5ff5a0a64d9ce0a5ecaed34c0400e7c2c89c
1,750
Leetcode-Kotlin
Apache License 2.0
src/Day02.kt
aeisele
572,478,307
false
{"Kotlin": 4468}
enum class Shape(val worth: Int) { ROCK(1), PAPER(2), SCISSORS(3) } fun main() { fun charsFromLine(line: String): Pair<Char, Char> { val tokens = line.split(' ') return Pair(tokens[0][0], tokens[1][0]) } fun toShape(c: Char): Shape { return when (c) { 'A', 'X' -> Shape.ROCK 'B', 'Y' -> Shape.PAPER 'C', 'Z' -> Shape.SCISSORS else -> throw RuntimeException("invalid input") } } fun calcRound(opponent: Shape, mine: Shape): Int { return mine.worth + when (opponent) { Shape.ROCK -> when (mine) { Shape.ROCK -> 3 Shape.PAPER -> 6 Shape.SCISSORS -> 0 } Shape.PAPER -> when (mine) { Shape.ROCK -> 0 Shape.PAPER -> 3 Shape.SCISSORS -> 6 } Shape.SCISSORS -> when (mine) { Shape.ROCK -> 6 Shape.PAPER -> 0 Shape.SCISSORS -> 3 } } } fun toWin(opponent: Shape): Shape { return when(opponent) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } } fun toLose(opponent: Shape): Shape { return when(opponent) { Shape.ROCK -> Shape.SCISSORS; Shape.PAPER -> Shape.ROCK; Shape.SCISSORS -> Shape.PAPER } } fun part1(input: List<String>): Int { var sum = 0 for (line in input) { val chars = charsFromLine(line) sum += calcRound(toShape(chars.first), toShape(chars.second)); } return sum } fun part2(input: List<String>): Int { var sum = 0; for (line in input) { val chars = charsFromLine(line); val opponent = toShape(chars.first) val mine = when (chars.second) { 'X' -> toLose(opponent) 'Y' -> opponent 'Z' -> toWin(opponent) else -> throw RuntimeException("invalid input") } sum += calcRound(opponent, mine); } return sum; } // 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") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
40a867c599fda032660724b81b0c12070ac5ba87
2,531
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/day5/Day5.kt
afTrolle
572,960,379
false
{"Kotlin": 33530}
package day5 import Day import ext.component6 fun main() { Day5("Day05").solve() } class Day5(input: String) : Day<Pair<List<MutableList<Char>>, List<Day5.Action>>>(input) { data class Action(val from: Int, val to: Int, val units: Int) override fun parseInput(): Pair<List<MutableList<Char>>, List<Action>> { val (init, actions) = inputByGroups val towerByRows = init.dropLast(1).map { line -> line.chunked(4).map { it[1].takeIf(Char::isLetter) } } val numberOfTowers = init.last().split(" ").mapNotNull(String::toIntOrNull).max() val towers = List(numberOfTowers) { towerIndex -> towerByRows.mapNotNullTo(mutableListOf()) { it.getOrNull(towerIndex) } } val tasks = actions.map { val (_, units, _, from, _, to) = it.split(" ").map(String::toIntOrNull) Action(from!!, to!!, units!!) } return towers to tasks } override fun part1(input: Pair<List<MutableList<Char>>, List<Action>>): Any { val (towers, tasks) = input tasks.forEach { (from, to, units) -> for (x in 0 until units) { val item = towers[from - 1].removeFirst() towers[to - 1].add(0, item) } } return towers.map { it.first() }.joinToString(separator = "") } override fun part2(input: Pair<List<MutableList<Char>>, List<Action>>): Any { val (towers, tasks) = input tasks.forEach { (from, to, units) -> val cargo = List(units) { towers[from - 1].removeFirst() } towers[to - 1].addAll(0, cargo) } return towers.map { it.first() }.joinToString(separator = "") } }
0
Kotlin
0
0
4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545
1,752
aoc-2022
Apache License 2.0
src/Day09.kt
oleskrede
574,122,679
false
{"Kotlin": 24620}
import kotlin.math.abs import kotlin.math.max fun main() { val toDirection = mapOf( "R" to Direction.RIGHT, "U" to Direction.UP, "L" to Direction.LEFT, "D" to Direction.DOWN, ) fun isTouching(a: Position, b: Position): Boolean { val dx = abs(a.x - b.x) val dy = abs(a.y - b.y) return max(dx, dy) <= 1 } fun simulateRope(ropeSize: Int, input: List<String>): Int { val knots = MutableList(ropeSize) { Position(0, 0) } val tailPositions = mutableSetOf(knots.last()) for (headMotion in input) { val tokens = headMotion.trim().split(" ") val headDir = toDirection[tokens.first()]!! val headDist = tokens[1].toInt() for (headStep in 0 until headDist) { knots[0] = Position(knots[0].x + headDir.dx, knots[0].y + headDir.dy) for (i in 1 until knots.size) { val prevKnot = knots[i - 1] val knot = knots[i] if (!isTouching(prevKnot, knot)) { // Find and normalize direction from knot to prevKnot var dx = prevKnot.x - knot.x var dy = prevKnot.y - knot.y dx /= max(1, abs(dx)) dy /= max(1, abs(dy)) knots[i] = Position(knot.x + dx, knot.y + dy) } } tailPositions.add(knots.last()) } } return tailPositions.size } fun part1(input: List<String>): Int { return simulateRope(2, input) } fun part2(input: List<String>): Int { return simulateRope(10, input) } val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") test(part1(testInput), 13) test(part2(testInput2), 36) val input = readInput("Day09") timedRun { part1(input) } timedRun { part2(input) } } private enum class Direction(val dx: Int, val dy: Int) { UP(0, 1), DOWN(0, -1), LEFT(-1, 0), RIGHT(1, 0) } private data class Position(val x: Int, val y: Int)
0
Kotlin
0
0
a3484088e5a4200011335ac10a6c888adc2c1ad6
2,166
advent-of-code-2022
Apache License 2.0
2022/main/day_15/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_15_2022 import java.io.File import kotlin.math.abs import kotlin.math.absoluteValue val inputRe = Regex("[\\w\\s]*x=(?<xPos>-?\\d+), y=(?<yPos>-?\\d+):[\\w\\s]*x=(?<xTarget>-?\\d+), y=(?<yTarget>-?\\d+)") fun part1(input: List<String>) { val parsed = input.mapNotNull(inputRe::find) .map { it.destructured.toList().map(String::toInt) } .map { (xPos, yPos, xTarget, yTarget) -> (xPos to yPos) to (xTarget to yTarget) } val row2000000 = mutableSetOf<Int>() parsed.forEach { val (xPos, yPos) = it.first val (xTarget, yTarget) = it.second val dst = (xPos - xTarget).absoluteValue + (yPos-yTarget).absoluteValue val dstToY = (yPos - 2000000).absoluteValue if (dstToY <= dst) { val width = dst - dstToY row2000000.addAll((xPos - width)..(xPos + width)) } if (yTarget == 2000000) { row2000000.remove(xTarget) } } print("The number of positions that cannot contain a beacon is ${row2000000.size}") } fun part2(input: List<String>) { val max = 4000000 val sensors = input.mapNotNull(inputRe::find) .map { it.destructured.toList().map(String::toInt) } .map { (xPos, yPos, xTarget, yTarget) -> (xPos to yPos) to (xTarget to yTarget) } val safeRangesPerLine = Array<MutableList<IntRange>>(max + 1) { mutableListOf() } sensors.forEach { (sensor, beacon) -> for (y in 0..max) { val dst = (sensor.first - beacon.first).absoluteValue + (sensor.second-beacon.second).absoluteValue val dstToY = abs(sensor.second - y) val width = dst - dstToY if (width > 0) { safeRangesPerLine[y].add(sensor.first - width..sensor.first + width) } } } safeRangesPerLine.forEachIndexed { y, ranges -> val sortedRanges = ranges.sortedBy { it.first } var highest = sortedRanges.first().last sortedRanges.drop(1).map { if (it.first > highest) { print("The tuning frequency is ${(it.first - 1).toBigInteger() * 4000000.toBigInteger() + y.toBigInteger()}") } if (it.last > highest) { highest = it.last } } } } fun main(){ val inputFile = File("2022/inputs/Day_15.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
2,512
AdventofCode
MIT License
src/Day05.kt
zhtk
579,137,192
false
{"Kotlin": 9893}
private data class CrateMove(val amount: Int, val from: Int, val to: Int) fun main() { val input = readInput("Day05") val stackDescription = input.takeWhile { it.isNotEmpty() }.dropLast(1).map { it.chunked(4).map { it[1] } } val crateMovement = input.dropWhile { it.isNotEmpty() }.drop(1).map { val description = it.split(' ') CrateMove(description[1].toInt(), description[3].toInt() - 1, description[5].toInt() - 1) } simulateCrateMovement(stackDescription, crateMovement) { stack, movement -> repeat(movement.amount) { stack[movement.to].add(stack[movement.from].removeLast()) } }.println() simulateCrateMovement(stackDescription, crateMovement) { stack, movement -> stack[movement.to].addAll(stack[movement.from].takeLast(movement.amount)) repeat(movement.amount) { stack[movement.from].removeLast() } }.println() } private fun simulateCrateMovement( stackDescription: List<List<Char>>, crateMovement: List<CrateMove>, moveInterpretation: (Array<ArrayDeque<Char>>, CrateMove) -> Unit ): String { val stack = Array(stackDescription[0].size) { ArrayDeque<Char>() } stackDescription.reversed().forEach { it.forEachIndexed { pileNumber, crate -> if (crate != ' ') stack[pileNumber].add(crate) } } crateMovement.forEach { moveInterpretation(stack, it) } return stack.joinToString("") { it.last().toString() } }
0
Kotlin
0
0
bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1
1,452
aoc2022
Apache License 2.0
src/Day08.kt
anisch
573,147,806
false
{"Kotlin": 38951}
typealias Forest = List<List<Tree>> data class Tree( val height: Int, var isVisible: Boolean = false, var score: Int = 0, ) fun createForest(input: List<String>): Forest = input .map { line -> line.chunked(1).map { s -> Tree(s.toInt()) } } fun Forest.checkTreeVisibility() { // from left to right side (indices).forEach { row -> var max = -1 (this[row].indices).forEach { col -> if (this[row][col].height > max) { max = this[row][col].height this[row][col].isVisible = true } } } // from right to left side (indices).forEach { row -> var max = -1 (this[row].indices.reversed()).forEach { col -> if (this[row][col].height > max) { max = this[row][col].height this[row][col].isVisible = true } } } // from top to bottom side (this[0].indices).forEach { col -> var max = -1 (this[col].indices).forEach { row -> if (this[row][col].height > max) { max = this[row][col].height this[row][col].isVisible = true } } } // from bottom to top side (this[0].indices).forEach { col -> var max = -1 (this[col].indices.reversed()).forEach { row -> if (this[row][col].height > max) { max = this[row][col].height this[row][col].isVisible = true } } } } fun Forest.calcTreeScores() { (1 until this.size - 1).forEach { row -> (1 until this[0].size - 1).forEach { col -> val ch = this[row][col].height // looking right var ix = 0 var max = 0 for (c in col + 1 until this[row].size) { ix++ val next = this[row][c].height if (next >= ch) break if (max <= next) max = next } // looking left var jx = 0 max = 0 for (c in col - 1 downTo 0) { jx++ val next = this[row][c].height if (next >= ch) break if (max <= next) max = next } // looking down var kx = 0 max = 0 for (r in row + 1 until this.size) { kx++ val next = this[r][col].height if (next >= ch) break if (max <= next) max = next } // looking up var lx = 0 max = 0 for (r in row - 1 downTo 0) { lx++ val next = this[r][col].height if (next >= ch) break if (max <= next) max = next } this[row][col].score = ix * jx * kx * lx } } } fun main() { fun part1(input: List<String>): Int { val forest = createForest(input) forest.checkTreeVisibility() return forest.sumOf { row -> row.count { tree -> tree.isVisible } } } fun part2(input: List<String>): Int { val forest = createForest(input) forest.checkTreeVisibility() forest.calcTreeScores() return forest.maxOf { row -> row.maxOf { tree -> tree.score } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val input = readInput("Day08") check(part1(testInput) == 21) println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
3,770
Advent-of-Code-2022
Apache License 2.0
src/Day15.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.io.Reader import kotlin.math.abs fun main() { val testInput = """ 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() val parsedTest = parseInput(testInput.reader()) check(partOne(parsedTest, 10) == 26) val testPartTwo = partTwo(parsedTest, 20) check(testPartTwo.tuningFrequency == 56000011L) val parsed = parseInput(reader("Day15.txt")) println(partOne(parsed, 2000000)) val partTwo = partTwo(parsed, 4000000) //println(partTwo) println(partTwo.tuningFrequency) } val TunnelCoordinates.tuningFrequency get() = this.x * 4000000L + this.y private fun partTwo(sensorBeacons: List<SensorBeacon>, maxXY: Int): TunnelCoordinates { for (y in 0..maxXY) { val ranges = sensorBeacons.mapNotNull { it.xRangeCovered(y) }.sortedBy { it.first } var x = 0 for (i in 0..ranges.lastIndex) { val range = ranges[i] if (x in range) { x = range.last + 1 } } if (x < maxXY) { return(TunnelCoordinates(x, y)) } } TODO() } private fun partOne(sensorBeacons: List<SensorBeacon>, y: Int): Int { val empties = mutableSetOf<TunnelCoordinates>() sensorBeacons.forEach { sb -> val (sensor, beacon) = sb empties.addAll(sensor.getEmptyBeacons(beacon, y)) } return empties.size } private fun parseInput(src: Reader): List<SensorBeacon> { val out = mutableListOf<SensorBeacon>() val beacons = mutableMapOf<TunnelCoordinates, TunnelCoordinates>() val coordRegex = Regex("""-?\d+""") src.forEachLine { line -> val (sensorX, sensorY, beaconX, beaconY) = coordRegex.findAll(line).toList().map { it.value.toInt() } val sensor = TunnelCoordinates(sensorX, sensorY) val beacon = TunnelCoordinates(beaconX, beaconY).let { beacons[it] ?: it.also { beacons[it] = it } } out += SensorBeacon(sensor, beacon) } return out } data class SensorBeacon( val sensor: TunnelCoordinates, val nearestBeacon: TunnelCoordinates ) { private val beaconDistance = sensor.manhattanDistance(nearestBeacon) fun xRangeCovered(y: Int): IntRange? { val yDist = abs(sensor.y - y) if (yDist > beaconDistance) return null val xDelta = abs(beaconDistance - yDist) val min = sensor.x - xDelta val max = sensor.x + xDelta return min..max } } data class TunnelCoordinates( val x: Int, val y: Int ) fun TunnelCoordinates.manhattanDistance(other: TunnelCoordinates): Int { return abs(this.x - other.x) + abs(this.y - other.y) } fun TunnelCoordinates.getEmptyBeacons(beacon: TunnelCoordinates, y: Int): Set<TunnelCoordinates> { val distance = this.manhattanDistance(beacon) val empties = mutableSetOf<TunnelCoordinates>() if (y in this.y-distance..this.y+distance) { val yDist = y - this.y val plusMinus = distance - abs(yDist) val x1 = this.x - plusMinus val x2 = this.x + plusMinus for (x in x1..x2) { empties += TunnelCoordinates(x, y) } } empties -= this empties -= beacon return empties }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
4,009
advent-of-code-2022-kotlin
Apache License 2.0
src/Day02.kt
yalexaner
573,141,113
false
{"Kotlin": 4235}
@file:JvmName("Day2Kt") import kotlin.math.max fun main() { runTests() val input = readInput("Day02") println(part1(input)) } private fun runTests() { val testInput = readInput("Day02_test") val part1Result = part1(testInput) check(part1Result == 15) { "part1 is $part1Result, but expected 15" } } private fun part1(input: List<String>): Int { var score = 0 for (position in input) { val outcome = computeOutcome(position) ?: return -1 score += computeScore(outcome, position) ?: return -1 } return score } /** * Enemy's hand: A for Rock, B for Paper, and C for Scissors * Player's hand: X for Rock, Y for Paper, and Z for Scissors */ private fun computeOutcome(position: String): Outcome? { val winPositions = listOf("A Y", "B Z", "C X") val losePositions = listOf("A Z", "B X", "C Y") val drawPositions = listOf("A X", "B Y", "C Z") return when (position) { in winPositions -> Outcome.WIN in losePositions -> Outcome.LOSE in drawPositions -> Outcome.DRAW else -> null } } private fun computeScore(outcome: Outcome, position: String): Int? { var score = 0 score += when (outcome) { Outcome.WIN -> 6 Outcome.DRAW -> 3 Outcome.LOSE -> 0 } val playersHand = position.split(" ").last() score += when (playersHand) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> return null } return score } private enum class Outcome { WIN, LOSE, DRAW }
0
Kotlin
0
0
58c2bf57543253db544fa8950aac4dc67896b808
1,543
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/jball/aoc2022/day14/Day14.kt
fibsifan
573,189,295
false
{"Kotlin": 43681}
package de.jball.aoc2022.day14 import de.jball.aoc2022.Day import kotlin.math.abs class Day14(test: Boolean = false): Day<Int>(test, 24, 93) { private val rocks = input.map { rockFormation -> rockFormation.split(" -> ") .map { coordinate -> val (x, y) = coordinate.split(",") Point(x.toInt(), y.toInt()) } .windowed(2) .flatMap { (a, b) -> a..b } }.flatten().toSet() private val restingGrains = mutableSetOf<Point>() private val lowestRock = rocks.maxBy { (_, b) -> b }.y private val dropPoint = Point(500,0) override fun part1(): Int { while(true) { var grain = dropPoint var nextPosition = nextPosition(grain) while (nextPosition != null && nextPosition.y <= lowestRock) { grain = nextPosition nextPosition = nextPosition(grain) } if (grain.y >= lowestRock) { return restingGrains.size } restingGrains.add(grain) } } private fun nextPosition(grain: Point): Point? { for (candidate in listOf(Point(grain.x, grain.y+1), Point(grain.x-1, grain.y+1), Point(grain.x+1, grain.y+1))) { if (!rocks.contains(candidate) && !restingGrains.contains(candidate)) { return candidate } } return null } override fun part2(): Int { while(true) { var grain = dropPoint var nextPosition = nextPosition(grain) while (nextPosition != null && nextPosition.y <= lowestRock+1) { grain = nextPosition nextPosition = nextPosition(grain) } restingGrains.add(grain) if (grain == dropPoint) { return restingGrains.size } } } } class Point(val x: Int, val y: Int) { operator fun component1() = x operator fun component2() = y operator fun rangeTo(other: Point): List<Point> { return if (x == other.x) { List(abs(other.y-y) + 1) { x } .zip(if(y < other.y) y..other.y else y downTo other.y) .map {(a, b) -> Point(a, b) } } else if (y == other.y) { (if(x < other.x) x..other.x else x downTo other.x) .zip(List(abs(other.x - x) + 1) { y }) .map {(a, b) -> Point(a, b) } } else { error("range from $this to $other is not horizontally or vertically.") } } override fun toString(): String { return "$x,$y" } override fun hashCode(): Int { return ((3 * x.hashCode()) + 5) * y.hashCode() } override fun equals(other: Any?): Boolean { return other is Point && other.x == x && other.y == y } } fun main() { Day14().run() }
0
Kotlin
0
3
a6d01b73aca9b54add4546664831baf889e064fb
2,887
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day13.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import utils.InputUtils fun columns(input: List<String>): List<String> = input[0].indices.map { index -> String(input.map { it[index] }.toCharArray()) } fun main() { val testInput = """#.##..##. ..#.##.#. ##......# ##......# ..#.##.#. ..##..##. #.#.##.#. #...##..# #....#..# ..##..### #####.##. #####.##. ..##..### #....#..#""".trimIndent().split("\n") fun findReflection(map: List<String>): List<Int> { val possibles = map.zipWithNext() .mapIndexed { index, pair -> index to pair } .filter { (_, x) -> x.first == x.second } .map { it.first } // n where the fold is between n and n+1 val filtered = possibles.filter { it.downTo(0).zip(it + 1..<map.size).all { (a, b) -> map[a] == map[b] } } return filtered } fun findReflection2(map: List<String>, errors: Int = 0): List<Int> { return map.indices.filter { it.downTo(0).zip(it + 1..<map.size) .map { (a, b) -> map[a] to map[b]} .sumOf { (a, b) -> a.zip(b).count { (x,y) -> x != y } } == errors } } fun part1(input: List<String>): Int { return input.toBlocksOfLines() //.onEach { println(columns(it)) } .map { map -> 100 * findReflection(map).sumOf { it+1 } + findReflection(columns(map)).sumOf { it+1} } .sum() } fun part2(input: List<String>): Int { return input.toBlocksOfLines() //.onEach { println(columns(it)) } .map { map -> 100 * findReflection2(map,1).sumOf { it+1 } + findReflection2(columns(map),1).sumOf { it+1} } .sum() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 405) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 13) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,065
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day22/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day22 import java.io.File fun main() { val inputLineRegex = """(on|off) x=([-]?\d+)..([-]?\d+),y=([-]?\d+)..([-]?\d+),z=([-]?\d+)..([-]?\d+)""".toRegex() val lines = File("src/main/kotlin/day22/input.txt").readLines() val rebootSteps = lines.map { line -> val (state, x0, x1, y0, y1, z0, z1) = inputLineRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException("Invalid input") RebootStep(state == "on", Cuboid(x0.toInt()..x1.toInt(), y0.toInt()..y1.toInt(), z0.toInt()..z1.toInt())) } val initializingRebootSteps = rebootSteps.filter { it.cube.x.first >= -50 && it.cube.x.last <= 50 && it.cube.y.first >= -50 && it.cube.y.last <= 50 && it.cube.z.first >= -50 && it.cube.z.last <= 50 } println(initializingRebootSteps.calculateTurnedOn()) println(rebootSteps.calculateTurnedOn()) } fun List<RebootStep>.calculateTurnedOn(): Long { val xCutPoints = flatMap { listOf(it.cube.x.first, it.cube.x.last + 1) }.distinct().sorted() val yCutPoints = flatMap { listOf(it.cube.y.first, it.cube.y.last + 1) }.distinct().sorted() val zCutPoints = flatMap { listOf(it.cube.z.first, it.cube.z.last + 1) }.distinct().sorted() val space = Array(xCutPoints.size - 1) { Array(yCutPoints.size - 1) { BooleanArray(zCutPoints.size - 1) } } //compress val xCompressedCutPoints = xCutPoints.withIndex().associateBy({ it.value }, { it.index }) val yCompressedCutPoints = yCutPoints.withIndex().associateBy({ it.value }, { it.index }) val zCompressedCutPoints = zCutPoints.withIndex().associateBy({ it.value }, { it.index }) for (rebootStep in this) { val cube = rebootStep.cube for (x in xCompressedCutPoints[cube.x.first]!! until xCompressedCutPoints[cube.x.last + 1]!!) { for (y in yCompressedCutPoints[cube.y.first]!! until yCompressedCutPoints[cube.y.last + 1]!!) { for (z in zCompressedCutPoints[cube.z.first]!! until zCompressedCutPoints[cube.z.last + 1]!!) { space[x][y][z] = rebootStep.turnedOn } } } } //decompress and count var count = 0L for (x in space.indices) { for (y in space[x].indices) { for (z in space[x][y].indices) { if (space[x][y][z]) count += 1L * (xCutPoints[x + 1] - xCutPoints[x]) * (yCutPoints[y + 1] - yCutPoints[y]) * (zCutPoints[z + 1] - zCutPoints[z]) } } } return count } data class RebootStep(val turnedOn: Boolean, val cube: Cuboid) data class Cuboid(val x: IntRange, val y: IntRange, val z: IntRange)
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,642
aoc-2021
MIT License
2021/src/day15/day15.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day15 import java.io.File fun main() { val board = Board.getBoard(File("src/day15", "day15input.txt").readLines(), true) println("[${board.numRows} x ${board.numCols}]") println(board.getLowestPathSum()) } class Board(private val data: Array<IntArray>, val multiplied: Boolean = false) { val numCols = data[0].size val numRows = data.size val cache: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() fun getRows(): Int { return if (multiplied) { numRows * 5 } else { numRows } } fun getCols(): Int { return if (multiplied) { numCols * 5 } else { numCols } } fun getLowestPathSum(): Int { return getLowestPathSum(Pair(getRows() - 1, getCols() - 1)) } fun getLowestPathSum(cell: Pair<Int, Int>): Int { if (cache.containsKey(cell)) { return cache[cell]!! } return if (isStart(cell)) { 0 } else { getValue(cell) + (getNeighbors(cell).minOf { neighbor -> getLowestPathSum(neighbor) .also { if (!cache.containsKey(neighbor) || it < cache[neighbor]!!) { cache[neighbor] = it } } }) } } private fun isStart(cell: Pair<Int, Int>): Boolean { return cell.first == 0 && cell.second == 0 } fun getNeighbors(cell: Pair<Int, Int>): List<Pair<Int, Int>> { // Only build up and to the left return buildList { val rowIndex = cell.first val colIndex = cell.second if (rowIndex > 0) add(Pair(rowIndex - 1, colIndex)) if (colIndex > 0) add(Pair(rowIndex, colIndex - 1)) // if (colIndex < getCols() - 1) add(Pair(rowIndex, colIndex + 1)) // if (rowIndex < getRows() - 1) add(Pair(rowIndex + 1, colIndex)) } } fun getValue(cell: Pair<Int, Int>): Int { return if (multiplied) { val tileY = cell.first / numRows val tileX = cell.second / numCols val innerIndexY = cell.first % numRows val innerIndexX = cell.second % numCols val startValue = data[innerIndexY][innerIndexX] val computedValue = (startValue + tileY + tileX) if (computedValue <= 9) { computedValue } else { (computedValue) % 9 } } else { data[cell.first][cell.second] } } companion object { fun getBoard(input: List<String>, multiplied: Boolean = false): Board { return Board( input.map { it.toCharArray() .map { cell -> cell.digitToInt() } .toIntArray() }.toTypedArray(), multiplied ) } } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,004
adventofcode
Apache License 2.0
src/main/kotlin/Problem12.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
/** * Highly divisible triangular number * * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be * 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: * * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * 1: 1 * 3: 1,3 * 6: 1,2,3,6 * 10: 1,2,5,10 * 15: 1,3,5,15 * 21: 1,3,7,21 * 28: 1,2,4,7,14,28 * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred divisors? * * https://projecteuler.net/problem=12 */ fun main() { println(highlyDivisibleTriangularNumber(5)) println(highlyDivisibleTriangularNumber(500)) } private fun highlyDivisibleTriangularNumber(n: Int): Int { var num = 1 while (true) { val triangular = (num * (num + 1)) / 2 val numberOfFactors = primeFactorizationOf(triangular) .map { it.value + 1 } .fold(1L) { acc, i -> acc * i } if (numberOfFactors > n) { return triangular } num++ } } fun primeFactorizationOf(n: Int): Map<Int, Int> = buildMap { var num = n while (num != 1) { primeLoop@ for (i in 1..n) { if (primes[i] == 0) { primes[i] = findPrime(i).toInt() } val prime = primes[i] if (num % prime == 0) { num /= prime set(prime, getOrDefault(prime, 0) + 1) break@primeLoop } } } } private val primes = IntArray(65500) { 0 }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
1,651
project-euler
MIT License
year2019/src/main/kotlin/net/olegg/aoc/year2019/day12/Day12.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2019.day12 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.utils.lcf import net.olegg.aoc.year2019.DayOf2019 import kotlin.math.sign /** * See [Year 2019, Day 12](https://adventofcode.com/2019/day/12) */ object Day12 : DayOf2019(12) { private val PATTERN = "<.=(-?\\d+), .=(-?\\d+), .=(-?\\d+)>".toRegex() override fun first(): Any? { val initial = lines .mapNotNull { line -> PATTERN.find(line)?.let { match -> val (x, y, z) = match.destructured.toList().map { it.toInt() } return@let Vector3D(x, y, z) } } val planets = initial.map { it to Vector3D() } repeat(1000) { planets.map { first -> planets.forEach { second -> val diff = second.first - first.first first.second += Vector3D(diff.x.sign, diff.y.sign, diff.z.sign) } } planets.forEach { (position, speed) -> position += speed } } return planets.sumOf { it.first.manhattan() * it.second.manhattan() } } override fun second(): Any? { val initial = lines .mapNotNull { line -> PATTERN.find(line)?.let { match -> val (x, y, z) = match.destructured.toList().map { it.toInt() } return@let Vector3D(x, y, z) } } val planets = initial.map { it to Vector3D() } val footprints = List(3) { mutableMapOf<List<Int>, Long>() } val repeats = mutableMapOf<Int, Long>() var step = 0L while (repeats.size < footprints.size) { val curr = footprints.indices.map { axis -> planets.flatMap { (planet, speed) -> listOf(planet[axis], speed[axis]) } } curr.forEachIndexed { axis, footprint -> if (axis !in repeats) { if (footprint in footprints[axis]) { repeats[axis] = step - (footprints[axis][footprint] ?: 0L) } else { footprints[axis][footprint] = step } } } step++ planets.map { first -> planets.forEach { second -> val diff = second.first - first.first first.second += Vector3D(diff.x.sign, diff.y.sign, diff.z.sign) } } planets.forEach { (position, speed) -> position += speed } } return repeats.values.reduce { a, b -> lcf(a, b) } } } fun main() = SomeDay.mainify(Day12)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,380
adventofcode
MIT License
2020/kotlin/day-7/main.kt
waikontse
330,900,073
false
null
import util.FileUtils fun main() { val fileUtils = FileUtils("input.txt") // Do some processing of the input for grokking later on. val cleanLines = cleanInputLines(fileUtils.lines) val mapOfBags = bagsToMap(cleanLines) println (mapOfBags) println (findTargetBags(mapOfBags, "shiny gold")) println (findTargetBags2(mapOfBags, "shiny gold")) println (findTargetBags2Helper(mapOfBags, "shiny gold")) println (findTargetBags2(mapOfBags, "shiny gold").map { getMultiplier(it)}) println (findTargetBags2(mapOfBags, "shiny gold").map { getBag(it)}) } fun cleanInputLines(rawData: List<String>): List<List<String>> { return rawData .map { it.replace(" bags contain", ",") } .map { it.replace(Regex(" bags?"), "") } .map { it.replace(".", "") } .map { it.split(',').map { it.trim() } } } fun bagsToMap(bagsConfiguration: List<List<String>>): Map<String, List<String>> { val mutableMapOfBags = mutableMapOf<String, List<String>>(); return bagsConfiguration .associateByTo(mutableMapOfBags, { it.first() }, { it.subList(1, it.lastIndex + 1) }) } fun findTargetBags(bagsConfig: Map<String, List<String>>, targetBag: String): Int { val containerBagsSet = mutableSetOf<String>() findTargetBagsHelper(bagsConfig, targetBag, containerBagsSet) return containerBagsSet.size } fun findTargetBagsHelper(bagsConfig: Map<String, List<String>>, targetBag: String, containerBags: MutableSet<String>) { val foundContainers = findContainerBags(bagsConfig, targetBag) containerBags.addAll(foundContainers) foundContainers.map { findTargetBagsHelper(bagsConfig, it, containerBags) } } fun findContainerBags(bagsConfig: Map<String, List<String>>, targetBag: String): Set<String> { return bagsConfig .filter { it.value.map { it.contains(targetBag) }.contains(true) } .keys } fun findTargetBags2(bagsConfig: Map<String, List<String>>, targetBag: String): List<String> { return bagsConfig .filter { it.key.contains(targetBag) } .values .flatten() } fun findTargetBags2Helper(bagsConfig: Map<String, List<String>>, targetBag: String): Int { if (bagsConfig.get(targetBag)!!.contains("no other")) { return 1 } val bagCount = findTargetBags2(bagsConfig, targetBag) .map { getMultiplier(it) * findTargetBags2Helper(bagsConfig, getBag(it)) + getMultiplier(it) * isFinalBag(bagsConfig, getBag(it)) } .sum() return bagCount } fun getMultiplier(bag: String): Int { return bag.split(' ')[0].toInt() } fun isFinalBag(bagsConfig: Map<String, List<String>>, targetBag: String): Int { if (bagsConfig.get(targetBag)!!.contains("no other")) { return 0 } else { return 1 } } fun getBag(bag: String): String { return bag.replace(Regex("\\d+ "), "") }
0
Kotlin
0
0
abeb945e74536763a6c72cebb2b27f1d3a0e0ab5
2,911
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/advent/day18/Snailfish.kt
hofiisek
434,171,205
false
{"Kotlin": 51627}
package advent.day18 import advent.loadInput import java.io.File /** * @author <NAME> */ fun part1(input: File) = input.readLines() // .first() // .let { pairs -> buildTreeRecursively(RootNode(), pairs.drop(1))} .map { snailfishNumber -> buildTreeRecursively(RootNode(), snailfishNumber.drop(1))} .onEach(::println) .map { it.reduce() } .onEach(::println) .reduce { first, second -> first sumWith second } .let { val summed = it println("after addition: $it") val reduced = summed.reduce() println("---------------------") println("final sum: $reduced") } fun buildTreeRecursively(curr: TreeNode, snailfishNumber: String): TreeNode = when { snailfishNumber.isBlank() -> curr snailfishNumber.first() == ',' -> buildTreeRecursively(curr, snailfishNumber.drop(1)) snailfishNumber.first() == ']' -> when (curr) { is RootNode -> curr is InternalNode -> buildTreeRecursively(curr.parent, snailfishNumber.drop(1)) is LeafNode -> buildTreeRecursively(curr.parent, snailfishNumber.drop(1)) } snailfishNumber.first() == '[' -> when (curr) { is RootNode, is InternalNode -> { buildTreeRecursively( curr = InternalNode(parent = curr).also { curr.appendChild(it) }, snailfishNumber = snailfishNumber.drop(1) ) } is LeafNode -> throw IllegalArgumentException("Leaf node can't have any children") } snailfishNumber.first().isDigit() -> { curr.appendChild(LeafNode(parent = curr, value = snailfishNumber.first().digitToInt())) buildTreeRecursively(curr, snailfishNumber.drop(1)) } else -> throw IllegalArgumentException("Invalid format of snailfish pairs: $snailfishNumber") } infix fun RootNode.sumWith(otherRoot: RootNode): RootNode { val newRoot = RootNode() val newLeft = this@sumWith.rebuildTreeWithNewRoot(newRoot) val newRight = otherRoot.rebuildTreeWithNewRoot(newRoot) return newRoot.apply { left = newLeft right = newRight } } fun RootNode.rebuildTreeWithNewRoot(newRoot: RootNode): TreeNode { fun rebuildTree(curr: TreeNode, parent: TreeNode): TreeNode = when (curr) { is RootNode, is InternalNode -> { InternalNode(parent = parent).apply { left = curr.left?.let { rebuildTree(it, this) } right = curr.right?.let { rebuildTree(it, this) } } } is LeafNode -> LeafNode(value = curr.value, parent = parent) } val rebuilt = rebuildTree(this, newRoot) return rebuilt } fun TreeNode.reduce(): RootNode { // explode action // - node must be nested inside four (or more) pairs // - node must be an internal node // - both children must be leaf nodes firstOrNull { it.depth >= 4 && it is InternalNode // && listOfNotNull(it.left, it.right).all { it is LeafNode } } ?.let { it as InternalNode } ?.explode() ?.also { println("after explode: $it") } ?.reduce() // split action // - must be a leaf node with value >= 10 firstOrNull { it is LeafNode && it.value >= 10 } ?.let { it as LeafNode } ?.split() ?.also { println("after split: $it") } ?.reduce() // return root node if no more nodes can explode or split return backToRoot() } fun part2(input: File) = Unit fun main() { // with(loadInput(day = 18)) { // with(loadInput(day = 18, filename = "input_example.txt")) { // with(loadInput(day = 18, filename = "explode_examples.txt")) { with(loadInput(day = 18, filename = "sum_example.txt")) { part1(this) println(part2(this)) } }
0
Kotlin
0
2
3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb
3,781
Advent-of-code-2021
MIT License
src/Day07.kt
findusl
574,694,775
false
{"Kotlin": 6599}
import java.io.File import java.util.Stack private fun part1(input: File): Int { val root = input.useLines { PredictiveIterator(it.iterator()).parseFileSystem() } return root.allDirectories().filter { it.size < 100000 }.sumOf { it.size } } private fun part2(input: File): Int { val root = input.useLines { PredictiveIterator(it.iterator()).parseFileSystem() } val freeSpace = 70000000 - root.size val sizeNeeded = 30000000 - freeSpace return root.allDirectories().map { it.size }.filter { it > sizeNeeded }.min() } private fun FileSystem.Directory.allDirectories(): List<FileSystem.Directory> { return children.values.filterIsInstance<FileSystem.Directory>().flatMap { it.allDirectories() } + this } private fun PredictiveIterator<String>.parseFileSystem( root: FileSystem.Directory = FileSystem.Directory(), current: FileSystem.Directory = root ): FileSystem.Directory { if (!hasNext()) return root return when (val command = next()) { "$ cd /" -> { parseFileSystem(root, root) } "$ ls" -> { do { val subFile = takeNextIf { !it.startsWith("$") } ?: break if (subFile.startsWith("dir")) { val fileName = subFile.substring(4) current.children[fileName] = FileSystem.Directory(parent = current) } else { val (size, name) = subFile.split(' ') current.children[name] = FileSystem.File(size.toInt(), current) } } while (true) parseFileSystem(root, current) } "$ cd .." -> { parseFileSystem(root, current.parent as FileSystem.Directory) } else -> { assert(command.startsWith("$ cd")) val fileName = command.substring(5) val file = current.children[fileName] as? FileSystem.Directory checkNotNull(file) { "No directory $fileName for command $command" } parseFileSystem(root, file) } } } private sealed interface FileSystem { val size: Int val parent: FileSystem? class File(override val size: Int, override val parent: FileSystem): FileSystem class Directory( val children: MutableMap<String, FileSystem> = mutableMapOf(), override val parent: FileSystem? = null ): FileSystem { override val size: Int by lazy { children.values.sumOf { it.size } } } } private class PredictiveIterator<T: Any>(private val iterator: Iterator<T>): Iterator<T> { private var next: T? = null override fun hasNext(): Boolean = next != null || iterator.hasNext() override fun next(): T { val next = this.next return if (next != null) { this.next = null next } else { iterator.next() } } fun takeNextIf(predicate: (T) -> Boolean): T? { if (next != null) return next if (!iterator.hasNext()) return null val next = iterator.next() return if (predicate(next)) next else { this.next = next null } } } fun main() { runDay(7, 95437, ::part1) runDay(7, 24933642, ::part2) }
0
Kotlin
0
0
035f0667c115b09dc36a475fde779d4b74cff362
3,271
aoc-kotlin-2022
Apache License 2.0
src/day07/Day07.kt
wickenico
573,048,677
false
{"Kotlin": 27144}
package day07 import day07.Directory.Companion.ROOT import readInput private class Directory(val parent: Directory?, val children: MutableList<Directory> = mutableListOf()) { var size = 0L fun getTotal(): Long = this.size + this.children.sumOf { it.getTotal() } companion object { val ROOT: Directory = Directory( parent = null ) } } fun main() { fun createFilesystemGraph(input: List<String>): List<Directory> { var current = ROOT val directories = mutableListOf(ROOT) input.forEach { line -> when { line == "$ cd /" -> { current = ROOT } line == "$ cd .." -> { current = current.parent ?: current } line.startsWith("$ cd ") -> { val directory = Directory(parent = current) current.children.add(directory) if (!directories.contains(directory)) { directories.add(directory) } current = directory } line.first().isDigit() -> { current.size += line.substringBefore(" ").toLong() } else -> { // Not necessary } } } return directories.toList() } fun part1(input: List<String>): Long { val directories = createFilesystemGraph(input) return directories.map { it.getTotal() }.filter { it <= 100_000 }.sum() } fun part2(input: List<String>): Long { val directories = createFilesystemGraph(input) val missingSpace = 30_000_000 - (70_000_000 - directories.first().getTotal()) return directories.filter { it.getTotal() >= missingSpace }.minOf { it.getTotal() } } val input = readInput("day07/Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
1,997
advent-of-code-kotlin-2022
Apache License 2.0
kotlin/src/main/kotlin/io/github/ocirne/aoc/year2023/Day5.kt
ocirne
327,578,931
false
{"Python": 323051, "Kotlin": 67246, "Sage": 5864, "JavaScript": 832, "Shell": 68}
package io.github.ocirne.aoc.year2023 import io.github.ocirne.aoc.AocChallenge import kotlin.math.max import kotlin.math.min class Day5(val lines: List<String>) : AocChallenge(2023, 5) { data class UseType(val start: Long, val end: Long, val delta: Long) private val seeds = if (lines.isEmpty()) { listOf() } else { lines.first().split(":").last().trim().split(" ").map { it.toLong() } } class Almanac(val lines: List<String>) { private val almanac = addMissingRanges(readAlmanac(lines)) private fun readAlmanac(lines: List<String>): List<List<UseType>> { if (lines.isEmpty()) { return listOf() } val rawAlmanac = mutableListOf<List<UseType>>() var useTypes = mutableListOf<UseType>() for (line in lines.drop(1)) { when { line.isBlank() -> { if (useTypes.isNotEmpty()) { rawAlmanac.add(useTypes) } useTypes = mutableListOf() } line.endsWith(':') -> { // ignore } else -> { val (destinationStart, sourceStart, rangeLength) = line.split(' ').map { it.toLong() } val sourceEnd = sourceStart + rangeLength val delta = destinationStart - sourceStart useTypes.add(UseType(sourceStart, sourceEnd, delta)) } } } rawAlmanac.add(useTypes) return rawAlmanac } private fun addMissingRanges(rawAlmanac: List<List<UseType>>): List<List<UseType>> { return rawAlmanac.map { useTypes -> val t = useTypes.sortedBy { it.start } val useType = mutableListOf(t.first()) t.zipWithNext { a, b -> if (a.end < b.start) { useType.add(UseType(a.end, b.start, 0)) } useType.add(b) } listOf(UseType(Long.MIN_VALUE, t.first().start, 0)) + useType.toList() + listOf(UseType(t.last().end, Long.MAX_VALUE, 0)) } } fun findLocation(start: Long, end: Long, depth: Int = 0): Long { if (depth >= almanac.size) { return start } return almanac[depth].filter { useType -> start < useType.end && useType.start < end }.minOfOrNull { useType -> findLocation( start = max(start + useType.delta, useType.start + useType.delta), end = min(end + useType.delta, useType.end + useType.delta), depth = depth + 1, ) } ?: Long.MAX_VALUE } } private val almanac = Almanac(lines) override fun part1(): Long { return seeds.minOf { seed -> almanac.findLocation(seed, seed + 1) } } override fun part2(): Long { return seeds.chunked(2).minOf { (start, length) -> almanac.findLocation(start, start + length) } } }
0
Python
0
1
b8a06fa4911c5c3c7dff68206c85705e39373d6f
3,376
adventofcode
The Unlicense
src/Day05.kt
DeltaSonic62
572,718,847
false
{"Kotlin": 8676}
fun getData(input: List<String>): Pair<MutableList<MutableList<String>>, MutableList<List<Int>>> { val crates = mutableListOf<MutableList<String>>(mutableListOf()) val instructions = mutableListOf<List<Int>>() var isCratesDone = false; for (line in input) { if (line.isBlank()) continue if (line[1] == '1') { isCratesDone = true continue } if (isCratesDone) { val inst1 = line.split("move")[1].split("from")[0].trim().toInt(); val inst2 = line.split("move")[1].split("from")[1].split("to")[0].trim().toInt(); val inst3 = line.split("move")[1].split("from")[1].split("to")[1].trim().toInt(); instructions.add(listOf(inst1, inst2, inst3)); continue } while (crates.size <= getColCount(input) - 1) { crates += mutableListOf<String>() } for ((index, i) in (line.indices step 4).withIndex()) { if (line.substring(i..i + 2).isNotBlank()) { crates[index].add(line.substring(i..i + 2)) } } } return Pair(crates, instructions) } fun getColCount(input: List<String>): Int { for (line in input) { if (line[1] == '1') return line.trim().last().toString().toInt() } return 0 } fun getTops(crates: List<List<String>>): String { var res = "" for (col in crates) { if (col.isNotEmpty()) res += col[0][1] } return res } fun main() { fun part1(input: List<String>): String { val (crates, instructions) = getData(input) for (ins in instructions) { for (i in 0 until ins[0]) { val temp = crates[ins[1] - 1].first() crates[ins[1] - 1].removeAt(0) crates[ins[2] - 1].add(0, temp) } } return getTops(crates); } fun part2(input: List<String>): String { val (crates, instructions) = getData(input) for (ins in instructions) { for (i in ins[0] - 1 downTo 0) { val temp = crates[ins[1] - 1][i] crates[ins[1] - 1].removeAt(i) crates[ins[2] - 1].add(0, temp) } } return getTops(crates) } // 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)) }
0
Kotlin
0
0
7cdf94ad807933ab4769ce4995a43ed562edac83
2,557
aoc-2022-kt
Apache License 2.0
src/main/kotlin/day09/Solution.kt
TestaDiRapa
573,066,811
false
{"Kotlin": 50405}
package day09 import java.io.File import kotlin.math.abs data class Position( val x: Int = 0, val y: Int = 0 ) { fun doAStep(direction: Direction): Position { return when (direction) { Direction.UP -> this.copy(y = y+1) Direction.DOWN -> this.copy(y = y-1) Direction.LEFT -> this.copy(x = x-1) Direction.RIGHT -> this.copy(x = x+1) } } fun follow(position: Position): Position = if ( abs(x - position.x) <= 1 && abs(y - position.y) <= 1) this else if ( y == position.y) this.copy(x = x + if (position.x > x) 1 else -1) else if ( x == position.x) this.copy(y = y + if (position.y > y) 1 else -1) else this.copy(x = x + if (position.x > x) 1 else -1, y = y + if (position.y > y) 1 else -1) } class Rope( length: Int = 0, nodes: List<Position> = emptyList() ) { private val nodes = nodes.ifEmpty { List(length) { Position() } } private fun updateRecursive(headPosition: Position, nodes: List<Position>): List<Position> { return if(nodes.isEmpty()) emptyList() else { val newHead = nodes.first().follow(headPosition) listOf(newHead) + updateRecursive(newHead, nodes.subList(1, nodes.size)) } } fun doAStep(direction: Direction): Rope { val newHead = nodes.first().doAStep(direction) return Rope( nodes = listOf(newHead) + updateRecursive(newHead, nodes.subList(1, nodes.size)) ) } fun getTailPosition() = nodes.last() } enum class Direction { UP, DOWN, LEFT, RIGHT; companion object { fun from(s: String): Direction { return when (s) { "U" -> UP "D" -> DOWN "L" -> LEFT "R" -> RIGHT else -> throw Exception() } } } } fun parseTailMovementAndCountPositions(size: Int) = File("src/main/kotlin/day09/input.txt") .readLines() .fold(Pair(Rope(size), setOf(Position()))) { acc, line -> val (d, amount) = line.split(" ") val direction = Direction.from(d) (0 until amount.toInt()).fold(acc) { innerAcc, _ -> val newRope = innerAcc.first.doAStep(direction) Pair( newRope, innerAcc.second + newRope.getTailPosition() ) } }.second.size fun main() { println("The number of positions the short rope visited at least once is: ${parseTailMovementAndCountPositions(2)}") println("The number of positions the long rope visited at least once is: ${parseTailMovementAndCountPositions(10)}") }
0
Kotlin
0
0
b5b7ebff71cf55fcc26192628738862b6918c879
2,730
advent-of-code-2022
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day14.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.y2015.data.Day14Data object Day14 { private val input = Day14Data.input private val reindeerRegex = """^(\w+) can fly (\d+) km/s for (\d+) seconds?, but then must rest for (\d+) seconds?\.$""".toRegex() fun part1(): Int { val reindeer = input.lines().map { Reindeer(it.toReindeerSpec()) } return generateSequence(State(reindeer)) { it.move() }.dropWhile { it.turn < 2503 }.first().reindeer.maxOf { it.first.distance } } fun part2(): Int { val reindeer = input.lines().map { Reindeer(it.toReindeerSpec()) } return generateSequence(State(reindeer)) { it.move() }.dropWhile { it.turn < 2503 }.first().reindeer.maxOf { it.second } } private data class ReindeerSpec(val name: String, val speed: Int, val endurance: Int, val sleepiness: Int) private fun String.toReindeerSpec(): ReindeerSpec { val match = reindeerRegex.matchEntire(this) ?: error("Wrong reindeer spec: $this") val (name, speed, endurance, sleepiness) = match.destructured return ReindeerSpec(name, speed.toInt(), endurance.toInt(), sleepiness.toInt()) } private enum class ReindeerState { FLYING, RESTING, } private class Reindeer(val spec: ReindeerSpec, val state: ReindeerState, val distance: Int, val countdown: Int) { constructor(spec: ReindeerSpec) : this(spec, ReindeerState.FLYING, 0, spec.endurance) fun move(): Reindeer = when (state) { ReindeerState.FLYING -> { if (countdown > 0) { Reindeer(spec, ReindeerState.FLYING, distance + spec.speed, countdown - 1) } else { Reindeer(spec, ReindeerState.RESTING, distance, spec.sleepiness - 1) } } ReindeerState.RESTING -> { if (countdown > 0) { Reindeer(spec, ReindeerState.RESTING, distance, countdown - 1) } else { Reindeer(spec, ReindeerState.FLYING, distance + spec.speed, spec.endurance - 1) } } } } private class State(val turn: Int, val reindeer: List<Pair<Reindeer, Int>>) { constructor(reindeer: List<Reindeer>) : this(0, reindeer.map { it to 0 }) fun move(): State { val newReindeer = reindeer.map { (r, s) -> r.move() to s } val furthest = newReindeer.maxOf { it.first.distance } val scoredReindeer = newReindeer.map { (r, s) -> r to if (r.distance == furthest) s + 1 else s } return State(turn + 1, scoredReindeer) } } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
2,750
adventofcode2015
MIT License
src/Day01.kt
aaronbush
571,776,335
false
{"Kotlin": 34359}
fun main() { fun loadInventory(input: List<String>): Map<Int, List<Int>> { val inventory = mutableMapOf<Int, MutableList<Int>>() var elf = 1 input.forEach { if (it.isEmpty()) { elf++ } else { val cals = inventory.getOrDefault(elf, mutableListOf()) cals += it.toInt() inventory[elf] = cals } } return inventory } fun part1(input: List<String>): Int { val inventory = loadInventory(input) val result = inventory.map { entry -> entry.key to entry.value.sum() }.toMap() println(result) return result.maxOf { it.value } } fun part2(input: List<String>): Int { val inventory = loadInventory(input) val result = inventory.map { entry -> entry.key to entry.value.sum() }.toMap() val sorted = result.toSortedMap { o1, o2 -> if (result[o1]!! > result[o2]!!) -1 else 1 } // reverse order println(sorted.values.take(3)) return sorted.values.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") // check(part1(testInput) == 24000) part2(testInput) val input = readInput("Day01") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d76106244dc7894967cb8ded52387bc4fcadbcde
1,407
aoc-2022-kotlin
Apache License 2.0
src/Day11.kt
MerickBao
572,842,983
false
{"Kotlin": 28200}
import java.math.BigInteger fun main() { var LCM = 1L fun gcd(a: Long, b: Long): Long { if (b == 0L) return a return gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return a * b / gcd(a, b) } class Node { var id: Int = 0 var items= arrayListOf<BigInteger>() var op: String = "" var factor: Long = 0 var test: Long = 0 var trueId: Int = 0 var falseId: Int = 0 } fun next(op: String, x: BigInteger, y: BigInteger): BigInteger { if (op == "+") return x.add(y) if (op == "-") return x.subtract(y) if (op == "*") return x.multiply(y) return x / y } fun game(input: List<String>): Long { val monkey = arrayListOf<Node>() var idx = 0 while (idx < input.size) { val node = Node() node.id = idx / 7 var now = input[idx + 1].trim().split(" ") val items = arrayListOf<BigInteger>() for (i in 2 until now.size) { if (i == now.size - 1) items.add(BigInteger(now[i])) else items.add(BigInteger(now[i].substring(0, now[i].length - 1))) } node.items = items now = input[idx + 2].trim().split(" ") node.op = now[4] if (now[5] == "old") node.factor = -1 else node.factor = now[5].toLong() now = input[idx + 3].trim().split(" ") node.test = now[3].toLong() LCM = lcm(LCM, now[3].toLong()) now = input[idx + 4].trim().split(" ") node.trueId = now[5].toInt() now = input[idx + 5].trim().split(" ") node.falseId = now[5].toInt() monkey.add(node) idx += 7 } val cnt = LongArray(monkey.size) for (x in 0 until 10000) { for (i in monkey.indices) { cnt[i] += 1L * monkey[i].items.size for (item in monkey[i].items) { var old = item if (monkey[i].factor == -1L) old = next(monkey[i].op, old, old) else old = next(monkey[i].op, old, BigInteger("" + monkey[i].factor)) // old /= 3 old = old.mod(BigInteger("" + LCM)) val nextId: Int = if (old.mod(BigInteger("" + monkey[i].test)).toString() == "0") { monkey[i].trueId } else { monkey[i].falseId } monkey[nextId].items.add(old) } monkey[i].items.clear() } } for (i in cnt) print("$i ") println() cnt.sort() return cnt[monkey.size - 1] * cnt[monkey.size - 2] } val input = readInput("Day11") println(game(input)) }
0
Kotlin
0
0
70a4a52aa5164f541a8dd544c2e3231436410f4b
2,895
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dwt/Dwt23.kt
sssemil
268,084,789
false
null
package dwt import utils.Rational private val Int.isPrime: Boolean get() { if (this == 1) return false for (i in 2..this / 2) { if (this % i == 0) return false } return true } fun main() { // generate boxes val xs = (1..45).toList() val boxes = mutableListOf( xs.filter { it % 3 == 0 }, xs.filter { it % 3 != 0 && it % 2 == 0 }, xs.filter { it % 3 != 0 && it % 2 != 0 && it.isPrime } ) boxes.add(xs.minus(boxes.flatten())) // simulate random selection val simLt10Prob = play(boxes, 10_000_000L) { it < 10 }.simplify() val simPrimeProb = play(boxes, 10_000_000L) { it.isPrime }.simplify() val simLt10AndPrimeProb = play(boxes, 10_000_000L) { it < 10 && it.isPrime }.simplify() val simLt10CondPrimeProb = simLt10AndPrimeProb / simLt10Prob println("----------------------------------------------------------------------------------------------------") println("(simulated)\t\tPr[E] = $simLt10Prob = ${simLt10Prob.toDouble()}") println("(simulated)\t\tPr[F] = $simPrimeProb = ${simPrimeProb.toDouble()}") println("(simulated)\t\tPr[F and E] = $simLt10AndPrimeProb = ${simLt10AndPrimeProb.toDouble()}") println("(simulated)\t\tPr[F | E] = $simLt10CondPrimeProb = ${simLt10CondPrimeProb.toDouble()}") println("----------------------------------------------------------------------------------------------------") // build probabilities val partOfProbabilityPerBox = Rational(1, boxes.size.toLong()) val counts = boxes.flatMap { bxs -> val partOfProbabilityPerItemPerBox = partOfProbabilityPerBox / bxs.count() bxs.map { item -> Pair(item, partOfProbabilityPerItemPerBox) } } // sanity check counts.fold( Rational(0, 0), { acc, (_, pr) -> acc + pr }).let { sumTotal -> check(sumTotal.isOne) } val calcLt10Prob = calc(counts) { it < 10 }.simplify() val calcPrimeProb = calc(counts) { it.isPrime }.simplify() val calcLt10AndPrimeProb = calc(counts) { it < 10 && it.isPrime }.simplify() val calcLt10CondPrimeProb = calcLt10AndPrimeProb / calcLt10Prob println("----------------------------------------------------------------------------------------------------") println("(calculated)\tPr[E] = $calcLt10Prob = ${calcLt10Prob.toDouble()}") println("(calculated)\tPr[F] = $calcPrimeProb = ${calcPrimeProb.toDouble()}") println("(calculated)\tPr[F and E] = $calcLt10AndPrimeProb = ${calcLt10AndPrimeProb.toDouble()}") println("(calculated)\tPr[F | E] = $calcLt10CondPrimeProb = ${calcLt10CondPrimeProb.toDouble()}") println("----------------------------------------------------------------------------------------------------") } fun calc(counts: List<Pair<Int, Rational>>, condition: (Int) -> Boolean): Rational { return counts.fold( Rational(0, 0), { acc, (element, pr) -> if (condition(element)) { acc + pr } else { acc } }) } fun play(boxes: List<List<Int>>, totalCount: Long, condition: (Int) -> Boolean): Rational { var lt10Count = 0L for (i in 0 until totalCount) { boxes.random().let { box -> box.random().let { element -> if (condition(element)) { lt10Count++ } } } } return Rational(lt10Count, totalCount) }
0
Kotlin
0
0
02d951b90e0225bb1fa36f706b19deee827e0d89
3,509
math_playground
MIT License
src/Day03.kt
BenD10
572,786,132
false
{"Kotlin": 6791}
val prio by lazy { ('a'..'z') + ('A'..'Z') } fun Char.getPriority() = prio.indexOf(this) + 1 fun main() { fun part1(input: List<String>): Int { return input.map { it.chunked(it.length / 2) { it.map { it.getPriority() } } }.map { (it.first().toSet().intersect(it.last().toSet())) }.sumOf { it.sum() } } fun part2(input: List<String>): Int { return input.map { it.toSet() }.chunked(3).map { it[0].intersect(it[1].intersect(it[2])).map { it.getPriority() } }.sumOf { it.sum() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println(part1(testInput)) check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) check(part2(testInput) == 70) println(part2(input)) }
0
Kotlin
0
0
e26cd35ef64fcedc4c6e40b97a63d7c1332bb61f
909
advent-of-code
Apache License 2.0
src/aoc2023/Day01.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2023 import readInput import java.math.BigDecimal fun main() { fun part1(input: List<String>): BigDecimal { var sum = BigDecimal.ZERO for (line in input) { sum = sum.add((10 * line.find { it.isDigit() }?.digitToInt()!!).toBigDecimal()) sum = sum.add(line.findLast { it.isDigit() }?.digitToInt()?.toBigDecimal()) } return sum } fun part2(input: List<String>): Long { val digits = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val digitValues = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) var sum = 0L for (line in input) { val (indexChars, valueChars) = line.findAnyOf(digits) ?: Pair(input.size + 1, 0) val indexDigit = line.indexOfFirst { it.isDigit() } if (indexDigit < indexChars) { sum += 10 * (line[indexDigit].digitToInt()) } else { sum += 10 * (digitValues[valueChars]!!) } val (indexCharsLast, valueCharsLast) = line.findLastAnyOf(digits) ?: Pair(-1, 0) val indexDigitLast = line.indexOfLast { it.isDigit() } if (indexDigitLast > indexCharsLast) { sum += line[indexDigitLast].digitToInt() } else { sum += digitValues[valueCharsLast]!! } } return sum } println(part1(readInput("aoc2023/Day01"))) println(part2(readInput("aoc2023/Day01"))) }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
1,707
advent-of-code-kotlin
Apache License 2.0
src/Day05.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
// Advent of Code 2022, Day 05, Supply Stacks fun main() { data class Day05(val stacks: MutableList<ArrayDeque<Char>>, val moves: List<List<Int>>) fun part1(input: Day05): String { val stacks = input.stacks val moves = input.moves moves.forEach { for (i in 1..it[0]) { val c = stacks[it[1]].removeLast() stacks[it[2]].add(c) } } return stacks.fold("") { acc, next -> acc + next.last() } } fun part2(input: Day05): String { val stacks = input.stacks val moves = input.moves moves.forEach { val all = mutableListOf<Char>() for (i in 1..it[0]) { val c = stacks[it[1]].removeLast() all.add(0, c) } stacks[it[2]].addAll(all) } return stacks.fold("") { acc, next -> acc + next.last() } } fun parse(input: List<String>) : Day05 { // get size var size = 0 run size@ { input.forEach { if (!it.contains("[")) { val indicies = it.trim().split("\\s+".toRegex()) size = indicies.last().toInt() return@size } } } //println("size is $size") val stacks = MutableList(size) {ArrayDeque<Char>()} val moves = mutableListOf<List<Int>>() run moveStart@ { input.forEach { if (it.contains("[")) { var i = 0 var stackIdx = 0 while (i < it.lastIndex) { if (it[i] == '[') { stacks[stackIdx].addFirst(it[i+1]) } i+= 4 stackIdx++ } return@forEach // continue } else if (it.contains("move")) { val move = it.trim().split("move ", " from ", " to ") // subtract 1 for 0-based indices moves.add(listOf(move[1].toInt(), move[2].toInt()-1, move[3].toInt()-1)) //println(moves) } } } //println(stacks) return Day05(stacks, moves) } var parsedTestInput = parse(readInput("Day05_test")) //println(parsedTestInput) check(part1(parsedTestInput) == "CMZ") parsedTestInput = parse(readInput("Day05_test")) // reset mutable parsed input check(part2(parsedTestInput) == "MCD") var input = parse(readInput("Day05")) println(part1(input)) input = parse(readInput("Day05")) println(part2(input)) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
2,723
AdventOfCode2022
Apache License 2.0
src/Day4.kt
syncd010
324,790,559
false
null
class Day4 : Day { private fun convert(input: List<String>): Pair<Int, Int> { val split = input[0].split("-") return Pair(split[0].toInt(), split[1].toInt()) } private fun countPasswords(minVal: Int, maxVal: Int, sequenceRule: (List<Int>) -> Boolean): Int { val digits = minVal.toDigits() var count = 0 // Rule: The value is within the range given in your puzzle input while (digitsToNum(digits) <= maxVal) { // Rules: Sorted and sequence Rule as provided if (digits.isSorted() && sequenceRule(digits)) count++ // Move to next possible number val idx = digits.indexOfLast { it != 9 } digits[idx]++ digits.subList(idx + 1, digits.size).fill(digits[idx]) } return count } override fun solvePartOne(input: List<String>): Int { val (minVal, maxVal) = convert(input) // Rule: Two adjacent digits are the same return countPasswords(minVal, maxVal) { it.zipWithNext { a, b -> a == b }.any { it } } } override fun solvePartTwo(input: List<String>): Int { val (minVal, maxVal) = convert(input) // Rule: Two adjacent digits are the same and the two adjacent matching digits are not part of a larger group of matching digits return countPasswords(minVal, maxVal) { val diff = it.zipWithNext { a, b -> a == b } for ((idx, b) in diff.withIndex()) { if (b && ((idx == 0) || !diff[idx - 1]) && ((idx == diff.size - 1) || !diff[idx + 1])) { return@countPasswords true } } false } } }
0
Kotlin
0
0
11c7c7d6ccd2488186dfc7841078d9db66beb01a
1,757
AoC2019
Apache License 2.0
jvm/src/main/kotlin/io/prfxn/aoc2021/day11.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Dumbo Octopus (https://adventofcode.com/2021/day/11) package io.prfxn.aoc2021 fun main() { val lines = textResourceReader("input/11.txt").readLines().map { it.map(Char::digitToInt) } fun process( grid: Array<IntArray>, cells: List<Pair<Int, Int>>, flashed: MutableSet<Pair<Int, Int>> = mutableSetOf() ): MutableSet<Pair<Int, Int>> { cells.onEach { (r, c) -> grid[r][c]++ } .asSequence() .filter { (r, c) -> grid[r][c] > 9 && r to c !in flashed } .forEach { (r, c) -> grid[r][c] = 0 flashed.add(r to c) val affectedCells = (r-1..r+1).flatMap { nr -> (c-1..c+1).map { nc -> nr to nc } } .filter { (nr, nc) -> nr in grid.indices && nc in grid[0].indices && !(nr == r && nc == c) && nr to nc !in flashed } if (affectedCells.isNotEmpty()) process(grid, affectedCells, flashed) } return flashed } fun doStep(grid: Array<IntArray>) = process(grid, grid.indices.flatMap { r -> grid[0].indices.map { c -> r to c } }) fun getGrid() = lines.map { it.toIntArray() }.toTypedArray() val answer1 = getGrid().let { grid -> generateSequence { doStep(grid) } .take(100) .fold(0) { sum, flashed -> sum + flashed.size } } val answer2 = getGrid().let { grid -> val gridSize = grid.size * grid[0].size generateSequence { doStep(grid) } .withIndex() .find { it.value.size == gridSize }!! .index + 1 } sequenceOf(answer1, answer2).forEach(::println) } /** output * 1655 * 337 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,872
aoc2021
MIT License
src/Day03.kt
paulbonugli
574,065,510
false
{"Kotlin": 13681}
fun main() { fun determinePriority(c : Char) : Int { return if (c > 'Z') { c - 'a' + 1 } else { c - 'A' + 26 + 1 } } fun part1(input : List<String>) : Int { return input.map { line -> val c1 = line.subSequence(0, line.length / 2) val c2 = line.subSequence((line.length / 2), line.length) c1 to c2 }.map { (first, second) -> first.asIterable().first(second::contains) }.sumOf { determinePriority(it) } } fun part2(input : List<String>) : Int { return input.chunked(3).flatMap { group -> group.map{ it.toSet() }.reduce{ left, right -> left intersect right} }.sumOf { determinePriority(it) } } val lines = readInput("Day03") println("Part 1: " + part1(lines)) println("Part 2: " + part2(lines)) }
0
Kotlin
0
0
d2d7952c75001632da6fd95b8463a1d8e5c34880
881
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch8/Problem89.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch8 /** * Problem 89: Roman Numerals * * https://projecteuler.net/problem=89 * * Goal: Given a string of Roman number symbols, output a valid (or more efficient) Roman number * that represents it, by following the rules below. * * Constraints: 1 <= length of input string <= 1000 * * Roman Numerals: {I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000} * * Roman numbers are written in descending order of symbols to be added, with the appearance of a * symbol with lesser value before another symbol implying subtraction. This is why 14 is written * as XIV, not IVX. * * Notably, M is the only symbol that can appear more than 3 times in a row. This is why 9 is * written as IX and not VIII. Also, V, L, and D will not appear more than once. * * Subtraction Rules: * - I can only be subtracted from V and X. * - X can only be subtracted from L and C. * - C can only be subtracted from D and M. * - V, L, D, and M cannot be subtracted from another symbol. * - Only one I, X, and C can be used as the leading numeral in part of a subtractive pair. * e.g. 999 is written as CMXCIX, not IM. * * e.g.: input = "IIIII" * output = "V" * input = "VVVVVVVVV" * output = "XLV" */ class RomanNumerals { private val romanSymbols = mapOf( "M" to 1000, "CM" to 900, "D" to 500, "CD" to 400, "C" to 100, "XC" to 90, "L" to 50, "XL" to 40, "X" to 10, "IX" to 9, "V" to 5, "IV" to 4, "I" to 1 ) fun getRomanNumber(input: String) = parseInput(input).toRomanNumber() /** * Creates an integer from a string representation of a Roman Number by iterating through * every character and looking forward to see if the appropriate value must be added or * subtracted. * * This could be solved in the opposite way that Int.toRomanNumber() works, by iterating * through an alternative map sorted from the lowest value to highest (but with subtractive * pairs first). Every symbol could be removed from the original string & resulting lengths * compared to create an incrementing numerical value. */ private fun parseInput(input: String): Int { var value = 0 for ((i, ch) in input.withIndex()) { val current = romanSymbols.getOrDefault(ch.toString(), 0) value = if (i == input.lastIndex) { value + current } else { val next = romanSymbols.getOrDefault(input[i+1].toString(), 0) if (next <= current) { value + current } else { value - current } } } return value } /** * Creates a Roman Number by repeatedly dividing out all mapped symbols from the original * number. */ private fun Int.toRomanNumber(): String { val romanNumeral = StringBuilder() var num = this for ((symbol, value) in romanSymbols) { if (num == 0 || symbol == "I") break romanNumeral.append(symbol.repeat(num / value)) num %= value } romanNumeral.append("I".repeat(num)) return romanNumeral.toString() } /** * Project Euler specific implementation that returns the number of characters saved by * writing all 1000 input strings in their more efficient minimal form. * * Note that test resource input strings are not guaranteed to have symbols in descending * value order. */ fun romanCharsSaved(inputs: List<String>): Int { return inputs.sumOf { input -> // this should never be a negative value input.length - getRomanNumber(input).length } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
3,770
project-euler-kotlin
MIT License
src/Day19/Day19.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
import kotlin.math.absoluteValue fun Triple<Int, Int, Int>.get(i: Int): Int = when (i) { 0 -> this.first 1 -> this.second 2 -> this.third else -> throw IllegalArgumentException(i.toString()) } fun Triple<Int, Int, Int>.rotate(d: Int): Triple<Int, Int, Int> { val c0 = d % 3 val c0s = 1 - ((d / 3) % 2) * 2 val c1 = (c0 + 1 + (d / 6) % 2) % 3 val c1s = 1 - (d / 12) * 2 val c2 = 3 - c0 - c1 val c2s = c0s * c1s * (if (c1 == (c0 + 1) % 3) 1 else -1) return Triple(get(c0) * c0s, get(c1) * c1s, get(c2) * c2s) } fun Triple<Int, Int, Int>.shift(offset: Triple<Int, Int, Int>) = Triple(first - offset.first, second - offset.second, third - offset.third) fun minus(e1: Triple<Int, Int, Int>, e2: Triple<Int, Int, Int>): Triple<Int, Int, Int> = Triple(e1.first - e2.first, e1.second - e2.second, e1.third - e2.third) fun Triple<Int, Int, Int>.abs() = Triple(first.absoluteValue, second.absoluteValue, third.absoluteValue) fun Triple<Int, Int, Int>.sum() = first + second + third fun intersect( e1: List<Triple<Int, Int, Int>>, e2: List<Triple<Int, Int, Int>> ): Pair<List<Triple<Int, Int, Int>>, Triple<Int, Int, Int>>? { for (d in 0 until 24) { val rotated = e2.map { it.rotate(d) } for (x1 in e1) { for (x2 in rotated) { val dist = minus(x2, x1) val shifted = rotated.map { it.shift(dist) } if (e1.toSet().intersect(shifted.toSet()).size >= 12) { return Pair(shifted, Triple(0, 0, 0).rotate(d).shift(dist)) } } } } return null } fun main() { fun preprocess(input: List<String>): MutableList<List<Triple<Int, Int, Int>>> { val res = mutableListOf<List<Triple<Int, Int, Int>>>() var current = mutableListOf<Triple<Int, Int, Int>>() var i = 0 while (input.size > i) { if (input[i].startsWith("---")) { if (current.isNotEmpty()) { res.add(current) current = mutableListOf() } } else if (input[i] != "") { val split = input[i].split(",").map { it.toInt() } current.add(Triple(split[0], split[1], split[2])) } i++ } if (current.isNotEmpty()) { res.add(current) } return res } fun calc(input: MutableList<List<Triple<Int, Int, Int>>>): Pair<Int, Int> { val foundPos = HashSet<Triple<Int, Int, Int>>() val foundSets = mutableSetOf(0) val remaining = (1 until input.size).toMutableSet() val scannerPos = ArrayList(Array<Triple<Int, Int, Int>?>(input.size) { null }.toList()) foundPos.addAll(input[0]) scannerPos[0] = Triple(0, 0, 0) while (remaining.isNotEmpty()) { outer@ for (e1 in remaining) { for (e2 in foundSets) { val newPos = intersect(input[e2], input[e1]) if (newPos != null) { input[e1] = newPos.first foundPos.addAll(newPos.first) remaining.remove(e1) foundSets.add(e1) scannerPos[e1] = newPos.second println("found: $foundSets") println("remaining: $remaining") println() break@outer } } } } val scannerPosNotNull = scannerPos.filterNotNull() var max = -1 for (e1 in scannerPosNotNull) { for (e2 in scannerPosNotNull) { val manhattanDist = minus(e1, e2).abs().sum() if (manhattanDist > max) { max = manhattanDist } } } return Pair(foundPos.size, max) } val testInput = preprocess(readInput(19, true)) val input = preprocess(readInput(19)) val testResult = calc(testInput) check(testResult.first == 79) check(testResult.second == 3621) val result = calc(input) println(result.first) println(result.second) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
4,232
advent-of-code-2021
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day15.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.Point import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import kotlin.math.abs /** * [Day 15: Beacon Exclusion Zone](https://adventofcode.com/2022/day/15). */ object Day15 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day15") println("Part One: ${part1(input, 2000000)}") println("Part Two: ${part2(input, 4000000)}") } } fun part1(input: List<String>, row: Int): Int { val sensors = Sensors(input) val minColumn = sensors.sensorMap.values.map { it.minColumnCovered(row) }.minOf { it.x } val maxColumn = sensors.sensorMap.values.map { it.maxColumnCovered(row) }.maxOf { it.x } var currentCell = Point(minColumn, row) var count = 0 while (currentCell.x <= maxColumn) { val coveredBySensor = sensors.coveredBySensor(currentCell) if (coveredBySensor != null) { val maxColumnCovered = coveredBySensor.maxColumnCovered(currentCell.y) count += maxColumnCovered.x - currentCell.x + 1 count -= sensors.sensorsOnRow(currentCell.y, currentCell.x, maxColumnCovered.x).size count -= sensors.beaconsOnRow(currentCell.y, currentCell.x, maxColumnCovered.x).size currentCell = maxColumnCovered } currentCell = Point((currentCell.x + 1), currentCell.y) } return count } fun part2(input: List<String>, maxCoordinate: Int): Long { val notCoveredCell = checkNotNull(notCoveredCell(input, maxCoordinate)) return notCoveredCell.x.toLong() * 4000000 + notCoveredCell.y.toLong() } class Sensor(val point: Point, val beacon: Point) { private val beaconDistance: Int by lazy { point.distanceTo(beacon) } private fun distanceTo(cell: Point) = point.distanceTo(cell) fun covers(cell: Point) = beaconDistance >= distanceTo(cell) fun maxColumnCovered(row: Int) = Point(point.x + abs(beaconDistance - abs(row - point.y)), row) fun minColumnCovered(row: Int) = Point(point.x - abs(beaconDistance - abs(row - point.y)), row) } class Sensors(input: List<String>) { private val beacons: Set<Point> val sensorMap: Map<Point, Sensor> fun sensorsOnRow(row: Int, minColumn: Int, maxColumn: Int) = sensorMap.values.filter { it.point.y == row && it.point.x >= minColumn && it.point.x <= maxColumn } fun beaconsOnRow(row: Int, minColumn: Int, maxColumn: Int) = beacons.filter { it.y == row && it.x >= minColumn && it.x <= maxColumn } init { val regex = "-?\\d+".toRegex() sensorMap = input.map { line -> regex.findAll(line).map { it.value.toInt() }.toList() } .map { Sensor(Point(it[0], it[1]), Point(it[2], it[3])) }.associateBy { it.point } beacons = sensorMap.values.map { it.beacon }.toSet() } fun coveredBySensor(cell: Point) = sensorMap.values.find { it.covers(cell) } } private fun notCoveredCell(input: List<String>, maxCoordinate: Int): Point? { val sensors = Sensors(input) (0..maxCoordinate).forEach { row -> var currentCell = Point(0, row) while (currentCell.x <= maxCoordinate) { val coveredBySensor = sensors.coveredBySensor(currentCell) if (coveredBySensor != null) { val cell = coveredBySensor.maxColumnCovered(currentCell.y) currentCell = Point((cell.x + 1), cell.y) } else return currentCell } } return null } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,794
advent-of-code
MIT License
src/Day07.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
fun main() { data class Node(val name: String, val size: Int, val leafs: List<Node>) val cdPattern = Regex("\\$ cd ([/\\w]+)") val filePattern = Regex("(\\d+) .*") val exitPattern = Regex("\\$ cd \\.\\.") var matchingDirSum = 0 fun enter(iterator: Iterator<String>): Int { var currentDirSum = 0 iterator.next() // ignore ls command while (iterator.hasNext()) { val it = iterator.next() when { cdPattern.matches(it) -> { val subdirSize = enter(iterator) currentDirSum += subdirSize } exitPattern.matches(it) -> { if (currentDirSum <= 100000) matchingDirSum += currentDirSum return currentDirSum } filePattern.matches(it) -> { val (fileSize) = filePattern.find(it)!!.destructured currentDirSum += fileSize.toInt() } } } return currentDirSum } fun part1(input: List<String>): Int { matchingDirSum = 0 val iterator = input.iterator() iterator.next() // ignore first cd command enter(iterator) return matchingDirSum } fun build(command: String, iterator: Iterator<String>): Node { val (dirname) = cdPattern.find(command)!!.destructured val leafs = mutableListOf<Node>() var size = 0 iterator.next() // ignore ls command while (iterator.hasNext()) { val it = iterator.next() when { cdPattern.matches(it) -> { val node = build(it, iterator) size += node.size leafs.add(node) } exitPattern.matches(it) -> { break } filePattern.matches(it) -> { val (fileSize) = filePattern.find(it)!!.destructured size += fileSize.toInt() } } } return Node(dirname, size, leafs) } fun dfs(node: Node, necessarySpace: Int): Node { return node.leafs.filter { it.size >= necessarySpace }.map { dfs(it, necessarySpace) }.minByOrNull { it.size } ?: node } fun part2(input: List<String>): Int { val iterator = input.iterator() val command = iterator.next() val root = build(command, iterator) val necessarySpace = 30000000 - (70000000 - root.size) return dfs(root, necessarySpace).size } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day07_test") check(part1(testInput) == 95437) val input = readInput("resources/Day07") println(part1(input)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
2,981
advent_of_code_2022
Apache License 2.0
src/day20/Day20.kt
spyroid
433,555,350
false
null
package day20 import readInput import kotlin.system.measureTimeMillis data class Pixel(val x: Int, val y: Int, var color: Int) data class Image(val width: Int, val height: Int, val bgColor: Int, val algo: List<Int>, val pixels: List<Pixel>) { companion object { private fun mapPixel(ch: Char) = if (ch == '#') 1 else 0 fun of(input: List<String>): Image { val algo = input.first().map { mapPixel(it) }.toList() val pixels = mutableListOf<Pixel>() .apply { input.drop(2).forEachIndexed { y, line -> line.forEachIndexed { x, v -> add(Pixel(x, y, mapPixel(v))) } } } return Image(input.drop(2).first().length, input.size - 2, 0, algo, pixels) } } private fun at(x: Int, y: Int): Pixel? { if (x < 0 || x >= width || y < 0) return null return pixels.getOrNull(x + width * y) } private fun matrix(x: Int, y: Int) = listOf( at(x - 1, y - 1), at(x, y - 1), at(x + 1, y - 1), at(x - 1, y), at(x, y), at(x + 1, y), at(x - 1, y + 1), at(x, y + 1), at(x + 1, y + 1), ) private fun clone(): Image { val bgColor = if (bgColor == 0) algo.first() else algo.last() val pixels = mutableListOf<Pixel>() .apply { (0 until height + 2).forEach { y -> (0 until width + 2).forEach { x -> add(Pixel(x, y, 0)) } } } return Image(width + 2, height + 2, bgColor, algo, pixels) } private fun colorAt(x: Int, y: Int) = matrix(x, y) .map { it?.color ?: bgColor } .joinToString("") .toInt(2) .let { algo[it] } fun enhance() = clone() .also { it.pixels.onEach { p -> p.color = colorAt(p.x - 1, p.y - 1) } } fun litPixels() = pixels.filter { it.color == 1 } } fun solve(input: List<String>, iterations: Int) = generateSequence(Image.of(input)) { it.enhance() } .drop(iterations) .first() .litPixels() .count() fun main() { val testData = readInput("day20/test") val inputData = readInput("day20/input") var res1 = solve(testData, 2) check(res1 == 35) { "Expected 35 but got $res1" } measureTimeMillis { res1 = solve(inputData, 2) } .also { time -> println("⭐️ Part1: $res1 in $time ms") } measureTimeMillis { res1 = solve(inputData, 50) } .also { time -> println("⭐️ Part2: $res1 in $time ms") } }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
2,485
Advent-of-Code-2021
Apache License 2.0
src/Day03.kt
uberbinge
572,972,800
false
{"Kotlin": 7404}
val input = readInput("Day03").split("\n") fun main() { part1() part2() } fun part1() { input.map { val first = it.substring(0, it.length / 2) val second = it.substring(it.length / 2) (first intersect second).single() }.sumOf { it.score() }.also { check(8202 == it) } } fun part2() { input.chunked(3) { val (a, b, c) = it (a intersect b intersect c).single() }.sumOf { it.score() }.also { check(2864 == it) } } private fun Char.score(): Int { return when (this) { in 'a'..'z' -> this - 'a' + 1 in 'A'..'Z' -> this - 'A' + 27 else -> error("Invalid character") } } infix fun String.intersect(other: String): Set<Char> = toSet() intersect other.toSet() infix fun Set<Char>.intersect(other: String): Set<Char> = this intersect other.toSet()
0
Kotlin
0
0
ef57861156ac4c1a097fabe03322edcfa4d2d714
840
aoc-2022-kotlin
Apache License 2.0
src/main/java/io/github/lunarwatcher/aoc/day11/Day11.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day11 import io.github.lunarwatcher.aoc.commons.Vector2i import io.github.lunarwatcher.aoc.commons.readFile import java.util.* data class ElevenPart2(val coords: Vector2i, val size: Int, val sum: Int) private fun parseData(serialNumber: Int) : SortedMap<Vector2i, Int>{ val powerLevels = mutableMapOf< Vector2i, Int>() for (x in 1..300){ for (y in 1..300){ val rackId = x + 10; val powerLevelStr = (((rackId * y) + serialNumber) * rackId).toString() val powerLevel = powerLevelStr[powerLevelStr.length - 3].toString().toInt() - 5 powerLevels[Vector2i(x, y)] = powerLevel } } return powerLevels.toSortedMap(compareBy({it.x}, {it.y})) } fun day11part1processor(serialNumber: Int) : Pair<Int, Int>{ val sortedMap = parseData(serialNumber); val powerLevelsSummed = mutableMapOf<Int, Pair<Int, Int>>() for(x in 2..299){ for(y in 2..299){ val area = mutableListOf<Int>() for(i in -1..1){ for(j in -1..1){ area.add(sortedMap[Vector2i(x + i, y + j)]!!) } } powerLevelsSummed[area.sum()] = x - 1 to y - 1 } } // Sorted = descending val finalSortedMap = powerLevelsSummed.toSortedMap() return finalSortedMap[finalSortedMap.lastKey()]!! } fun day11part2processor(serialNumber: Int) : ElevenPart2 { val sortedMap = parseData(serialNumber); var highest = ElevenPart2(Vector2i(0, 0), 0, 0) // It's unrealistic for t to be 1 or > 20, especially considering the sizes of part 1 for(size in 2..20){ var highestArea = 0 var coords = Vector2i(0, 0) for(x in 1..(300 - size)){ for(y in 1..(300 - size)){ var area: Int = 0 for(i in 0 until size){ for(j in 0 until size){ area += sortedMap[Vector2i(x + i, y + j)]!! } } if(area > highestArea){ highestArea = area; coords = Vector2i(x, y) } } } if(highestArea > highest.sum){ highest = ElevenPart2(coords, size, highestArea) } } return highest; } fun day11(part: Boolean){ val data = readFile("day11.txt").first().toInt() println(if(!part) day11part1processor(data) else day11part2processor(data)) }
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
2,503
AoC-2018
MIT License
src/main/kotlin/solutions/day12/Day12.kt
Dr-Horv
112,381,975
false
null
package solutions.day12 import solutions.Solver data class Node(val id: Int, val neighbours: MutableSet<Node>) { override fun hashCode(): Int { return id.hashCode() } override fun equals(other: Any?): Boolean { return when(other) { is Node -> id == other.id else -> false } } } class Day12: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val nodes = mutableMapOf<Int, Node>() buildGraphs(input, nodes) val nodesConnected = traverse(nodes.getValue(0)) if(!partTwo) { return nodesConnected.size.toString() } val groups = mutableListOf(nodesConnected) var lonelyNode = findUnconnectedNode(nodes, groups) while (lonelyNode != null) { val newGroup = traverse(lonelyNode) groups.add(newGroup) lonelyNode = findUnconnectedNode(nodes, groups) } return groups.size.toString() } private fun findUnconnectedNode(nodes: Map<Int, Node>, groups: List<Set<Node>>): Node? { return nodes.values.firstOrNull { n -> groups.none { g -> g.contains(n) } } } private fun buildGraphs(input: List<String>, nodes: MutableMap<Int, Node>) { input.map { it.split("<->") } .forEach { val id = it[0].trim().toInt() val neighbours = it[1].split(",").map(String::trim).map(String::toInt) val node = nodes.computeIfAbsent( id, { nodeId -> Node(nodeId, mutableSetOf()) } ) connect(node, neighbours, nodes) } } private fun traverse(value: Node, nodes: MutableSet<Node> = mutableSetOf()): Set<Node> { nodes.add(value) value.neighbours .filter { !nodes.contains(it) } .forEach { traverse(it, nodes) } return nodes } private fun connect(node: Node, neighbours: List<Int>, nodes: MutableMap<Int, Node>) { neighbours.forEach { val neighbourNode = nodes.computeIfAbsent( it, {id -> Node(id, mutableSetOf()) } ) node.neighbours.add(neighbourNode) neighbourNode.neighbours.add(node) } } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
2,408
Advent-of-Code-2017
MIT License
src/Day13.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { fun getNumber(list: MutableList<Char>): Int? { if (!list[0].isDigit()) { return null } if (list[1].isDigit()) { val number = "" + list[0] + list[1] return number.toInt() } return list[0].digitToInt() } fun bracket(array: MutableList<Char>) { var closing = 1 if (array[1].isDigit()) { closing++ } array.add(closing, ']') array.add(0, '[') } fun isInOrder(first: MutableList<Char>, second: MutableList<Char>): Boolean { val firstNumber = getNumber(first) val secondNumber = getNumber(second) if (firstNumber != null && secondNumber != null) { if (firstNumber < secondNumber) return true if (firstNumber > secondNumber) return false } if (firstNumber != null && second[0] == '[') { bracket(first) } if (first[0] == '[' && secondNumber != null) { bracket(second) } return when { first[0] == ']' && second[0] != ']' -> true first[0] != ']' && second[0] == ']' -> false else -> isInOrder(first.subList(1, first.size), second.subList(1, second.size)) } } fun part1(input: List<String>): Int { var answer = 0 var i = 0 while (i < input.size) { if (isInOrder(input[i].toMutableList(), input[i + 1].toMutableList())) { answer += (i / 3 + 1) } i += 3 } return answer } fun part2(input: List<String>): Int { val compare: (String, String) -> Int = { a: String, b: String -> Int if (isInOrder(a.toMutableList(), b.toMutableList())) -1 else 1 } val newInput = input.toMutableList() while (newInput.remove("")) { } newInput.add("[[2]]") newInput.add("[[6]]") newInput.sortWith(compare) return (newInput.indexOf("[[2]]") + 1) * (newInput.indexOf("[[6]]") + 1) } val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
2,287
advent-of-code-2022
Apache License 2.0
src/Day07.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
import kotlin.math.min private fun root(): Node { val root = Node() var cur = root readInput("Day07").forEach { cmd -> if (cmd.startsWith("$")) { val cmdS = cmd.split(" ") if (cmdS[1] == "cd") { cur = when (cmdS[2]) { "/" -> root ".." -> cur.parent else -> cur.children[cmdS[2]]!! } } } else { val (size, name) = cmd.split(" ") if (size == "dir") { cur.children.putIfAbsent(name, Node(name, cur)) } else { cur.children[name] = Node(name, size.toInt(), cur) } } } return root } private fun traverseDirSizes(node: Node, acceptDirSize: (Long) -> Unit = {}): Long { return if (node.dir) { val dirSize = node.children.map { traverseDirSizes(it.value, acceptDirSize) }.sum() acceptDirSize(dirSize) dirSize } else { node.size.toLong() } } private fun part1(root: Node): Long { val threshold = 100000L var dirsSum = 0L traverseDirSizes(root) { dirSize -> if (dirSize <= threshold) { dirsSum += dirSize } } return dirsSum } private fun part2(root: Node): Long { val threshold = traverseDirSizes(root) - 40000000 var minDirSize = Long.MAX_VALUE traverseDirSizes(root) { dirSize -> if (dirSize >= threshold) { minDirSize = min(minDirSize, dirSize) } } return minDirSize } fun main() { println(part1(root())) println(part2(root())) } data class Node( val dir: Boolean, val size: Int = 0, val name: String, val children: HashMap<String, Node> = HashMap() ) { var parent: Node = this // create dir constructor(dirName: String, parent: Node) : this(dir = true, name = dirName) { this.parent = parent } // create file constructor(filename: String, size: Int, parent: Node) : this(dir = false, name = filename, size = size) { this.parent = parent } // create root constructor() : this(dir = true, name = "/") }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
2,173
advent-of-code-2022
Apache License 2.0
src/Day01.kt
Totwart123
573,119,178
false
null
fun main() { fun getCalsByElves(input: List<String>): List<Int> { var numberInput = input.map { if (it.isEmpty()) -1 else it.toInt() }.toList() val emptyLines = numberInput.mapIndexed { index, i -> if (i == -1) index + 1 else -1 }.filter { it != -1 }.toMutableList().dropLast(0).reversed().toMutableList() emptyLines.add(0) val resultSet = emptyLines.map { val result = numberInput.takeLast(numberInput.size - it).sum() numberInput = numberInput.dropLast(numberInput.size - it).dropLast(1) result }.toList() return resultSet } fun part1(input: List<String>): Int { return getCalsByElves(input).max() } fun part2(input: List<String>): Int { return getCalsByElves(input).sortedDescending().take(3).sum() } check(part1(readInput("Day01_test")) == 24000) println(part1(readInput("Day01_test"))) println(part1(readInput("Day01"))) check(part2(readInput("Day01_test")) == 45000) println(part2(readInput("Day01_test"))) println(part2(readInput("Day01"))) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
1,107
AoC
Apache License 2.0
src/Day11.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
import kotlin.math.floor import kotlin.math.pow class Round(list: List<Monkey>) { private val lookup: Map<Int, Monkey> private val sharedModulus: Int var adjust = true init { lookup = list.associateBy { it.id } sharedModulus = lookup.values.map { it.modulus }.reduce { res, mod -> res * mod } } fun execute(times: Int): Long { for (i in 1..times) { for (monkey in lookup.values) { for (item in monkey.items) { val passTo = monkey.execute(item, adjust) item.worry = item.worry % sharedModulus lookup[passTo]!!.items.add(item) } monkey.items.removeAll(monkey.items) } } return result } private val result: Long get() { val result = lookup.values.map { it.inspections }.sortedDescending() return result[0] * result[1] } } class Monkey(val id: Int, val items: MutableList<Item>, private val operation: Char, private val operationAmount: Int, val modulus: Int, private val monkeyIdTrueCase: Int, private val monkeyIdFalseCase: Int) { var inspections = 0L fun execute(item: Item, adjust: Boolean): Int { inspections ++ operate(item) if (adjust) { item.adjust() } return passTo(test(item)) } private fun operate(item: Item) { when (operation) { '*' -> item.worry = item.worry * operationAmount '+' -> item.worry = item.worry + operationAmount '^' -> item.worry = floor(item.worry.toDouble().pow(operationAmount)).toLong() } } private fun test(item: Item): Boolean { return item.worry % modulus == 0L } private fun passTo(testResult: Boolean): Int { return if (testResult) monkeyIdTrueCase else monkeyIdFalseCase } } class Item(var worry: Long) { fun adjust() { worry /= 3L } } fun main() { fun parse(input: String): List<Monkey> { val monkeysRaw = input.split("\n\n") val monkeys: MutableList<Monkey> = ArrayList() for (str in monkeysRaw) { val lines = str.split("\n") val id = Integer.parseInt(lines[0].replace("Monkey ", "").replace(":", "")) val items = lines[1].replace(Regex("\\s+Starting items:\\s+"), "").split(", ").map { Item(Integer.parseInt(it).toLong()) }.toMutableList() val operation: Char val operationAmount: Int val operationStringSplit = lines[2].replace(Regex("\\s+Operation: new = old\\s"), "").split(" ") if (operationStringSplit[1] == "old") { operation = '^' operationAmount = 2 } else { operation = operationStringSplit[0][0] operationAmount = Integer.parseInt(operationStringSplit[1]) } val modulus = Integer.parseInt(lines[3].replace(Regex("\\s+Test: divisible by\\s"), "")) val monkeyIdTrueCase = Integer.parseInt(lines[4].replace(Regex("\\s+If true: throw to monkey\\s"), "")) val monkeyIdFalseCase = Integer.parseInt(lines[5].replace(Regex("\\s+If false: throw to monkey\\s"), "")) val monkey = Monkey(id, items, operation, operationAmount, modulus, monkeyIdTrueCase, monkeyIdFalseCase) monkeys.add(monkey) } return monkeys } fun part1(input: String): Long { val round = Round(parse(input)) return round.execute(20) } fun part2(input: String): Long { val round = Round(parse(input)) round.adjust = false return round.execute(10000) } // test if implementation meets criteria from the description, like: val testInput = readChunk("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readChunk("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
4,097
2022-advent
Apache License 2.0
src/Day04.kt
tstellfe
575,291,176
false
{"Kotlin": 8536}
fun main() { fun String.toSections() = this.split(",").map { pair -> val sections = pair.split("-") sections[0].toInt()..sections[1].toInt() } fun IntRange.isIn(other: IntRange): Boolean { this.forEach { if (!other.contains(it)) return false } return true } fun IntRange.hasAtLeastOne(other: IntRange): Boolean { this.forEach { if (other.contains(it)) return true } return false } fun part1(input: List<String>): Int { return input.sumOf { line -> val sections = line.toSections() val a = sections[0].isIn(sections[1]) val b = sections[1].isIn(sections[0]) if(a or b) 1 as Int else 0 as Int } } fun part2(input: List<String>): Int { return input.sumOf { line -> val sections = line.toSections() val a = sections[0].hasAtLeastOne(sections[1]) val b = sections[1].hasAtLeastOne(sections[0]) if(a or b) 1 as Int else 0 as Int } } val testInput = readInput("Day04_test") val input = readInput("Day04") println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
e100ba705c8e2b83646b172d6407475c27f02eff
1,095
adventofcode-2022
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem5/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem5 /** * LeetCode page: [5. Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/description/); * * Note: There is a linear time complexity algorithm called Manacher's algorithm, see [Ref.](https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) */ class Solution { /* Complexity: * Time O(|s|^2) and Space O(1); */ fun longestPalindrome(s: String): String { var indicesOfLongestPalindrome = 0 until 0 for (index in s.indices) { val longestExpansion = findLongestPalindromeExpansion(index, s) if (longestExpansion.size() > indicesOfLongestPalindrome.size()) { indicesOfLongestPalindrome = longestExpansion } } return s.slice(indicesOfLongestPalindrome) } private fun findLongestPalindromeExpansion(seedIndex: Int, s: String): IntRange { /* Two cases should be considered: one for odd length palindrome (e.g. "b(a)b") and one for * even length palindrome(e.g. "ba(a)b"). */ val oddLongest = findLongestPalindromeExpansion(seedIndex, seedIndex, s) val evenLongest = findLongestPalindromeExpansion(seedIndex - 1, seedIndex, s) return if (oddLongest.size() > evenLongest.size()) oddLongest else evenLongest } private fun findLongestPalindromeExpansion(floorCenterIndex: Int, ceilingCenterIndex: Int, s: String): IntRange { var start = floorCenterIndex var end = ceilingCenterIndex while (start > -1 && end < s.length && s[start] == s[end]) { start-- end++ } val noValidExpansion = end == ceilingCenterIndex return if (noValidExpansion) end until end else start + 1 until end } private fun IntRange.size() = last - first + 1 }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,878
hj-leetcode-kotlin
Apache License 2.0
app/src/main/kotlin/advent/of/code/twentytwenty/Day2.kt
obarcelonap
320,300,753
false
null
package advent.of.code.twentytwenty fun main(args: Array<String>) { val lines = getResourceAsLines("/day2-input") val validPasswordsByOcurrencesRange = filterValidPasswords(lines, ::validatorByOccurrencesRange) println("Part 1: found ${validPasswordsByOcurrencesRange.size} valid passwords") val validPasswordsByUniqueIndexAssertion = filterValidPasswords(lines, ::validatorByUniqueIndexAssertion) println("Part 2: found ${validPasswordsByUniqueIndexAssertion.size} valid passwords") } fun filterValidPasswords(lines: Iterable<String>, policyValidator: (Policy) -> (Password) -> Boolean): List<Pair<Policy, Password>> { return lines.map { parsePolicyAndPassword(it) } .filter { (policy, password) -> policyValidator(policy)(password) } .toList() } data class Policy(val firstInt: Int, val secondInt: Int, val character: Char) data class Password(val value: String) fun parsePolicyAndPassword(line: String): Pair<Policy, Password> { val (policyTokens, passwordValue) = line.split(":") val (policyBoundaryTokens, character) = policyTokens.split(" ") val (lowerBound, upperBound) = policyBoundaryTokens.split("-") val policy = Policy(lowerBound.toInt(), upperBound.toInt(), character.single()) val password = Password(passwordValue.trim()) return Pair(policy, password) } fun validatorByOccurrencesRange(policy: Policy): (Password) -> Boolean { return fun(password: Password): Boolean { val (lowerBound, upperBound, character) = policy val occurrences = password.value.asIterable() .count { it == character } return occurrences in lowerBound..upperBound } } fun validatorByUniqueIndexAssertion(policy: Policy): (Password) -> Boolean { return fun(password: Password): Boolean { val (firstIndex, secondIndex, character) = policy val firstIndexChar = password.value[firstIndex - 1] val secondIndexChar = password.value[secondIndex - 1] return (firstIndexChar == character || secondIndexChar == character) && firstIndexChar != secondIndexChar } }
0
Kotlin
0
0
a721c8f26738fe31190911d96896f781afb795e1
2,124
advent-of-code-2020
MIT License
year2022/src@jvm/cz/veleto/aoc/year2022/Day19.kt
haluzpav
573,073,312
false
{"Kotlin": 164348}
package cz.veleto.aoc.year2022 import cz.veleto.aoc.core.AocDay class Day19(config: Config) : AocDay(config) { private val inputRegex = Regex( """ ^Blueprint ([0-9]+): Each ore robot costs ([0-9]+) ore. Each clay robot costs ([0-9]+) ore. Each obsidian robot costs ([0-9]+) ore and ([0-9]+) clay. Each geode robot costs ([0-9]+) ore and ([0-9]+) obsidian.$ """.trimIndent().replace("\n", " ") ) override fun part1(): String = parseBlueprints() .sumOf { it.id * calcMaxGeodes(it, minutes = 24, pruningSlope = 0.5) } .toString() override fun part2(): String = parseBlueprints() .take(3) .fold(1) { acc, blueprint -> acc * calcMaxGeodes(blueprint, minutes = 32, pruningSlope = 1.4) } .toString() fun parseBlueprints(): Sequence<Blueprint> = input.map { line -> val ints = inputRegex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() } Blueprint( id = ints[0], robots = listOf( Robot( produces = Resource.Ore, costs = listOf(ints[1], 0, 0, 0), ), Robot( produces = Resource.Clay, costs = listOf(ints[2], 0, 0, 0), ), Robot( produces = Resource.Obsidian, costs = listOf(ints[3], ints[4], 0, 0), ), Robot( produces = Resource.Geode, costs = listOf(ints[5], 0, ints[6], 0), ), ), ) } fun calcMaxGeodes(blueprint: Blueprint, minutes: Int, pruningSlope: Double): Int { check(blueprint.robots.size == Resource.entries.size) check(blueprint.robots.zip(Resource.entries) { robot, resource -> robot.produces == resource }.all { it }) val zeroResources = List(Resource.entries.size) { 0 } val startNode = Node( robotCounts = List(blueprint.robots.size) { if (it == 0) 1 else 0 }, resourceCounts = zeroResources, skippedRobots = emptySet(), performance = 0, // whatever ) val nodeComparator: (Node, Node) -> Int = { p0, p1 -> // effectively make the Set based only on Node.resourceCounts and Node.robotCounts sequence { for (i in Resource.entries.indices) yield(p0.resourceCounts[i].compareTo(p1.resourceCounts[i])) for (i in blueprint.robots.indices) yield(p0.robotCounts[i].compareTo(p1.robotCounts[i])) }.firstOrNull { it != 0 } ?: 0 } var leafNodes = sortedSetOf<Node>(nodeComparator, startNode) val maxResourcesForRobot = Resource.entries.map { resource -> when (resource) { Resource.Geode -> Int.MAX_VALUE else -> blueprint.robots.maxOf { it.costs[resource.ordinal] } } } var totalPruned = 0 for (minute in 1..minutes) { val minPerformanceCoefficient = (pruningSlope / minutes * minute).coerceIn(0.0..0.9) val maxPerformance = leafNodes.maxOf { it.performance } listOf( "blueprint ${blueprint.id}", "minute $minute", "leaf nodes ${leafNodes.size}", "lastMinuteMaxPerformance $maxPerformance", "minPerformanceCoefficient %.2f".format(minPerformanceCoefficient), ).joinToString().also { if (config.log) println(it) } val newLeafNodes = sortedSetOf<Node>(nodeComparator) for (node in leafNodes) { if (minute > 13 && node.performance < maxPerformance * minPerformanceCoefficient) { totalPruned++ continue } val newActions = if (minute < minutes) { val buildRobotActions = blueprint.robots .filterIndexed { index, robot -> index !in node.skippedRobots && node.robotCounts[index] < maxResourcesForRobot[robot.produces.ordinal] && haveEnoughQuantities(robot.costs, node.resourceCounts) } .map { FactoryAction.Build(it) } val skippedRobots = buildRobotActions.map { blueprint.robots.indexOf(it.robot) }.toSet() listOf(FactoryAction.Wait(skippedRobots)) + buildRobotActions } else { listOf(null) } newLeafNodes += newActions.map { action -> val resourceCounts = Resource.entries.mapIndexed { index, resource -> val robot = blueprint.robots[index] check(robot.produces == resource) val newRobotCosts = if (action is FactoryAction.Build) action.robot.costs else zeroResources node.resourceCounts[index] + node.robotCounts[index] - newRobotCosts[index] } val builtRobotIndex = (action as? FactoryAction.Build)?.robot?.let { blueprint.robots.indexOf(it) } val robotCounts = node.robotCounts.mapIndexed { index, count -> if (index == builtRobotIndex) count + 1 else count } val performance = calcPerformance(blueprint, minutes, minute, resourceCounts, robotCounts) val newSkippedRobots = if (action is FactoryAction.Wait) { node.skippedRobots + action.skippedRobots } else { emptySet() } Node( robotCounts = robotCounts, resourceCounts = resourceCounts, skippedRobots = newSkippedRobots, performance = performance, ) } } leafNodes = newLeafNodes } if (config.log) println("totalPruned $totalPruned") return leafNodes.maxOf { it.resourceCounts[3] } } private fun calcPerformance( blueprint: Blueprint, minutes: Int, minute: Int, resourceCounts: List<Int>, robotCounts: List<Int>, ): Int { val resourcesValue = Resource.entries.mapIndexed { i, resource -> resource.value * resourceCounts[i] }.sum() val robotsValue = blueprint.robots.mapIndexed { i, robot -> val robotCostValue = Resource.entries.mapIndexed { j, resource -> resource.value * robot.costs[j] }.sum() val robotPotentialResourcesValue = robot.produces.value * (minutes - minute) val robotIntrinsicValue = 5 + robot.produces.value val robotValue = robotCostValue + robotPotentialResourcesValue + robotIntrinsicValue robotValue * robotCounts[i] }.sum() return resourcesValue + robotsValue } private fun haveEnoughQuantities(costs: List<Int>, stock: List<Int>): Boolean = Resource.entries.indices.all { stock[it] >= costs[it] } private data class Node( val robotCounts: List<Int>, val resourceCounts: List<Int>, val skippedRobots: Set<Int>, val performance: Int, ) private sealed interface FactoryAction { data class Wait( val skippedRobots: Set<Int>, ) : FactoryAction data class Build( val robot: Robot, ) : FactoryAction } data class Blueprint( val id: Int, val robots: List<Robot>, ) data class Robot( val produces: Resource, val costs: List<Int>, ) enum class Resource(val value: Int) { Ore(1), Clay(2), Obsidian(4), Geode(8), } }
0
Kotlin
0
1
32003edb726f7736f881edc263a85a404be6a5f0
7,986
advent-of-pavel
Apache License 2.0
src/main/kotlin/dp/MaxSumRect.kt
yx-z
106,589,674
false
null
package dp import util.* /* Suppose you are given an array M[1..n, 1..n] of numbers, which may be positive, negative, or zero, and which are not necessarily integers. Describe an algorithm to find the largest sum of elements in any rectangular subarray of the form M[i..i', j..j']. Try to solve it in O(n^3) time */ fun OneArray<OneArray<Double>>.maxSumRect(): Double { val M = this val n = size // assuming M is n by n as the problem stated // dp(i, j): an array of column sums from row i to row j // where i, j in 1..n and defined only for j >= i val dp = OneArray(n) { OneArray(n) { OneArray(n) { 0.0 } } } // space: O(n^3) // dp(i, j) = M[i] if i = j // = dp(i, j - 1) + M[j] o/w // where we are using python-like array addition w/ broadcasting for (i in 1 until n) { for (j in i..n) { dp[i, j] = if (i == j) M[i].copy() else dp[i, j - 1] + M[j] } } // O(n^3) // now we do Kadane's Algorithm as in MaxSum and kep track of the max var max = 0.0 for (i in 1 until n) { for (j in i..n) { val currMax = dp[i, j].maxSum() max = max(max, currMax) } } // O(n^3) return max } operator fun OneArray<Double>.plus(that: OneArray<Double>) = indices.map { this[it] + that[it] }.toOneArray() fun OneArray<Double>.maxSum(): Double { var maxEndingHere = 0.0 var maxSoFar = 0.0 forEach { maxEndingHere += it maxEndingHere = max(maxEndingHere, 0.0) maxSoFar = max(maxSoFar, maxEndingHere) } return maxSoFar } fun main(args: Array<String>) { val M = oneArrayOf( oneArrayOf(1.0, 3.0, -1.0, 0.5), oneArrayOf(2.5, -2.5, 1.5, 0.25), oneArrayOf(1.5, -2.0, 2.5, 3.5), oneArrayOf(3.5, 2.0, -1.5, 2.0)) println(M.maxSumRect()) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,707
AlgoKt
MIT License
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day11/Day11.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2022.day11 import nerok.aoc.utils.Input import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun operateOnItem(item: ULong, operation: String): ULong { val (first, operator, last) = operation .trim() .removePrefix("new = ") .replace("old", item.toString()) .split(" ") return when (operator) { "*" -> first.toULong() * last.toULong() "+" -> first.toULong() + last.toULong() else -> throw UnsupportedOperationException("Operator is not known: '$operator', first: $first, last: $last") } } fun runRoundP1(monkeys: List<Monkey>): List<Monkey> { monkeys.forEach { monkey: Monkey -> val monkeyItems = monkey.items monkey.items = emptyList<ULong>().toMutableList() monkeyItems.forEach { item -> val newScore = operateOnItem(item, monkey.operation) / 3uL if (newScore % monkey.test.toULong() == 0uL) { monkeys[monkey.trueDest].items.add(newScore) } else { monkeys[monkey.falseDest].items.add(newScore) } monkey.inspectedObjects++ } } return monkeys } fun part1(input: String): ULong { var monkeys = input.split("\n\n").map { monkey -> val linedMonkey = monkey.lines() Monkey( id = linedMonkey.first().removePrefix("nerok.aoc.aoc2022.day11.Monkey ").removeSuffix(":").toULong(), items = linedMonkey[1].trim().removePrefix("Starting items: ").split(", ").map { it.toULong() }.toMutableList(), operation = linedMonkey[2].trim().removePrefix("Operation: "), test = linedMonkey[3].trim().removePrefix("Test: divisible by ").toInt(), trueDest = linedMonkey[4].trim().removePrefix("If true: throw to monkey ").toInt(), falseDest = linedMonkey[5].trim().removePrefix("If false: throw to monkey ").toInt() ) } val rounds = 20 (1..rounds).forEach { _ -> monkeys = runRoundP1(monkeys) } return monkeys.sortedBy { it.inspectedObjects }.takeLast(2).map { it.inspectedObjects }.reduce { acc, l -> acc * l } } fun runRoundP2(monkeys: List<Monkey>): List<Monkey> { val modulo = monkeys.map { it.test }.reduce { acc, i -> acc * i }.toULong() monkeys.forEach { monkey: Monkey -> val monkeyItems = monkey.items monkey.items = emptyList<ULong>().toMutableList() monkeyItems.forEach { item -> val newScore = operateOnItem(item, monkey.operation) % modulo // newScore = if (round % 2L == 0L) newScore else newScore if (newScore % monkey.test.toULong() == 0uL) { monkeys[monkey.trueDest].items.add(newScore) } else { monkeys[monkey.falseDest].items.add(newScore) } monkey.inspectedObjects++ } } return monkeys } fun part2(input: String): ULong { var monkeys = input.split("\n\n").map { monkey -> val linedMonkey = monkey.lines() Monkey( id = linedMonkey.first().removePrefix("nerok.aoc.aoc2022.day11.Monkey ").removeSuffix(":").toULong(), items = linedMonkey[1].trim().removePrefix("Starting items: ").split(", ").map { it.toULong() }.toMutableList(), operation = linedMonkey[2].trim().removePrefix("Operation: "), test = linedMonkey[3].trim().removePrefix("Test: divisible by ").toInt(), trueDest = linedMonkey[4].trim().removePrefix("If true: throw to monkey ").toInt(), falseDest = linedMonkey[5].trim().removePrefix("If false: throw to monkey ").toInt() ) } val rounds = 10_000 (1..rounds).forEach { _ -> monkeys = runRoundP2(monkeys) } return monkeys.sortedBy { it.inspectedObjects }.takeLast(2).map { it.inspectedObjects }.reduce { acc, l -> acc * l } } // test if implementation meets criteria from the description, like: val testInput = Input.getInput("Day11_test") check(part1(testInput) == 10605uL) check(part2(testInput) == 2713310158uL) val input = Input.getInput("Day11") println(measureTime { println(part1(input)) }.toString(DurationUnit.MICROSECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.MICROSECONDS, 3)) } data class Monkey( val id: ULong, var items: MutableList<ULong>, val operation: String, val test: Int, val falseDest: Int, val trueDest: Int, var inspectedObjects: ULong = 0uL )
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
4,857
AOC
Apache License 2.0
src/Day01.kt
zhiqiyu
573,221,845
false
{"Kotlin": 20644}
import kotlin.math.max class SimpleHeap(var data: Array<Int> = arrayOf(0, 0, 0)) { fun add(item: Int) { data.set(2, max(data.get(2), item)) reorder() return } fun reorder() { var cur = 2 while (cur > 0 && data.get(cur) > data.get(cur - 1)) { val temp = data.get(cur-1) data.set(cur-1, data.get(cur)) data.set(cur, temp) cur-- } } } fun main() { fun part1(input: List<String>): Int { var largest = 0 var cur = 0 for (line in input) { val parsed = line.toIntOrNull() if (parsed !== null) { cur += parsed } else { largest = max(largest, cur) cur = 0 } } return max(largest, cur) } fun part2(input: List<String>): Int { var heap = SimpleHeap() var cur = 0 for (line in input) { val parsed = line.toIntOrNull() if (parsed !== null) { cur += parsed } else { heap.add(cur) cur = 0 } } heap.add(cur) return heap.data.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println("----------") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d3aa03b2ba2a8def927b94c2b7731663041ffd1d
1,538
aoc-2022
Apache License 2.0
src/test/kotlin/amb/aoc2020/day17.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test class Day17 : TestBase() { fun getInput(file: String): HyperCube { return getTestData(file).filter { it.isNotEmpty() }.flatMapIndexed { x, line -> line.mapIndexed { y, value -> Pair(Quadrupel(x, y, 0,0), value == '#') }.filter { it.second } }.toMap() } private fun runCycle(input: HyperCube) : HyperCube { val xMin = input.keys.minOf { it.first } val yMin = input.keys.minOf { it.second } val zMin = input.keys.minOf { it.third } val wMin = input.keys.minOf { it.fourth } val xMax = input.keys.maxOf { it.first } val yMax = input.keys.maxOf { it.second } val zMax = input.keys.maxOf { it.third } val wMax = input.keys.maxOf { it.fourth } val newActives = emptyList<Quadrupel<Int>>().toMutableList() for (x in xMin - 1..xMax + 1) { for (y in yMin - 1..yMax + 1) { for (z in zMin - 1..zMax + 1) { for (w in wMin - 1..wMax + 1) { val pos = Quadrupel(x, y, z,w) val oldCubePos = input[pos] val iAmActive = (oldCubePos != null && oldCubePos) val actives = input.filter { (kotlin.math.abs(x - it.key.first) <= 1 && kotlin.math.abs(y - it.key.second) <= 1 && kotlin.math.abs(z - it.key.third) <= 1 && kotlin.math.abs(w - it.key.fourth) <= 1) }.values.sumBy { if (it) 1 else 0 } if (iAmActive && (actives == 3 || actives == 4)) newActives.add(pos) if (!iAmActive && actives == 3) newActives.add(pos) } } } } val result = newActives.map { Pair(it, true) }.toMap() return result } @Test fun task1() { var cube = getInput("input17") for (round in 1..6) { cube = runCycle(cube) } val sum = cube.values.sumBy { if (it) 1 else 0 } logger.info { "$sum active cells" } } @Test fun task2() { } } typealias Cube = Map<Triple<Int, Int, Int>, Boolean> typealias HyperCube = Map<Quadrupel<Int>, Boolean> data class Quadrupel<out A>( val first: A, val second: A, val third: A, val fourth: A )
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
2,510
aoc2020
MIT License
src/Day09.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
import java.io.File import java.lang.IllegalArgumentException import java.lang.IllegalStateException import kotlin.math.abs import kotlin.math.sqrt data class Position(val y: Int, val x: Int) data class RopeSection(val head: Position, val tail: Position) typealias Rope = Array<Position> data class Direction(val dy: Int, val dx: Int) data class Movement(val direction: Direction, val steps: Int) val CLOSE_THRESHOLD: Double = sqrt(2.0) fun toDirection(a: Position, b: Position) = Direction(b.y - a.y, b.x - a.x) fun distance(a: Position, b: Position) = sqrt((a.x - b.x).toDouble() * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)) fun movePoint(p: Position, movementDirection: Direction) = Position(p.y + movementDirection.dy, p.x + movementDirection.dx) fun adjust(ropeSection: RopeSection, movementDirection: Direction): RopeSection { val (h, t) = ropeSection return if (distance(h, t) <= CLOSE_THRESHOLD) { ropeSection } else { ropeSection.copy(tail = when { t == h -> t t.x == h.x -> t.copy(y = t.y + movementDirection.dy) t.y == h.y -> t.copy(x = t.x + movementDirection.dx) else -> when (abs(t.x - h.x) to abs(t.y - h.y)) { 1 to 2 -> Position((h.y + t.y) / 2, h.x) 2 to 1 -> Position(h.y, (t.x + h.x) / 2) 2 to 2 -> Position((h.y + t.y) / 2, (h.x + t.x) / 2) else -> throw IllegalStateException("unreachable") } }) } } fun move(rope: Rope, m: Movement): Pair<Rope, List<Position>> { val tailPositions = mutableListOf(rope.last()) repeat(m.steps) { var direction = m.direction rope[0] = movePoint(rope[0], direction) val headSection = adjust( RopeSection(rope[0], rope[1]), direction) direction = toDirection(rope[1], headSection.tail) rope[1] = headSection.tail for (i in 2 until rope.lastIndex) { val section = adjust( RopeSection(rope[i - 1], rope[i]), direction) direction = toDirection(rope[i], section.tail) rope[i] = section.tail } val section = adjust( RopeSection(rope[rope.lastIndex - 1], rope[rope.lastIndex]), direction) rope[rope.lastIndex] = section.tail tailPositions.add(rope.last()) } return rope to tailPositions } fun parseMovement(line: String): Movement { val parts = line.split(" ") val steps = parts[1].toInt() return when (parts[0]) { "R" -> Movement(Direction(0, 1), steps) "L" -> Movement(Direction(0, -1), steps) "U" -> Movement(Direction(-1, 0), steps) "D" -> Movement(Direction(1, 0), steps) else -> throw IllegalArgumentException("unknown movement $line") } } fun parseMovements(name: String): List<Movement> = File("src", "$name.txt") .readLines() .map(::parseMovement) fun main() { fun moveRope(ropeLength: Int, movements: List<Movement>): Int { val startRope = Array(ropeLength) { Position(0, 0) } val tailPositions = mutableSetOf<Position>() movements.fold(startRope) { r, movement -> val (newRope, doneTailPositions) = move(r, movement) tailPositions.addAll(doneTailPositions) newRope } return tailPositions.size } fun part1(movements: List<Movement>): Int { return moveRope(2, movements) } fun part2(movements: List<Movement>): Int { return moveRope(10, movements) } // test if implementation meets criteria from the description, like: val testMovements = parseMovements("Day09_test") check(part1(testMovements) == 13) check(part2(testMovements) == 1) check(part2(parseMovements("Day09_test_02")) == 36) val movements = parseMovements("Day09") println(part1(movements)) println(part2(movements)) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
3,933
aoc-2022-in-kotlin
Apache License 2.0
src/day15/Day15.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day15 import Point2D import readLines import kotlin.math.abs import kotlin.math.max import kotlin.math.min private class Sensor(val location: Point2D, val closestBeacon: Point2D) { var distance: Int = location.distanceTo(closestBeacon) } private fun parseInput(input: List<String>): Set<Sensor> { val pattern = "x=(-?\\d+), y=(-?\\d+)".toRegex() val set = mutableSetOf<Sensor>() for (line in input) { val matches = pattern.findAll(line).iterator() // Sensor val first = matches.next() val x1 = first.groupValues[1].toInt() val y1 = first.groupValues[2].toInt() val sensor = Point2D(x1, y1) // Beacon val second = matches.next() val x2 = second.groupValues[1].toInt() val y2 = second.groupValues[2].toInt() val beacon = Point2D(x2, y2) set.add(Sensor(sensor, beacon)) } return set } private fun part1(input: List<String>): Int { val set = parseInput(input) var minX = Integer.MAX_VALUE var maxX = Integer.MIN_VALUE var maxDistance = Integer.MIN_VALUE set.forEach { val sensor = it.location minX = min(minX, sensor.x) maxX = max(maxX, sensor.x) maxDistance = max(maxDistance, it.distance) } var count = 0 for (i in minX - maxDistance..maxX + maxDistance) { for (sensor in set) { // Exclude any sensor or beacon found on the 2,000,000th row if (i == sensor.location.x && sensor.location.y == 2_000_000 || i == sensor.closestBeacon.x && sensor.closestBeacon.y == 2_000_000) { break } // If the distance between sensor and coordinate is less than the sensor's manhattan // distance, a beacon cannot be at this coordinate if (abs(i - sensor.location.x) + abs(2_000_000 - sensor.location.y) <= sensor.distance) { count += 1 break } } } return count } private fun part2(input: List<String>): Long { val sensorSet = parseInput(input) // Given that there's only ONE possible solution, the distress beacon is guaranteed // to be +1 away from a perimeter. So we add +1 to each distance, which will help us // calculate all possible coordinates for the distress beacon. sensorSet.map { it.distance += 1 } // The problem statement specifies that the distress beacon is within this range. val distressBeaconRange = 0..4_000_000 return sensorSet.firstNotNullOf { sensor -> (-sensor.distance..sensor.distance).firstNotNullOfOrNull { delta -> listOf( // Imagine traversing a diamond perimeter from left to right. To do so, we move across the // x-axis from the leftmost point to the rightmost point while grabbing the corresponding +/- y axis. Point2D(sensor.location.x + delta, (sensor.location.y - sensor.distance) - delta), Point2D(sensor.location.x + delta, (sensor.location.y + sensor.distance) + delta) ).filter { // Filter out anything that isn't in the distress beacon range it.x in distressBeaconRange && it.y in distressBeaconRange }.firstOrNull { point -> // We found the distress beacon IF its abs distance to each sensor is >= the manhattan distance + 1 // (remember we added + 1 to each distance so we could traverse the perimeter) sensorSet.all { sensor -> abs(sensor.location.x - point.x) + abs(sensor.location.y - point.y) >= sensor.distance } } }?.let { // Calculate the tuning frequency it.x.toLong() * 4_000_000 + it.y } } } fun main() { //println(part1(readLines("day15/test"))) //println(part1(readLines("day15/test"))) println(part1(readLines("day15/input"))) println(part2(readLines("day15/input"))) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
4,031
aoc2022
Apache License 2.0
src/main/kotlin/year2022/day-11.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.aoc.Day import lib.aoc.Part import java.math.BigInteger fun main() { Day(11, 2022, PartA11(20, 3), PartB11(10_000, 1)).run() } open class PartA11(private val rounds: Int, private val worryLevelFactor: Int) : Part() { private lateinit var monkeys: List<Monkey> sealed class Operation(val action: (BigInteger) -> BigInteger) class MulOperation(factor: Int) : Operation({ it * factor.toBigInteger() }) class PowOperation : Operation({ it * it }) class AddOperation(summand: Int) : Operation({ it + summand.toBigInteger() }) private fun Operation(text: String): Operation { val (_, operator, right) = text.split(" ") return when { operator == "+" -> AddOperation(right.toInt()) operator == "*" && right == "old" -> PowOperation() operator == "*" -> MulOperation(right.toInt()) else -> throw IllegalArgumentException("unknown operator $operator") } } data class Monkey( val items: MutableList<BigInteger>, var operation: Operation, val testNumer: Int, val trueDestination: Int, val falseDestination: Int ) { var itemsInspected: BigInteger = BigInteger.valueOf(0) fun turn(monkeys: List<Monkey>, worryLevelFactor: Int) { val modulo = monkeys.map(Monkey::testNumer).reduce(Int::times) items.forEach { val old = it var item = operation.action(old) item /= worryLevelFactor.toBigInteger() item %= modulo.toBigInteger() val rest = item % testNumer.toBigInteger() if (rest == BigInteger.ZERO) { monkeys[trueDestination].items.add(item) } else { monkeys[falseDestination].items.add(item) } itemsInspected++ } items.clear() } } private fun Monkey(text: String): Monkey { val lines = text.split("\n") val items = lines[1].split(": ")[1].split(", ").map(String::toBigInteger) val operation = Operation(lines[2].split("new = ")[1]) val testNumber = lines[3].split("by ")[1].toInt() val trueDestination = lines[4].split("monkey ")[1].toInt() val falseDestination = lines[5].split("monkey ")[1].toInt() return Monkey(items.toMutableList(), operation, testNumber, trueDestination, falseDestination) } override fun parse(text: String) { monkeys = text.split("\n\n").map(::Monkey) } override fun compute(): String { repeat(rounds) { monkeys.forEach { it.turn(monkeys, worryLevelFactor) } } return monkeys.map(Monkey::itemsInspected) .sorted() .takeLast(2) .reduce { acc, x -> acc * x } .toString() } override val exampleAnswer: String get() = "10605" } class PartB11(rounds: Int, worryLevelFactor: Int) : PartA11(rounds, worryLevelFactor) { override val exampleAnswer: String get() = "2713310158" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
3,247
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumIncompatibility.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1681. Minimum Incompatibility * @see <a href="https://leetcode.com/problems/minimum-incompatibility">Source</a> */ fun interface MinimumIncompatibility { operator fun invoke(nums: IntArray, k: Int): Int } class MinimumIncompatibilityDFS : MinimumIncompatibility { private var n = 0 private val memo: MutableMap<String, Int> = HashMap() private var k0 = 0 override operator fun invoke(nums: IntArray, k: Int): Int { nums.sort() k0 = k val count = IntArray(LIMIT) for (num in nums) if (++count[num] > k) return -1 // if same number more than k times, we can not answer the question cause there must be one bucket with same // number twice n = nums.size / k // n is the number of element in each bucket return dfs(HashSet(), count) } private fun dfs(level: MutableSet<Int>, count: IntArray): Int { if (level.size == n) { return if (end(count)) findDiff(level) else findDiff(level) + dfs(HashSet(), count) } // count is remaining element status, level is current hand bucket element val key = "${count.contentHashCode()} $level" if (memo.containsKey(key)) { return memo.getOrDefault(key, -1) } var res = INITIAL for (i in 1 until LIMIT) { if (count[i] <= 0) continue // no more this number left if (!level.add(i)) continue // at hand same number already exist count[i]-- res = min(res, dfs(level, count)) count[i]++ level.remove(i) if (level.isNotEmpty()) break // first element we don't need to expand } memo[key] = res return res } private fun findDiff(level: Set<Int>): Int { return level.max() - level.min() } private fun end(count: IntArray): Boolean { for (c in count) { if (c != 0) { return false } } return true } companion object { private const val INITIAL = 1000 private const val LIMIT = 17 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,789
kotlab
Apache License 2.0
src/Day10.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>, duration: Int): Int { var x = 1 var cycle = 1 fun checkCycle(): Boolean { return cycle == duration } for (instruction in input) { if (instruction.startsWith("addx")) { val amount = instruction.split(" ")[1].toInt() cycle += 1 if (checkCycle()) { return x * cycle } cycle += 1 x += amount } else if (instruction == "noop") { cycle += 1 } if (checkCycle()) { return x * cycle } } return 0 } fun sumPart1(input: List<String>): Int { return intArrayOf(20, 60, 100, 140, 180, 220).sumOf { part1(input, it) } } fun part2(input: List<String>, width: Int = 40) { var x = 1 var cycle = 1 val output = StringBuilder(240) fun render() { val char = if ((cycle % 40 - x-1).absoluteValue <= 1) "#" else "." output.append(char) if (cycle > 240) return } for (instruction in input) { if (instruction.startsWith("addx")) { val amount = instruction.split(" ")[1].toInt() render() cycle += 1 render() cycle += 1 x += amount } else if (instruction == "noop") { render() cycle += 1 } } // println(output) output.toString().chunked(40).forEach { println(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") // check(part1(testInput, 20) == 420) // check(part1(testInput, 60) == 1140) // check(part1(testInput, 100) == 1800) // check(part1(testInput, 140) == 2940) // check(part1(testInput, 180) == 2880) // check(part1(testInput, 220) == 3960) // // check(sumPart1(testInput) == 13140) // check(part2(testInput) == 45000) part2(testInput) println() val input = readInput("Day10") // println(sumPart1(input)) part2(input) }
0
Kotlin
0
0
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
2,283
adventofcode-2022
Apache License 2.0
src/main/kotlin/day03/day03.kt
corneil
572,437,852
false
{"Kotlin": 93311, "Shell": 595}
package main.day03 import utils.readFile import utils.readLines fun main() { fun calcPriority(value: Char): Int = when (value) { in 'a'..'z' -> value - 'a' + 1 in 'A'..'Z' -> value - 'A' + 27 else -> error("Invalid input $value") } fun calcRucksacks(input: List<String>): Int = input.map { Pair(it.substring(0 until it.length / 2), it.substring(it.length / 2)) } .map { Pair(it.first.toSet(),it.second.toSet()) } .map { it.first.intersect(it.second).first() } .sumOf { calcPriority(it) } fun calcBadges(input: List<String>): Int = input.chunked(3) .map { group -> group .map { it.toSet() } .reduce { a, b -> a.intersect(b) } .first() } .sumOf { calcPriority(it) } val test = """v<KEY>""" fun part1() { val testPriorities = calcRucksacks(readLines(test)) println("Test Priorities = $testPriorities") check(testPriorities == 157) val priorities = calcRucksacks(readFile("day03")) println("Priorities = $priorities") // added after success to ensure refactoring doesn't break check(priorities == 8123) } fun part2() { val testPriorities = calcBadges(readLines(test)) println("Test Priorities = $testPriorities") check(testPriorities == 70) val priorities = calcBadges(readFile("day03")) println("Priorities = $priorities") // added after success to ensure refactoring doesn't break check(priorities == 2620) } println("Day - 03") part1() part2() }
0
Kotlin
0
0
dd79aed1ecc65654cdaa9bc419d44043aee244b2
1,672
aoc-2022-in-kotlin
Apache License 2.0
src/Day23.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
private class ElvenField(map: List<String>) { val elfAmount: Int val elfPositions: MutableList<Pair<Int, Int>> = mutableListOf() val positionsToElf: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() val directions = mutableListOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) init { var counter = 0 map.withIndex().forEach { (x, line) -> line.withIndex().forEach { (y, char) -> if (char == '#') { elfPositions.add(x to y) positionsToElf[x to y] = counter counter++ } } } elfAmount = counter } fun makeTurn(): Boolean { val propositions: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() for ((ind, elf) in elfPositions.withIndex()) { var atLeastOne = false for (x in (-1..1)) { for (y in (-1..1)) { if (x == 0 && y == 0) continue if ((elf + (x to y)) in positionsToElf) { atLeastOne = true } } } if (!atLeastOne) continue for (dir in directions) { if ((-1..1).any { c -> val pos = elf + if (dir.first == 0) (c to dir.second) else (dir.first to c) pos in positionsToElf }) continue val pos = elf + dir if (pos in propositions) { propositions[pos] = -1 } else { propositions[pos] = ind } break } } var moved = false propositions.forEach { if (it.value != -1) { moved = true val oldPos = elfPositions[it.value] elfPositions[it.value] = it.key positionsToElf.remove(oldPos) positionsToElf[it.key] = it.value } } val dir = directions.removeAt(0) directions.add(dir) return moved } fun getFreeSpace(): Int { return (elfPositions.maxOf { (x, _) -> x } - elfPositions.minOf { (x, _) -> x } + 1) * (elfPositions.maxOf { (_, y) -> y } - elfPositions.minOf { (_, y) -> y } + 1) - elfAmount } } fun main() { fun part1(input: List<String>): Int { val field = ElvenField(input) repeat(10) { field.makeTurn() } return field.getFreeSpace() } fun part2(input: List<String>): Int { val field = ElvenField(input) var cnt = 1 while (field.makeTurn()) cnt++ return cnt } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
2,990
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day03.kt
fwangel
435,571,075
false
{"Kotlin": 150622}
package se.brainleech.adventofcode.aoc2021 import se.brainleech.adventofcode.compute import se.brainleech.adventofcode.readLines import se.brainleech.adventofcode.verify import java.util.stream.Collectors class Aoc2021Day03 { companion object { private const val ZERO = 0 private const val ONE = 1 } private fun transpose(matrix: List<IntArray>): Array<IntArray> { val rows = matrix.size val columns = matrix[0].size val transposed = Array(columns) { IntArray(rows) } for (i in 0 until rows) { for (j in 0 until columns) { transposed[j][i] = matrix[i][j] } } return transposed } private fun Array<IntArray>.mostOf(): Int { return this.withIndex().sumOf { it.value.mostOf() shl (this.size - 1 - it.index) } } private fun IntArray.mostOf(): Int { val groups = this.groupBy { it }.withDefault { emptyList() } if (groups.getValue(ONE).size >= groups.getValue(ZERO).size) { return ONE } return ZERO } private fun IntArray.leastOf(): Int { val groups = this.groupBy { it }.withDefault { emptyList() } if (groups.getValue(ONE).size < groups.getValue(ZERO).size) { return ONE } return ZERO } private fun Array<IntArray>.mostOfByIndex(): Map<Int, Int> { return this.withIndex().associate { it.index to it.value.mostOf() } } private fun Array<IntArray>.leastOfByIndex(): Map<Int, Int> { return this.withIndex().associate { it.index to it.value.leastOf() } } private fun IntArray.toDecimal(): Int { return this.withIndex().sumOf { it.value shl (this.size - 1 - it.index) } } fun part1(source: List<String>): Int { val input = source.stream() .map { bits -> bits.toCharArray() .map { bit -> bit.digitToInt() } .toIntArray() } .collect(Collectors.toList()) val output = transpose(input) val maxValue = (2 shl (output.size - 1)) - 1 val gamma = output.mostOf() val epsilon = maxValue - gamma return gamma * epsilon } fun part2(source: List<String>): Int { val input = source .map { bits -> bits.toCharArray() .map { bit -> bit.digitToInt() } .toIntArray() } .toList() fun oxygenGeneratorRating(): Int { var bitIndex = 0 var ratings = input do { val output = transpose(ratings) val byIndex = output.mostOfByIndex() ratings = ratings.filter { it[bitIndex] == byIndex[bitIndex] } bitIndex++ } while (ratings.size > 1) return ratings.first().toDecimal() } fun co2ScrubberRating(): Int { var bitIndex = 0 var ratings = input do { val output = transpose(ratings) val byIndex = output.leastOfByIndex() ratings = ratings.filter { it[bitIndex] == byIndex[bitIndex] } bitIndex++ } while (ratings.size > 1) return ratings.first().toDecimal() } val oxygen = oxygenGeneratorRating() val co2 = co2ScrubberRating() return oxygen * co2 } } fun main() { val solver = Aoc2021Day03() val prefix = "aoc2021/aoc2021day03" val testData = readLines("$prefix.test.txt") val realData = readLines("$prefix.real.txt") verify(198, solver.part1(testData)) compute({ solver.part1(realData) }, "$prefix.part1 = ") verify(230, solver.part2(testData)) compute({ solver.part2(realData) }, "$prefix.part2 = ") }
0
Kotlin
0
0
0bba96129354c124aa15e9041f7b5ad68adc662b
3,865
adventofcode
MIT License
src/main/kotlin/com/ginsberg/advent2021/Day17.kt
tginsberg
432,766,033
false
{"Kotlin": 92813}
/* * Copyright (c) 2021 by <NAME> */ /** * Advent of Code 2021, Day 17 - Trick Shot * Problem Description: http://adventofcode.com/2021/day/17 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day17/ */ package com.ginsberg.advent2021 import kotlin.math.absoluteValue class Day17(input: String) { private val targetArea: TargetArea = parseInput(input) fun solvePart1(): Int = (0..targetArea.x.last).maxOf { x -> (targetArea.y.first..targetArea.y.first.absoluteValue).maxOf { y -> val track = probePositions((Point2d(x, y))).takeWhile { !targetArea.hasOvershot(it) } if (track.any { it in targetArea }) track.maxOf { it.y } else 0 } } fun solvePart2(): Int = (0..targetArea.x.last).sumOf { x -> (targetArea.y.first..targetArea.y.first.absoluteValue).count { y -> probePositions(Point2d(x, y)).first { targetArea.hasOvershot(it) || it in targetArea } in targetArea } } private fun probePositions(velocity: Point2d): Sequence<Point2d> = sequence { var position = Point2d(0, 0) var actualVelocity = velocity while (true) { position = Point2d( position.x + actualVelocity.x, position.y + actualVelocity.y ) actualVelocity = Point2d( actualVelocity.x + if (actualVelocity.x > 0) -1 else if (actualVelocity.x < 0) 1 else 0, actualVelocity.y - 1 ) yield(position) } } private class TargetArea(val x: IntRange, val y: IntRange) { operator fun contains(point: Point2d): Boolean = point.x in x && point.y in y infix fun hasOvershot(point: Point2d): Boolean = point.x > x.last || point.y < y.first } private fun parseInput(input: String): TargetArea = TargetArea( input.substringAfter("=").substringBefore(".").toInt().. input.substringAfter("..").substringBefore(",").toInt(), input.substringAfterLast("=").substringBefore(".").toInt().. input.substringAfterLast(".").toInt() ) }
0
Kotlin
2
34
8e57e75c4d64005c18ecab96cc54a3b397c89723
2,246
advent-2021-kotlin
Apache License 2.0
src/day07/Day07.kt
pientaa
572,927,825
false
{"Kotlin": 19922}
package day07 import readLines fun main() { fun createFileSystem(input: List<String>): Directory { val fileSystem = Directory("/") val currentPath: MutableList<String> = mutableListOf() input.drop(1).map { when { it.contains("dir") -> { val directoryName = it.substring(4) fileSystem.addDirectory(directoryName, currentPath) } it.any { c -> c.isDigit() } -> { fileSystem.addFile(File(it), currentPath) } it.contains("cd") && it.contains("..") -> { currentPath.removeLast() } it.contains("cd") && !it.contains("..") -> { val directoryName = it.substring(5) currentPath.add(directoryName) } else -> {} } } return fileSystem } fun part1(input: List<String>): Int { val fileSystem = createFileSystem(input) return fileSystem.getAllDirectoriesFlatten() .map { it.getOverallSize() } .filter { it <= 100000 } .sum() } fun part2(input: List<String>): Int { val fileSystem = createFileSystem(input) val sizes = fileSystem.getAllDirectoriesFlatten() .map { it.getOverallSize() } val toDelete = sizes.max() - 40000000 return fileSystem.getAllDirectoriesFlatten() .map { it.getOverallSize() } .also { println(it) } .filter { it >= toDelete } .minBy { it } } // test if implementation meets criteria from the description, like: val testInput = readLines("day07/Day07_test") val input = readLines("day07/Day07") println(part1(input)) println(part2(input)) } class Directory(private val name: String) { private val directories: MutableList<Directory> = mutableListOf() private val files: MutableList<File> = mutableListOf() private var size: Int = 0 fun addDirectory(directoryName: String, path: List<String>) { val nestedDirectory = getDirectoryAtPath(path) nestedDirectory.addDirectory(Directory(directoryName)) } private fun addDirectory(directory: Directory) { if (directories.none { it.name == directory.name }) directories.add(directory) } fun addFile(file: File, path: List<String>) { val directory = getDirectoryAtPath(path) directory.addFile(file) } private fun addFile(file: File) { if (files.none { it.name == file.name }) { files.add(file) size += file.size } } fun getOverallSize(): Int = size + directories.sumOf { it.getOverallSize() } private fun getDirectoryAtPath(path: List<String>) = path.fold(this) { acc, s -> acc.directories.first { it.name == s } } fun getAllDirectoriesFlatten(): Set<Directory> = setOf(this) + directories + directories.flatMap { it.getAllDirectoriesFlatten() } } class File private constructor(val name: String, val size: Int) { companion object { operator fun invoke(line: String): File { val (size, name) = line.split(" ") return File(name, size.toInt()) } } }
0
Kotlin
0
0
63094d8d1887d33b78e2dd73f917d46ca1cbaf9c
3,347
aoc-2022-in-kotlin
Apache License 2.0
src/Day11.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
import java.lang.Exception fun main() { fun playRound(monkeys: List<Monkey>) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { var item = monkey.getFirstItem() item = monkey.calculateNewValue(item) item = item.div(3.toLong()) val newMonkey = if (item % monkey.divisibleValue.toLong() == 0L) monkey.testTrue else monkey.testFalse monkeys[newMonkey].addItem(item) } } } fun playRound2(monkeys: List<Monkey>, divider: Int) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { var item = monkey.getFirstItem() item = monkey.calculateNewValue(item) item %= divider val newMonkey = if (item % monkey.divisibleValue.toLong() == 0L) monkey.testTrue else monkey.testFalse monkeys[newMonkey].addItem(item) } } } fun List<String>.toMonkeys(): List<Monkey> { return this .filterNot { it.isBlank() } .chunked(6) .map { line -> val startingItems = line[1].split(":")[1].split(",").map { it.trim().toLong() } val operationLine = line[2].split(" ") val operation = operationLine[operationLine.size - 2] val operationValue = try { operationLine[operationLine.size - 1].toLong() } catch (e: Exception) { (-1).toLong() } val divisibleValue = line[3].split(" ").last().toInt() val testTrue = line[4].split(" ").last().toInt() val testFalse = line[5].split(" ").last().toInt() Monkey(startingItems, operation, operationValue, divisibleValue, testTrue, testFalse) } } fun part1(input: List<String>): Int { val monkeys = input.toMonkeys() repeat(20) { playRound(monkeys) } return monkeys.map { it.inspectedItems }.sortedDescending().take(2) .fold(1) { acc, i -> acc * i } } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val divider = monkeys.map { it.divisibleValue }.fold(1) { acc, i -> acc * i } repeat(10000) { playRound2(monkeys, divider) } return monkeys.map { it.inspectedItems }.sortedDescending().take(2) .fold(1) { acc, i -> acc * i } } val testInput = readInput("Day11Test") check(part1(testInput) == 10605) check(part2(testInput) == 2_713_310_158) val input = readInput("Day11") println("Question 1 - Answer: ${part1(input)}") println("Question 2 - Answer: ${part2(input)}") } class Monkey( items: List<Long>, operation: String, operationValue: Long, divisibleValue: Int, testTrue: Int, testFalse: Int ) { val items: ArrayDeque<Long> private val operation: String private val operationValue: Long val divisibleValue: Int val testTrue: Int val testFalse: Int var inspectedItems = 0 init { this.items = ArrayDeque(items) this.operation = operation this.operationValue = operationValue this.divisibleValue = divisibleValue this.testTrue = testTrue this.testFalse = testFalse } fun addItem(item: Long) { items.add(item) } fun getFirstItem(): Long { return items.removeFirst() } fun calculateNewValue(item: Long): Long { inspectedItems++ val ov = if (operationValue < 0.toLong()) item else operationValue return if (operation == "+") item + ov else item * ov } override fun toString(): String { return "Monkey(items=$items, inspectedItems=$inspectedItems)" } }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
3,895
AdventOfCode2022
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day2/Two.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day2 import com.tonnoz.adventofcode23.utils.readInput typealias Color = String const val SPACE = " " const val SEMICOLON = ";" const val COLON = ":" const val COMMA = "," object Two { @JvmStatic fun main(args: Array<String>) { val input = "inputTwo.txt".readInput() val games = input.map { it.toGame() } games .filter { it.rounds.none { gameR -> gameR.isInvalid() } } .sumOf { it.gameNr } .let { println(it) } //answer first problem games .map { it.toGameExtra() } .sumOf { it.minCubes.values.reduce(Int::times) } .let { println(it) } //answer second problem } //PROBLEM ONE //max 12 red cubes, 13 green cubes, and 14 blue cubes data class GameRound(val blueCubes: Int?, val greenCubes: Int?, val redCubes: Int?) data class Game(val gameNr: Int, val rounds: List<GameRound>, val minCubes: Map<Color, Int>) private fun GameRound.isInvalid(): Boolean = (this.redCubes ?: 0) > 12 || (this.greenCubes ?: 0) > 13 || (this.blueCubes ?: 0) > 14 private fun String.toGame(): Game { val line = this.split(COLON) val gameNr = line.first().split(SPACE).last().toInt() val roundsString = line.last().split(SEMICOLON) val rounds = roundsString.map { it.split(COMMA) .map { gameThrow -> gameThrow.trim() } .map { gameThrowT -> val (first, second) = gameThrowT.split(SPACE); first to second } .associate { (first, second) -> second to first.toInt() } }.map { GameRound(it["blue"], it["green"], it["red"]) } return Game(gameNr, rounds, emptyMap()) } //PROBLEM 2: private fun Game.toGameExtra(): Game { val maxBlue = this.rounds.maxBy { it.blueCubes ?: 0 }.blueCubes ?: 1 val maxRed = this.rounds.maxBy { it.redCubes ?: 0 }.redCubes ?: 1 val maxGreen = this.rounds.maxBy { it.greenCubes ?: 0 }.greenCubes ?: 1 return Game(this.gameNr, this.rounds, mapOf("blue" to maxBlue, "red" to maxRed, "green" to maxGreen)) } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
1,995
adventofcode23
MIT License
src/main/kotlin/adventofcode2023/day14/day14.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day14 import adventofcode2023.readInput import kotlin.time.measureTime fun main() { println("Day 14") val input = readInput("day14") println("Puzzle 1") val time1 = measureTime { println(calculateLoad(moveRocks(input.map { it.toCharArray() }))) } println("puzzle 1 took $time1") println("Puzzle 2") val time2 = measureTime { println(calculateLoad(circle(input, 1000000000))) } println("puzzle 2 took $time2") } fun moveRocks(input: List<CharArray>): List<CharArray> { for (line in (1..input.lastIndex)) { input[line].indices.forEach { column -> if (input[line][column] == 'O') { var newLine = line while (newLine > 0 && input[newLine - 1][column] == '.') { newLine-- } if (newLine != line) { input[newLine][column] = 'O' input[line][column] = '.' } } } } return input } fun calculateLoad(input: List<CharArray>) : Int { var counter = 0 input.forEachIndexed { index, chars -> counter += chars.count { it == 'O' } * (input.size - index) } return counter } fun List<CharArray>.rotate(): List<CharArray> { /* 1 2 3 7 4 1 4 5 6 => 8 5 2 7 8 9 9 6 3 */ return buildList { this@rotate.first.indices.forEach { index -> buildList { this@rotate.reversed().forEach { arr -> add(arr[index]) } }.toCharArray().let { add(it) } } } } fun circle(input: List<String>, n: Int): List<CharArray> { var preparedInput = input.map { it.toCharArray() } val cache = mutableMapOf<String, Int>() val cache2 = mutableMapOf<Int, List<CharArray>>() repeat(n) { iteration -> val buildString = preparedInput.joinToString("\n") { chars -> chars.joinToString("") { "$it" } } val oldValue = cache.put(buildString, iteration) if (oldValue != null) { val diff = iteration - oldValue val newIndex = oldValue + (n - oldValue) % diff return cache2[newIndex]!! } cache2[iteration] = buildList { addAll(preparedInput.map { it.copyOf() }) } val p1 = moveRocks(preparedInput) val p2 = moveRocks(p1.rotate()) val p3 = moveRocks(p2.rotate()) preparedInput = moveRocks(p3.rotate()).rotate() println("iteration $iteration") } return preparedInput }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
2,586
adventofcode2023
MIT License
src/main/kotlin/com/jacobhyphenated/advent2023/day2/Day2.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day2 import com.jacobhyphenated.advent2023.Day import com.jacobhyphenated.advent2023.product /** * Day 2: Cube Conundrum * * Each line of input represents a game with a bag with an unknown number of red, green, and blue cubes * Several times, reach into the bag for a sample of colors, then replace the cubes in the bag. */ class Day2: Day<List<String>> { override fun getInput(): List<String> { return readInputFile("2").lines() } /** * Part 1: Determine which games would have been possible * if the bag had been loaded with only 12 red cubes, 13 green cubes, and 14 blue cubes. * What is the sum of the IDs of those games? */ override fun part1(input: List<String>): Int { val colorCheck = mapOf(Color.RED to 12, Color.GREEN to 13, Color.BLUE to 14) return input.mapIndexed { index, line -> val passCheck = maxColorsFromLine(line).all { (color, count) -> colorCheck.getValue(color) >= count } // use index + 1 for the game ID if (passCheck) { index + 1 } else { 0 } }.sum() } /** * Part 2: What is the fewest number of possible cubes of each color for each game? * Multiply these numbers to get the score for each game, then add up the scores. */ override fun part2(input: List<String>): Int { return input.sumOf { line -> maxColorsFromLine(line).values.product() } } /** * Take the input string and parse it into a map * where the key is the color and the value is the minimum possible amount of that color in the bag */ private fun maxColorsFromLine(line: String): Map<Color, Int> { val colorSamples = line.split(":")[1].trim().split(";") val maxColorMap = mutableMapOf(Color.RED to 0, Color.GREEN to 0, Color.BLUE to 0) colorSamples.forEach { sample -> sample.split(",") .map { it.trim().split(" ") } .forEach { (number, colorString) -> val color = Color.fromString(colorString) val colorCount = number.toInt() if (maxColorMap.getValue(color) < colorCount) { maxColorMap[color] = colorCount } } } return maxColorMap } override fun warmup(input: List<String>) { maxColorsFromLine(input[0]) } } enum class Color { RED, BLUE, GREEN; companion object { fun fromString(input: String): Color { return when(input) { "blue" -> BLUE "red" -> RED "green" -> GREEN else -> throw IllegalArgumentException("Invalid color: $input") } } } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day2().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
2,650
advent2023
The Unlicense
2023/src/day08/Day08.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day08 import java.io.File fun main() { val input = File("src/day08/day08.txt").readLines() val instructions = input[0] val map = NodeMap(input.drop(2)) println(runInstructions(instructions, map)) println(runInstructionsAsGhost(instructions, map)) } class Node(val id: String, val left: String, val right: String) { } class NodeMap(input: List<String>) { private val LINE = Regex("""(\w{3}) = \((\w{3}), (\w{3})\)""") private val nodeMapping: Map<String, Node> init { nodeMapping = input.map { val match = LINE.find(it)!! val (id, left, right) = match.destructured Node(id, left, right) }.associateBy { it.id } } fun getNode(id: String): Node { return nodeMapping[id]!! } fun getStartingNodes(): List<Node> { return nodeMapping.entries.filter { it.key.endsWith("A") }.map { it.value } } } fun runInstructions(instructions: String, nodeMap: NodeMap): Int { val instructionList = instructions.toList() var node = nodeMap.getNode("AAA") var stepCount = 0 while (node.id != "ZZZ") { val instruction = instructionList[stepCount++ % instructionList.size] // println("$stepCount currentNode: ${node.id} ${node.left} ${node.right} $instruction") node = when (instruction) { 'R' -> nodeMap.getNode(node.right) 'L' -> nodeMap.getNode(node.left) else -> throw IllegalArgumentException("$instruction is not valid") } } return stepCount } fun runInstructionsAsGhost(instructions: String, nodeMap: NodeMap): Long { val instructionList = instructions.toList() // Find all the starting nodes val nodeList = nodeMap.getStartingNodes() var initialZ = MutableList(nodeList.size) { 0L } var stepCounts = MutableList(nodeList.size) { 0L } nodeList.forEachIndexed { index, startNode -> var node = startNode var stepCount = 0 var foundZ = false while (!node.id.endsWith("Z") || !foundZ) { if (node.id.endsWith("Z")) { println("${startNode.id} : found Z at $stepCount") foundZ = true initialZ[index] = stepCount.toLong() } val instruction = instructionList[stepCount++ % instructionList.size] // println("$stepCount currentNode: ${node.id} ${node.left} ${node.right} $instruction") node = when (instruction) { 'R' -> nodeMap.getNode(node.right) 'L' -> nodeMap.getNode(node.left) else -> throw IllegalArgumentException("$instruction is not valid") } } stepCounts[index] = stepCount.toLong() println("${startNode.id} : found second Z at $stepCount : period = ${stepCount - initialZ[index]}") } // Now get the least common multiple : meh, google sheets return stepCounts.reduce { acc, i -> acc * i } } fun gcd(a: Long, b: Long): Long { return if (b == 0L) { a } else { gcd(b, a % b) } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,081
adventofcode
Apache License 2.0
src/main/kotlin/g1801_1900/s1857_largest_color_value_in_a_directed_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1857_largest_color_value_in_a_directed_graph // #Hard #Hash_Table #Dynamic_Programming #Graph #Counting #Memoization #Topological_Sort // #2023_10_02_Time_1005_ms_(60.00%)_Space_253.2_MB_(20.00%) class Solution { fun largestPathValue(colors: String, edges: Array<IntArray>): Int { val len = colors.length val graph = buildGraph(len, edges) val frequencies = IntArray(26) val calculatedFrequencies = HashMap<Int, IntArray>() val status = IntArray(len) for (i in 0 until len) { if (status[i] != 0) { continue } val localMax = runDFS(graph, i, calculatedFrequencies, status, colors) if (localMax!![26] == -1) { frequencies.fill(-1) break } else { for (color in 0..25) { frequencies[color] = Math.max(frequencies[color], localMax[color]) } } } var max = Int.MIN_VALUE for (freq in frequencies) { max = Math.max(max, freq) } return max } private fun runDFS( graph: Array<MutableList<Int>?>, node: Int, calculatedFrequencies: HashMap<Int, IntArray>, status: IntArray, colors: String ): IntArray? { if (calculatedFrequencies.containsKey(node)) { return calculatedFrequencies[node] } val frequencies = IntArray(27) if (status[node] == 1) { frequencies[26] = -1 return frequencies } status[node] = 1 for (neighbour in graph[node]!!) { val localMax = runDFS(graph, neighbour, calculatedFrequencies, status, colors) if (localMax!![26] == -1) { return localMax } for (i in 0..25) { frequencies[i] = Math.max(frequencies[i], localMax[i]) } } status[node] = 2 val color = colors[node].code - 'a'.code frequencies[color]++ calculatedFrequencies[node] = frequencies return frequencies } private fun buildGraph(n: Int, edges: Array<IntArray>): Array<MutableList<Int>?> { val graph: Array<MutableList<Int>?> = arrayOfNulls(n) for (i in 0 until n) { graph[i] = ArrayList() } for (edge in edges) { graph[edge[0]]?.add(edge[1]) } return graph } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,494
LeetCode-in-Kotlin
MIT License
src/net/sheltem/aoc/y2023/Day12.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 suspend fun main() { Day12().run() } class Day12 : Day<Long>(21, 525152) { override suspend fun part1(input: List<String>): Long = input.map(SpringGroup::from).sumOf { it.possibleCombinations() } override suspend fun part2(input: List<String>): Long = input.map { SpringGroup.from(it, 4) }.sumOf { it.possibleCombinations() } data class SpringGroup(val line: String, val record: List<Int>) { private val maxLengths = IntArray(line.length) { line.drop(it).takeWhile { char -> char != '.' }.length } private val combinations = mutableMapOf<Pair<Int, Int>, Long>() fun possibleCombinations(charsUsed: Int = 0, numbersPlaced: Int = 0): Long = when { numbersPlaced == record.size -> if (line.drop(charsUsed).none { char -> char == '#' }) 1L else 0 charsUsed >= line.length -> 0L else -> { if (combinations[charsUsed to numbersPlaced] == null) { val take = if (canTake(charsUsed, record[numbersPlaced])) possibleCombinations(charsUsed + record[numbersPlaced] + 1, numbersPlaced + 1) else 0L val dontTake = if (line[charsUsed] != '#') possibleCombinations(charsUsed + 1, numbersPlaced) else 0L combinations[charsUsed to numbersPlaced] = take + dontTake } combinations[charsUsed to numbersPlaced]!! } } private fun canTake(index: Int, toTake: Int) = maxLengths[index] >= toTake && (index + toTake == line.length || line[index + toTake] != '#') companion object { fun from(fullRecord: String, add: Int = 0) = fullRecord .split(" ") .let { (line, record) -> SpringGroup(line + "?$line".repeat(add), (record + ",$record".repeat(add)).split(",").map(String::toInt)) } } } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
1,939
aoc
Apache License 2.0
src/Day01.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
import java.util.PriorityQueue fun main() { fun part1(input: List<String>): Int { return input .asSequence() .map(String::toIntOrNull) .sumGroups() .maxOrNull() ?: throw Exception("There's no food D:") } fun part2(input: List<String>): Int { return input .asSequence() .map(String::toIntOrNull) .sumGroups() .top(3) .sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } // Emits sums of groups of Int separated by nulls fun Sequence<Int?>.sumGroups() = sequence { var acc: Int? = null val iterator = iterator() while (iterator.hasNext()) { acc = when (val next = iterator.next()) { null -> { acc?.let { yield(it) } null } else -> (acc ?: 0) + next } } acc?.let { yield(it) } } // Returns top n maximum Ints in a sequence fun Sequence<Int>.top(n: Int): List<Int> { val top = PriorityQueue<Int>(n) for (value in this) { if (top.size < n || value > top.peek()) { top.add(value) if (top.size > n) { top.poll() } } } return top.toList() }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
1,395
aoc-2022
Apache License 2.0
2022/src/main/kotlin/com/github/akowal/aoc/Day08.kt
akowal
573,170,341
false
{"Kotlin": 36572}
package com.github.akowal.aoc import kotlin.math.max class Day08 { private val grid = inputFile("day08").readLines().map { it.map(Char::digitToInt) } private val cols = grid.size private val rows = grid.first().size fun solvePart1(): Int { var visible = 0 for (row in 0 until rows) { for (col in 0 until cols) { val h = grid[row][col] if (paths(row, col).any { path -> path.all { it < h } }) { visible++ } } } return visible } fun solvePart2(): Int { var maxScore = 0 for (row in 0 until rows) { for (col in 0 until cols) { val h = grid[row][col] val score = paths(row, col).map { path -> path.indexOfFirst { it >= h }.let { if (it >= 0) it + 1 else path.size } }.reduce { a, b -> a * b } maxScore = max(score, maxScore) } } return maxScore } private fun paths(row: Int, col: Int) = listOf( grid[row].slice(col - 1 downTo 0), grid[row].slice(col + 1 until cols), grid.slice(row - 1 downTo 0).map { it[col] }, grid.slice(row + 1 until cols).map { it[col] }, ) } fun main() { val solution = Day08() println(solution.solvePart1()) println(solution.solvePart2()) }
0
Kotlin
0
0
02e52625c1c8bd00f8251eb9427828fb5c439fb5
1,456
advent-of-kode
Creative Commons Zero v1.0 Universal
src/Day03.kt
josepatinob
571,756,490
false
{"Kotlin": 17374}
fun main() { fun getAlphabetList(): List<Char> { val alphabetList = mutableListOf<Char>() var lowerChar = 'a' while (lowerChar <= 'z') { alphabetList.add(lowerChar) ++lowerChar } var capChar = 'A' while (capChar <= 'Z') { alphabetList.add(capChar) ++capChar } return alphabetList.toList() } fun part1(input: List<String>): Int { var totalSum = 0 val alphabetList = getAlphabetList() var priority = 0 val alphabetPriorityMap = mutableMapOf<String, Int>() alphabetList.forEach { alphabetPriorityMap.put(it.toString(), ++priority) } input.forEach { val halfPoint = it.length / 2 val compartments = it.chunked(halfPoint) val compartmentOne = compartments[0] val compartmentTwo = compartments[1] val repeatedMap = mapOf<String, Int>() for (i in alphabetList) { if (compartmentOne.contains(i.toString()) && compartmentTwo.contains(i.toString())) { totalSum += alphabetPriorityMap.get(i.toString()) ?: 0 } } totalSum += repeatedMap.values.sum() } return totalSum } fun part2(input: List<String>): Int { var totalSum = 0 val alphabetList = getAlphabetList() var priority = 0 val alphabetPriorityMap = mutableMapOf<String, Int>() var counter = 0 alphabetList.forEach { alphabetPriorityMap.put(it.toString(), ++priority) } while (counter < input.size - 2) { val compartmentOne = input[counter] val compartmentTwo = input[counter + 1] val compartmentThree = input[counter + 2] val repeatedMap = mapOf<String, Int>() for (i in alphabetList) { if (compartmentOne.contains(i.toString()) && compartmentTwo.contains(i.toString()) && compartmentThree.contains(i.toString()) ) { totalSum += alphabetPriorityMap.get(i.toString()) ?: 0 } } totalSum += repeatedMap.values.sum() counter += 3 } return totalSum } // test if implementation meets criteria from the description, like: //val testInput = readInput("Day03Sample") //println(part1(testInput)) //println(part2(testInput)) val input = readInput("Day03") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d429a5fff7ddc3f533d0854e515c2ba4b0d461b0
2,645
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/Day17.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { val up = Point(0, -1) val left = Point(-1, 0) val right = Point(1, 0) val rocks = listOf( (0..3).map { i -> Point(i, 0) }.toSet(), setOf(Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2), Point(1, 0)), setOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2, 2)), (0..3).map { i -> Point(0, i) }.toSet(), setOf(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) ) fun convertToCacheKey(rocks: Set<Point>): Set<Point> { val maxY = rocks.map { it.y }.max() return rocks.filter { maxY - it.y <= 30 }.map { Point(it.x, maxY - it.y) }.toHashSet() } fun part1(input: String): Long { val rocksInCave = mutableSetOf<Point>() for (i in 0..6) { rocksInCave.add(Point(i, -1)) } val jetPattern = input.trim().toCharArray().map { it == '>' } var jetCounter = 0 for (rockCount in 0..2021) { var curRock: Set<Point> = rocks[rockCount % 5] val maxY = rocksInCave.map { it.y }.max() curRock = curRock.map { it.sum(Point(2, maxY + 4)) }.toSet() movement@ while (true) { if (jetPattern[jetCounter % jetPattern.size]) { val highestX = curRock.map { it.x }.max() val tentativeRight = curRock.map { it.sum(right) }.toSet() if (highestX < 6 && !tentativeRight.any { it in rocksInCave }) { curRock = tentativeRight } } else { val lowestX = curRock.map { it.x }.min() val tentativeLeft = curRock.map { it.sum(left) }.toSet() if (lowestX > 0 && !tentativeLeft.any { it in rocksInCave }) curRock = tentativeLeft } jetCounter++ for (c in curRock) { if (rocksInCave.contains(c.sum(up))) { rocksInCave.addAll(curRock) break@movement } } curRock = curRock.map { it.sum(up) }.toSet() } } return ((rocksInCave.maxOfOrNull { it.y } ?: 0) + 1).toLong() } fun part2(input: String): Long { val target = 1000000000000L val rocksInCave: MutableSet<Point> = mutableSetOf() for (i in 0..6) { rocksInCave.add(Point(i, -1)) } val jetPattern = input.trim().toCharArray().map { it == '>' } var jetCounter = 0 val cache: MutableMap<Set<Point>, Point> = mutableMapOf() var cycleFound = false var heightFromCycleRepeat: Long = 0 var rockCount: Long = 0 while (rockCount < target) { var curRock: Set<Point> = rocks[(rockCount % 5).toInt()] val maxY = rocksInCave.map { it.y }.max() curRock = curRock.map { it.sum(Point(2, maxY + 4)) }.toSet() movement@ while (true) { if (jetPattern[jetCounter % jetPattern.size]) { val highestX = curRock.map { it.x }.max() val tentativeRight = curRock.map { it.sum(right) }.toSet() if (highestX < 6 && !tentativeRight.any { it in rocksInCave }) { curRock = tentativeRight } } else { val lowestX = curRock.map { it.x }.min() val tentativeLeft = curRock.map { it.sum(left) }.toSet() if (lowestX > 0 && !tentativeLeft.any { it in rocksInCave }) curRock = tentativeLeft } jetCounter++ for (c in curRock) { if (rocksInCave.contains(c.sum(up))) { rocksInCave.addAll(curRock) val curHeight = rocksInCave.map { it.y }.max() val cacheKey: Set<Point> = convertToCacheKey(rocksInCave) if (!cycleFound && cache.containsKey(cacheKey)) { val info: Point = cache[cacheKey]!! val oldTime: Int = info.x val oldHeight: Int = info.y val cycleLength = (rockCount - oldTime).toInt() val cycleHeightChange = curHeight - oldHeight val numCycles = (target - rockCount) / cycleLength heightFromCycleRepeat = cycleHeightChange * numCycles rockCount += numCycles * cycleLength cycleFound = true } else { val info = Point(rockCount.toInt(), curHeight) cache[cacheKey] = info } break@movement } } curRock = curRock.map { it.sum(up) }.toSet() } rockCount++ } return (rocksInCave.map { it.y }.max() + heightFromCycleRepeat + 1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test").first() check(part1(testInput) == 3068L) println(part2(testInput)) val input = readInput("Day17").first() println(part1(input)) println(part2(input)) } fun Point.sum(o: Point) = Point(x + o.x, y + o.y)
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
5,455
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/com/richodemus/advent_of_code/two_thousand_sixteen/day1_taxicab/Main.kt
RichoDemus
75,489,317
false
null
package com.richodemus.advent_of_code.two_thousand_sixteen.day1_taxicab import com.richodemus.advent_of_code.two_thousand_sixteen.toFile fun main(args: Array<String>) { val directions = readDirections() var position = Position() var direction = Direction.NORTH val previousPositions = mutableSetOf(position) var foundPrevLocation = false directions.forEach { direction = direction.turn(it.turn) IntRange(1, it.steps).forEach { position = position.move(direction, 1) if (previousPositions.contains(position) && !foundPrevLocation) { println("Previously visited point: ${position.toAnswer()}") assert(position.toAnswer() == 116) foundPrevLocation = true } previousPositions.add(position) } } println("Answer: ${position.toAnswer()}") assert(position.toAnswer() == 241) } private fun readDirections() = "day1/directions.txt".toFile().readText().toDirections() private fun String.toDirections() = this.split(",").map(String::trim).map { Action(it) } private data class Position(val x: Int = 0, val y: Int = 0) { fun move(direction: Direction, steps: Int): Position { return when (direction) { Direction.NORTH -> Position(x, y + steps) Direction.SOUTH -> Position(x, y - steps) Direction.EAST -> Position(x + steps, y) Direction.WEST -> Position(x - steps, y) } } fun toAnswer() = Math.abs(x) + Math.abs(y) override fun toString(): String { return "Position(x=$x, y=$y)" } } private data class Action(val turn: Turn, val steps: Int) { constructor(raw: String) : this(raw[0].toTurn(), raw.substring(1).toInt()) } private fun Char.toTurn() = if ('R' == this) Turn.RIGHT else Turn.LEFT private enum class Turn { RIGHT, LEFT } private enum class Direction { NORTH { override fun turn(direction: Turn): Direction = if (direction == Turn.RIGHT) EAST else WEST }, SOUTH { override fun turn(direction: Turn): Direction = if (direction == Turn.RIGHT) WEST else EAST }, WEST { override fun turn(direction: Turn): Direction = if (direction == Turn.RIGHT) NORTH else SOUTH }, EAST { override fun turn(direction: Turn): Direction = if (direction == Turn.RIGHT) SOUTH else NORTH }; abstract fun turn(direction: Turn): Direction }
0
Kotlin
0
0
32655174f45808eb1530f00c4c49692310036395
2,449
advent-of-code
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/wildcard_matching/WildcardMatching.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.wildcard_matching import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/wildcard-matching * * Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. * '?' Matches any single character. * '*' Matches any sequence of characters (including the empty sequence). * * The matching should cover the entire input string (not partial). * * Note: * s could be empty and contains only lowercase letters a-z. * p could be empty and contains only lowercase letters a-z, and characters like ? or *. */ class WildcardMatching { @Test fun `some examples`() { isMatch("a", "a") shouldEqual true isMatch("a", "b") shouldEqual false isMatch("aa", "aa") shouldEqual true isMatch("aa", "a") shouldEqual false isMatch("a", "aa") shouldEqual false isMatch("", "*") shouldEqual true isMatch("a", "*") shouldEqual true isMatch("aa", "*") shouldEqual true isMatch("aa", "**") shouldEqual true isMatch("aa", "***") shouldEqual true isMatch("aa", "*a") shouldEqual true isMatch("aa", "a*") shouldEqual true isMatch("aa", "*aa") shouldEqual true isMatch("aa", "a*a") shouldEqual true isMatch("aa", "aa*") shouldEqual true isMatch("aa", "*b") shouldEqual false isMatch("aa", "b*") shouldEqual false isMatch("adceb", "*a*b") shouldEqual true isMatch("a", "?") shouldEqual true isMatch("cb", "?a") shouldEqual false isMatch("acdcb", "a*c?b") shouldEqual false } @Test fun `matchers examples`() { CharMatcher('a').invoke(Match("a")).any { it.isComplete } shouldEqual true SeqMatcher(listOf(CharMatcher('a'))).invoke(Match("a")).any { it.isComplete } shouldEqual true SeqMatcher(listOf(CharMatcher('a'))).invoke(Match("aa")).any { it.isComplete } shouldEqual false } } private data class Match(val s: String, val offset: Int = 0, val isComplete: Boolean = offset >= s.length) private typealias Matcher = (match: Match) -> Sequence<Match> private data class CharMatcher(val char: Char): Matcher { override fun invoke(match: Match) = when { match.isComplete -> emptySequence() match.s[match.offset] == char -> sequenceOf(Match(match.s, match.offset + 1)) else -> emptySequence() } } private data class SeqMatcher(val matchers: List<Matcher>): Matcher { override fun invoke(match: Match) = matchers.fold(sequenceOf(match)) { matches, matcher -> matches.flatMap { matcher.invoke(it) } } } private class QuestionMatcher: Matcher { override fun invoke(match: Match) = if (match.isComplete) emptySequence() else sequenceOf(Match(match.s, match.offset + 1)) } private class StarMatcher: Matcher { override fun invoke(match: Match) = (match.offset..match.s.length).asSequence().map { offset -> Match(match.s, offset) } } private fun isMatch(s: String, pattern: String): Boolean { val matcher = SeqMatcher(pattern.map { when (it) { '*' -> StarMatcher() '?' -> QuestionMatcher() else -> CharMatcher(it) } }) return matcher.invoke(Match(s)).any { match -> match.isComplete } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,431
katas
The Unlicense
src/Year2022Day13.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
import java.util.IdentityHashMap import kotlin.math.min import kotlin.math.sign fun main() { fun parse(line: String): List<Any> { val parentMap = IdentityHashMap<MutableList<Any>, MutableList<Any>?>() var currentList: MutableList<Any>? = null var index = 0 while(index < line.length) { when (line[index]) { '[' -> { val newList = mutableListOf<Any>() parentMap[newList] = currentList currentList?.add(newList ) currentList = newList } ']' -> { currentList = parentMap[currentList] } in '0'..'9' -> { val endIndex = line.indexOfFirst(index) { !it.isDigit() } currentList?.add(line.substring(index, endIndex).toInt()) index = endIndex } ',' -> {} else -> throw IllegalArgumentException() } index++ } return parentMap.firstNotNullOf { (key, value) -> if (value == null) key else null } } fun compare(o1: Any, o2: Any): Int { if (o1 is Int && o2 is Int) return o1.compareTo(o2) val l1 = o1 as? List<*> ?: listOf(o1) val l2 = o2 as? List<*> ?: listOf(o2) for (i in 0 until min(l1.size, l2.size)) { compare(l1[i]!!, l2[i]!!).let { if (it != 0) return it } } return (l1.size - l2.size).sign } fun part1(lines: List<String>): Int { return lines.asSequence() .chunked(2) .map { compare(parse(it[0]), parse(it[1])) <= 0 } .mapIndexed { index, comparison -> if (comparison) index + 1 else 0 } .sum() } fun part2(lines: List<String>): Int { val l = lines.asSequence().filter { it.isNotBlank() }.map { parse(it) }.toMutableList() val l1 = parse("[[2]]") val l2 = parse("[[6]]") l.add(l1) l.add(l2) l.sortWith(::compare) return (l.indexOfFirst { it === l1 } + 1) * (l.indexOfFirst { it === l2 } + 1) } val testLines = readLines(true) assertEquals(13, part1(testLines)) assertEquals(140, part2(testLines)) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
2,366
aoc-2022-in-kotlin
Apache License 2.0
src/Day07.kt
konclave
573,548,763
false
{"Kotlin": 21601}
class Dir( val name: String, ) { var children: MutableList<Dir> = mutableListOf() var parent: Dir? = null var value: Int = 0 set(v) { if (this.parent != null) { this.parent!!.value = v } field += v } constructor(name: String, parent: Dir) : this(name) { parent.children.add(this) this.parent = parent } } fun createTree(input: List<String>): Dir { var node = Dir("/") val root = node input.forEach { val parsed = it.split(" ") if (parsed.size == 3) { val (_, _, path) = parsed when (path) { "/" -> {} ".." -> { node = node.parent!! } else -> { node = node.children.find { child -> child.name == path }!! } } } else { val (prompt, path) = parsed when (prompt) { "$" -> {} "dir" -> { Dir(path, node) } else -> { node.value = prompt.toInt() } } } } return root } fun solve1(root: Dir, sizeLimit: Int): Int { val stack: MutableList<Dir> = mutableListOf() stack.add(root) var total = 0 while(stack.size > 0) { val current = stack.removeLast() if (current.value <= sizeLimit) { total += current.value } if (current.children.size > 0) { current.children.forEach { stack.add(it) } } } return total } fun solve2(root: Dir, total: Int, need: Int): Int { val stack: MutableList<Dir> = mutableListOf() val available = total - root.value stack.add(root) var remove: Dir = root while(stack.size > 0) { val current = stack.removeLast() if (available + current.value >= need && current.value < remove.value) { remove = current } if (current.children.size > 0) { current.children.forEach { stack.add(it) } } } return remove.value } fun main() { val input = readInput("Day07") val root = createTree(input) println(solve1(root, 100000)) println(solve2(root, 70000000, 30000000)) }
0
Kotlin
0
0
337f8d60ed00007d3ace046eaed407df828dfc22
2,338
advent-of-code-2022
Apache License 2.0
src/Day07/Solution.kt
cweinberger
572,873,688
false
{"Kotlin": 42814}
package Day07 import readInput import kotlin.math.max enum class ItemType { File, Directory } sealed class Item( open val name: String, open val parent: Item.Directory?, val type: ItemType ) { data class File( override val name: String, override val parent: Directory?, val size: Int ) : Item(name, parent, ItemType.File) data class Directory( override val name: String, override val parent: Directory?, val items: MutableList<Item> ) : Item(name, parent, ItemType.Directory) } enum class Command { ChangeDirectory, ListDirectory; companion object { fun withString(input: String): Command { return when (input) { "cd" -> ChangeDirectory "ls" -> ListDirectory else -> throw IllegalArgumentException("Unknown input for command '$input'") } } } } fun main() { fun parseCommand(input: String) : Pair<Command, String?> { return input .replace("$ ", "") .split(" ") .let { Pair( Command.withString(it.first()), if (it.size > 1) it.last() else null ) } } fun parseDirectory(input: String, parent: Item.Directory) : Item.Directory { return Item.Directory( input.split(" ").last(), parent, mutableListOf() ) } fun parseFile(input: String, parent: Item.Directory) : Item.File { return Item.File( input.split(" ").last(), parent, input.split(" ").first().toInt() ) } fun createFileSystem(input: List<String>): Item.Directory { var root = Item.Directory("/", null, mutableListOf()) var currentDir = root input.forEach { line -> if (line.startsWith("$")) { val cmd = parseCommand(line) when (cmd.first) { Command.ListDirectory -> return@forEach Command.ChangeDirectory -> { currentDir = when (cmd.second) { "/" -> root ".." -> currentDir.parent ?: root else -> currentDir.items .first { it.type == ItemType.Directory && it.name == cmd.second } as Item.Directory } } } } else if (line.startsWith("dir")) { val dir = parseDirectory(line, currentDir) currentDir.items.add(dir) } else { val file = parseFile(line, currentDir) currentDir.items.add(file) } } return root } fun printDirectory(dir: Item.Directory, prefix: String = "") { dir.items.forEach { item -> when(item) { is Item.Directory -> { println("$prefix - ${item.name}") printDirectory(item, "$prefix ") } is Item.File -> println("$prefix - ${item.name} (${item.size})") } } } fun getDirectorySize(dir: Item.Directory) : Int { return dir.items .filterIsInstance(Item.File::class.java) .sumOf { it.size } .plus( dir.items .filterIsInstance(Item.Directory::class.java) .sumOf { getDirectorySize(it) } ) } fun findDirectories( root: Item.Directory, filter: (Item.Directory) -> Boolean ) : List<Item.Directory> { return root.items .filterIsInstance(Item.Directory::class.java) .mapNotNull { if (filter(it)) { listOf(it) + findDirectories(it, filter) } else { findDirectories(it, filter) } } .flatten() } fun part1(input: List<String>): Int { val fs = createFileSystem(input) return findDirectories(fs) { getDirectorySize(it) <= 100000 } .sumOf { getDirectorySize(it) } } fun part2(input: List<String>): Int { val fs = createFileSystem(input) val totalSize = getDirectorySize(fs) val requiredSpace = 30000000 val diskSpace = 70000000 val spaceToFreeUp = requiredSpace - (diskSpace - totalSize) println("Disk usage: $totalSize of $diskSpace\n" + "Space to free up: $spaceToFreeUp") return findDirectories(fs) { getDirectorySize(it) >= spaceToFreeUp } .map { getDirectorySize(it) } .minOf { it } } val testInput = readInput("Day07/TestInput") val input = readInput("Day07/Input") println("\n=== Part 1 - Test Input ===") println(part1(testInput)) println("\n=== Part 1 - Final Input ===") println(part1(input)) println("\n=== Part 2 - Test Input ===") println(part2(testInput)) println("\n=== Part 2 - Final Input ===") println(part2(input)) }
0
Kotlin
0
0
883785d661d4886d8c9e43b7706e6a70935fb4f1
5,285
aoc-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day19/day19.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day19 import biz.koziolek.adventofcode.* import kotlin.math.absoluteValue fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val scanners = parseScannerReport(lines) val allBeacons = findAllBeaconsRelativeTo0(scanners) println("There are ${allBeacons.size} beacons") val maxDistance = findMaxScannerDistance(scanners) println("Max distance between two scanners is: $maxDistance") } fun parseScannerReport(lines: Iterable<String>): List<RandomScanner> = buildList { var beacons: MutableSet<Coord3d>? = null for (line in lines) { if (line.startsWith("--- scanner")) { if (beacons != null) { add(RandomScanner(beacons)) } beacons = mutableSetOf() } else if (line.isNotBlank()) { beacons?.add(Coord3d.fromString(line)) } } if (beacons != null) { add(RandomScanner(beacons)) } } interface Scanner { val beacons: Set<Coord3d> fun distanceToAllBeacons(from: Coord3d): Set<Double> = beacons.map { from.distanceTo(it) }.toSet() } data class RandomScanner(override val beacons: Set<Coord3d>) : Scanner { fun normalize(scannerRotation: Rotation, scannerCoord: Coord3d): NormalizedScanner { return NormalizedScanner( position = scannerCoord, beacons = beacons.map { it.rotate(scannerRotation) + scannerCoord }.toSet(), ) } } data class NormalizedScanner(val position: Coord3d, override val beacons: Set<Coord3d>) : Scanner fun findMaxScannerDistance(scanners: List<RandomScanner>): Int { val normalizedScanners = matchScanners(scanners) return sequence { for (scannerA in normalizedScanners) { for (scannerB in normalizedScanners) { yield(scannerA to scannerB) } } }.maxOf { it.first.position.manhattanDistanceTo(it.second.position) } } fun findAllBeaconsRelativeTo0(scanners: List<RandomScanner>): Set<Coord3d> = matchScanners(scanners) .flatMap { it.beacons } .toSet() fun matchScanners(scanners: List<RandomScanner>): List<NormalizedScanner> { val normalizedScanners: MutableList<NormalizedScanner?> = scanners.map { null }.toMutableList() normalizedScanners[0] = scanners[0].normalize(Rotation("+x", "+y", "+z"), Coord3d(0, 0, 0)) while (normalizedScanners.any { it == null }) { var matchedAnythingThisIteration = false for ((scannerToMatchIndex, scannerToMatch) in scanners.withIndex()) { if (normalizedScanners[scannerToMatchIndex] != null) { // Already matched continue } for (normalizedScanner in normalizedScanners) { if (normalizedScanner == null) { // Not yet matched and normalized continue } val sameCoords = findSameCoords(normalizedScanner, scannerToMatch) if (sameCoords.isNotEmpty()) { val rotation = findSecondScannerRotation(sameCoords) val scannerCenter = findSecondScannerCoordRelativeToFirst(sameCoords) normalizedScanners[scannerToMatchIndex] = scannerToMatch.normalize(rotation, scannerCenter) matchedAnythingThisIteration = true break } } } if (!matchedAnythingThisIteration) { val stillUnmatchedIndexes = scanners.indices.filter { index -> normalizedScanners[index] == null } throw IllegalStateException("Cannot match scanners: $stillUnmatchedIndexes") } } return normalizedScanners.filterNotNull() } fun findSameCoords(scannerA: Scanner, scannerB: Scanner, minInCommon: Int = 12): Map<Coord3d, Coord3d> { val distancesA = scannerA.beacons.associateWith { scannerA.distanceToAllBeacons(it) } val distancesB = scannerB.beacons.associateWith { scannerB.distanceToAllBeacons(it) } return buildMap { for ((beaconA, thisDistancesA) in distancesA.entries) { for ((beaconB, thisDistancesB) in distancesB.entries) { val inCommon = thisDistancesA.intersect(thisDistancesB) if (inCommon.size >= minInCommon) { put(beaconA, beaconB) } } } } } fun findSecondScannerCoordRelativeToFirst(sameCoords: Map<Coord3d, Coord3d>): Coord3d { val scannerBRotation = findSecondScannerRotation(sameCoords) return sameCoords .map { (a, b) -> a to b.rotate(scannerBRotation) } .map { it.first - it.second } .distinct() .single() } private fun Coord3d.rotate(rotation: Rotation) = Coord3d( x = rotateSingle(this, rotation.x), y = rotateSingle(this, rotation.y), z = rotateSingle(this, rotation.z), ) private fun rotateSingle(coord3d: Coord3d, singleRotation: String): Int = when (singleRotation) { "+x" -> coord3d.x "-x" -> -coord3d.x "+y" -> coord3d.y "-y" -> -coord3d.y "+z" -> coord3d.z "-z" -> -coord3d.z else -> throw IllegalArgumentException("Unknown rotation: $singleRotation") } private fun findSingleRotation(singleAxisValue: Int, otherCoord: Coord3d): String = when (singleAxisValue) { otherCoord.x -> "+x" -otherCoord.x -> "-x" otherCoord.y -> "+y" -otherCoord.y -> "-y" otherCoord.z -> "+z" -otherCoord.z -> "-z" else -> throw IllegalArgumentException("Cannot find single rotation - $singleAxisValue was not found in $otherCoord") } data class Rotation(val x: String, val y: String, val z: String) fun findSecondScannerRotation(sameCoords: Map<Coord3d, Coord3d>): Rotation = sameCoords.entries.asSequence() .zipWithNext() .map { (prev, next) -> val (prevA, prevB) = prev val (nextA, nextB) = next val vectorA = prevA - nextA val vectorB = prevB - nextB vectorA to vectorB } .filter { (vectorA, vectorB) -> val absValuesA = setOf(vectorA.x.absoluteValue, vectorA.y.absoluteValue, vectorA.z.absoluteValue) val absValuesB = setOf(vectorB.x.absoluteValue, vectorB.y.absoluteValue, vectorB.z.absoluteValue) absValuesA == absValuesB } .map { (vectorA, vectorB) -> val rotationX = findSingleRotation(vectorA.x, vectorB) val rotationY = findSingleRotation(vectorA.y, vectorB) val rotationZ = findSingleRotation(vectorA.z, vectorB) Rotation(rotationX, rotationY, rotationZ) } .groupBy { it } .map { it.key to it.value.size } .sortedByDescending { it.second } .map { it.first } .take(1) .first()
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
7,017
advent-of-code
MIT License
src/Day09.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
import kotlin.math.abs //enum class Move(val y: Int, val x: Int) { // Left(0, -1), // Right(0, 1), // Up(1, 0), // Down(-1, 0) //} class Coordinate( var x: Int = 0, var y: Int = 0) { operator fun plus(increment: Coordinate): Coordinate = Coordinate(x + increment.x, y + increment.y) operator fun minus(increment: Coordinate) = Coordinate(x - increment.x, y - increment.y) override fun hashCode(): Int = (x to y).hashCode() override fun equals(other: Any?): Boolean { if (other !is Coordinate) return false return x == other.x && y == other.y } } class Positions(val sizeOfTail: Int = 1) { var curH = Coordinate() val curT: Array<Coordinate> init { curT = Array(sizeOfTail, {_ -> Coordinate()}) } val set = hashSetOf(curT.last()) fun isClose(a: Coordinate, b: Coordinate): Boolean { return (abs(a.x - b.x) <= 1 && abs(a.y - b.y) <= 1 ) } fun moveH(dir: String) { curH += when (dir) { "U" -> Coordinate(0, 1) "D" -> Coordinate(0, -1) "L" -> Coordinate(-1, 0) "R" -> Coordinate(1, 0) else -> error("") } } fun moveT() { for (index in 0 until sizeOfTail) { val prev = if (index == 0) curH else curT[index - 1] if (!isClose(prev, curT[index])) { val delta = prev - curT[index] if (abs(delta.x) == 2) delta.x /= 2 if (abs(delta.y) == 2) delta.y /= 2 curT[index] += delta } } set.add(curT.last()) } } fun main() { fun part1(input: List<String>): Int { val positions = Positions() input.forEach { line -> val (dir, steps) = line.split(" ") repeat(steps.toInt()) { positions.moveH(dir) positions.moveT() } } return positions.set.size } fun part2(input: List<String>): Int { val positions = Positions(9) input.forEach { line -> val (dir, steps) = line.split(" ") repeat(steps.toInt()) { positions.moveH(dir) positions.moveT() } } return positions.set.size } val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
2,703
AdventOfCode
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2023/Day10.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2023 import se.saidaspen.aoc.util.* fun main() = Day10.run() object Day10 : Day(2023, 10) { private val map : MutableMap<P<Int, Int>, Char> = toMap(input) private val startPos = map.entries.first { it.value == 'S' }.key private var neighbours = mapOf( '|' to listOf(P(0, 1), P(0, -1)), '-' to listOf(P(1, 0), P(-1, 0)), 'F' to listOf(P(1, 0), P(0, 1)), '7' to listOf(P(-1, 0), P(0, 1)), 'L' to listOf(P(1, 0), P(0, -1)), 'J' to listOf(P(-1, 0), P(0, -1)), ) override fun part1(): Any { // Hardcoded start position map[startPos] = '7' return findEdges().size / 2 } override fun part2(): Any { val verticalCrossings = listOf('|', 'J', 'L') val edges = findEdges() val notInLoop = map.entries.filter { !edges.contains(it.key) } notInLoop.map { it.key }.forEach{ map[it] = '.'} return notInLoop // Map to the number of vertical pipes to the left .map { e -> (0 until e.key.first).count { verticalCrossings.contains(map[P(it, e.key.second)]) } } // If it is odd, it must be inside, I think! .count { it % 2 != 0 } } private fun findEdges(): Set<P<Int, Int>> { data class State(val path: P<P<Int, Int>, P<Int, Int>>, val dist: Int) var curr = State(P(startPos, startPos + P(0, 1)), 1) val edges = mutableSetOf<P<Int, Int>>() edges.add(curr.path.first) while (curr.path.second != startPos) { edges.add(curr.path.second) val next = neighbours[map[curr.path.second]]!! .map { it + curr.path.second } .filter { map.containsKey(it) } .first { it != curr.path.first } curr = State(P(curr.path.second, next), curr.dist + 1) } return edges } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,906
adventofkotlin
MIT License
dcp_kotlin/src/test/kotlin/dcp/day307/day307.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day307 // day307.kt // By <NAME>, 2020. import io.kotlintest.properties.Gen import io.kotlintest.properties.forAll import io.kotlintest.specs.StringSpec // Find the floor of an element in a sorted list. We will use this in testing. fun List<Int>.floor(x: Int): Int? = when { isEmpty() || first() > x -> null else -> drop(1).floor(x) ?: first() } // Find the ceil of an element in a sorted list. We will use this in testing. fun List<Int>.ceil(x: Int): Int? = when { isEmpty() || last() < x -> null else -> dropLast(1).ceil(x) ?: last() } // To make a Gen<BinarySearchTree>. class MutableBinarySearchTree(val value: Int, var left: MutableBinarySearchTree?, var right: MutableBinarySearchTree?) { fun insert(x: Int) { when { x < value && left == null -> left = MutableBinarySearchTree(x, null, null) x < value && left != null -> left!!.insert(x) x > value && right == null -> right = MutableBinarySearchTree(x, null, null) x > value && right != null -> right!!.insert(x) else -> Unit } } fun toBinarySearchTree(): BinarySearchTree = BinarySearchTree(value, if (left == null) null else left!!.toBinarySearchTree(), if (right == null) null else right!!.toBinarySearchTree()) } // A generator for binary search trees. class BinarySearchTreeGen: Gen<BinarySearchTree> { override fun constants(): Iterable<BinarySearchTree> = listOf(BinarySearchTree(0, null, null)) override fun random(): Sequence<BinarySearchTree> = generateSequence { val size = Gen.choose(1, 100).random().first() val list = Gen.choose(0, 1000).random().take(size) val msb = MutableBinarySearchTree(list.first(), null, null) (1 until size).forEach(msb::insert) msb.toBinarySearchTree() } } class PropertyTests: StringSpec() { init { "Make sure floor and ceil coincide for lists and trees" { forAll(BinarySearchTreeGen()) { t -> val values = t.values() (0 until 1000).all { Triple(it, t.floor(it), t.ceil(it)) == Triple(it, values.floor(it), values.ceil(it)) } } } } }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
2,233
daily-coding-problem
MIT License
src/Day02.kt
nGoldi
573,158,084
false
{"Kotlin": 6839}
fun main() { fun part1(input: List<String>): Int { return input.fold(mutableListOf(0)) { acc, s -> when (s) { "A Y" -> acc[acc.lastIndex] = 6 + 2 + acc.last() "A X" -> acc[acc.lastIndex] = 3 + 1 + acc.last() "A Z" -> acc[acc.lastIndex] = 0 + 3 + acc.last() "B Y" -> acc[acc.lastIndex] = 3 + 2 + acc.last() "B X" -> acc[acc.lastIndex] = 0 + 1 + acc.last() "B Z" -> acc[acc.lastIndex] = 6 + 3 + acc.last() "C Y" -> acc[acc.lastIndex] = 0 + 2 + acc.last() "C X" -> acc[acc.lastIndex] = 6 + 1 + acc.last() "C Z" -> acc[acc.lastIndex] = 3 + 3 + acc.last() else -> acc.add(0) } acc }.sum() } fun part2(input: List<String>): Int { return input.fold(mutableListOf(0)) { acc, s -> when (s) { "A X" -> acc[acc.lastIndex] = 0 + 3 + acc.last() "A Y" -> acc[acc.lastIndex] = 3 + 1 + acc.last() "A Z" -> acc[acc.lastIndex] = 6 + 2 + acc.last() "B X" -> acc[acc.lastIndex] = 0 + 1 + acc.last() "B Y" -> acc[acc.lastIndex] = 3 + 2 + acc.last() "B Z" -> acc[acc.lastIndex] = 6 + 3 + acc.last() "C X" -> acc[acc.lastIndex] = 0 + 2 + acc.last() "C Y" -> acc[acc.lastIndex] = 3 + 3 + acc.last() "C Z" -> acc[acc.lastIndex] = 6 + 1 + acc.last() else -> acc.add(0) } acc }.sum() } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bc587f433aa38c4d745c09d82b7d231462f777c8
1,691
advent-of-code
Apache License 2.0
classroom/src/main/kotlin/com/radix2/algorithms/week1/UnionFind.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week1 interface UF { fun union(p: Int, q: Int) fun connected(p: Int, q: Int): Boolean } class QuickFindUF(size: Int) : UF { private val ids: IntArray = IntArray(size) { it } override fun connected(p: Int, q: Int): Boolean = ids[p] == ids[q] override fun union(p: Int, q: Int) { val pId = ids[p] val qId = ids[q] for (i in 0 until ids.size) { if (ids[i] == pId) { ids[i] = qId } } } } open class QuickUnionUF(size: Int) : UF { protected val ids: IntArray = IntArray(size) { it } override fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) ids[pRoot] = qRoot } override fun connected(p: Int, q: Int): Boolean = root(p) == root(q) protected open fun root(p: Int): Int { var i = p while (i != ids[i]) { i = ids[i] } return i } } open class WeightedQuickUnionUF(size: Int) : QuickUnionUF(size) { protected val size: IntArray = IntArray(size) { 1 } override fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) if (pRoot == qRoot) return if (size[pRoot] < size[qRoot]) { ids[pRoot] = ids[qRoot] size[qRoot] += size[pRoot] } else { ids[qRoot] = ids[pRoot] size[pRoot] += size[qRoot] } } } class WeightedQuickUnionWithPathCompressionUF(size: Int) : WeightedQuickUnionUF(size) { override fun root(p: Int): Int { var i = p while (i != ids[i]) { ids[i] = ids[ids[i]] i = ids[i] } return i } } fun main(args: Array<String>) { val uf = WeightedQuickUnionWithPathCompressionUF(10) uf.union(4, 3) uf.union(3, 8) uf.union(6, 5) uf.union(9, 4) uf.union(2, 1) uf.union(5, 0) uf.union(7, 2) uf.union(6, 1) uf.union(7, 3) //println(uf.find(3)) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
2,014
coursera-algorithms-part1
Apache License 2.0
src/day16/Day16.kt
armanaaquib
572,849,507
false
{"Kotlin": 34114}
package day16 import readInput import kotlin.math.max data class Data(val valves: MutableMap<String, List<String>> = mutableMapOf(), val rates: MutableMap<String, Int> = mutableMapOf()) fun main() { fun parseInput(input: List<String>) = input.fold(Data()) { data, line -> val sl = line.split(" ") val name = sl[1] val rate = sl[4].removePrefix("rate=").removeSuffix(";").toInt() val valves = sl.slice(9..sl.lastIndex).map { it.removeSuffix(",") } data.valves[name] = valves data.rates[name] = rate data } fun findMaxPressureRelease( valves: MutableMap<String, List<String>>, rates: MutableMap<String, Int>, valve: String, minutes: Int, openedValves: MutableSet<String> ): Int { if (minutes <= 0) return 0 var newMinutes = minutes var pressure = 0 val rate = rates[valve]!! if (rate != 0 && !openedValves.contains(valve)) { newMinutes-- pressure = rate * newMinutes openedValves.add(valve) } else { openedValves.add(valve) } var maxPressure = 0 for (v in valves[valve]!!) { maxPressure = max(maxPressure, findMaxPressureRelease(valves, rates, v, newMinutes - 1, openedValves)) } return pressure + maxPressure } fun part1(input: List<String>): Int { val data = parseInput(input) val valves = data.valves val rates = data.rates val pressureRelease = findMaxPressureRelease(valves, rates, "AA", 30, mutableSetOf()) return pressureRelease } // fun part2(input: List<String>): Int { // val data = parseInput(input) // // return 0 // } // test if implementation meets criteria from the description, like: check(part1(readInput("Day16_test")) == 1651) println(part1(readInput("Day16"))) // check(part2(readInput("Day01_test")) == 45000) // println(part2(readInput("Day01"))) }
0
Kotlin
0
0
47c41ceddacb17e28bdbb9449bfde5881fa851b7
2,032
aoc-2022
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day05.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
package de.niemeyer.aoc2022 /** * Advent of Code 2022, Day 5: Supply Stacks * Problem Description: https://adventofcode.com/2022/day/5 */ import de.niemeyer.aoc.utils.Resources.resourceAsText import de.niemeyer.aoc.utils.getClassName typealias CrateStacks = List<ArrayDeque<Char>> data class Move(val number: Int, val source: Int, val target: Int) typealias Moves = List<Move> val inputMoveLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() fun String.toMove(): Move { val (number, source, target) = inputMoveLineRegex .matchEntire(this) ?.destructured ?: throw IllegalArgumentException("Incorrect move input line $this") return Move(number.toInt(), source.toInt(), target.toInt()) } fun parseInput(input: String): Pair<CrateStacks, Moves> { val (cratesLines, moveLines) = input.split("\n\n") val maxStack = cratesLines.trim().last().digitToInt() val crateStacks = List<ArrayDeque<Char>>(maxStack) { ArrayDeque() } cratesLines.lines().dropLast(1).forEach { line -> (0..(maxStack - 1)).forEach { stack -> val crate = line.getOrNull(stack * 4 + 1) if (crate != ' ' && crate != null) crateStacks[stack].addFirst(crate) } } val moves = moveLines.trim().lines().map { it.toMove() } return crateStacks to moves } fun main() { fun part1(input: String): String { val (crateStacks, moves) = parseInput(input) moves.forEach { (number, source, target) -> repeat(number) { crateStacks[target - 1] += crateStacks[source - 1].removeLast() } } return crateStacks.map { it.last() }.joinToString("") } fun part2(input: String): String { val (crateStacks, moves) = parseInput(input) moves.forEach { (number, source, target) -> val movingCrates = ArrayDeque<Char>() repeat(number) { movingCrates += crateStacks[source - 1].removeLast() } crateStacks[target - 1].addAll(movingCrates.reversed()) } return crateStacks.map { it.last() }.joinToString("") } val name = getClassName() val testInput = resourceAsText(fileName = "${name}_test.txt") val puzzleInput = resourceAsText(fileName = "${name}.txt") check(part1(testInput) == "CMZ") println(part1(puzzleInput)) check(part1(puzzleInput) == "TDCHVHJTG") check(part2(testInput) == "MCD") println(part2(puzzleInput)) check(part2(puzzleInput) == "NGCMPJLHV") }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,529
AoC-2022
Apache License 2.0
src/test/kotlin/icfp2019/TestUtils.kt
teemobean
193,117,049
true
{"JavaScript": 797310, "Kotlin": 129405, "CSS": 9434, "HTML": 5859, "Shell": 70}
package icfp2019 import com.google.common.base.CharMatcher import com.google.common.base.Splitter import icfp2019.model.* import org.pcollections.PVector import org.pcollections.TreePVector import java.nio.file.Paths fun String.toProblem(): Problem { return parseTestMap(this) } fun GameState.toProblem(): Problem { val nodes = this.board().map { it.map { cell -> val state = this.nodeState(cell.point) Node( cell.point, isObstacle = cell.isObstacle, isWrapped = state.isWrapped, hasTeleporterPlanted = cell.hasTeleporterPlanted, booster = state.booster ) } } val grid = TreePVector.from<PVector<Node>>(nodes.map { TreePVector.from(it) }) return Problem(name = "result", size = this.mapSize, startingPosition = this.startingPoint, map = grid) } fun loadProblem(problemNumber: Int): String { val path = Paths.get("problems/prob-${problemNumber.toString().padStart(3, padChar = '0')}.desc").toAbsolutePath() return path.toFile().readText() } fun boardString(problem: Problem, path: Set<Point> = setOf()): String = boardString(problem.map, problem.size, problem.startingPosition, path) fun boardString(cells: List<List<Node>>, size: MapSize, startingPosition: Point, path: Set<Point> = setOf()): String { val lines = mutableListOf<String>() for (y in (size.y - 1) downTo 0) { val row = (0 until size.x).map { x -> val node = cells[x][y] when { node.hasTeleporterPlanted -> '*' node.isWrapped -> 'w' startingPosition == Point(x, y) -> '@' node.isObstacle -> 'X' node.point in path -> '|' node.booster != null -> 'o' else -> '.' } }.joinToString(separator = " ") lines.add(row) } return lines.joinToString(separator = "\n") } fun printBoard(p: Problem, path: Set<Point> = setOf()) { println("${p.size}") print(boardString(p.map, p.size, p.startingPosition, path)) println() } fun printBoard(state: GameState, path: Set<Point> = setOf()) { printBoard(state.toProblem(), path) } fun parseTestMap(map: String): Problem { val mapLineSplitter = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings() val lines = mapLineSplitter.splitToList(map) .map { CharMatcher.whitespace().removeFrom(it) } .filter { it.isBlank().not() } .reversed() val height = lines.size val width = lines[0].length if (lines.any { it.length != width }) throw IllegalArgumentException("Inconsistent map line lengths") val startPoint = (0 until width).map { x -> (0 until height).map { y -> if (lines[y][x] == '@') Point(x, y) else null } }.flatten().find { it != null } ?: Point.origin() return Problem("Test", MapSize(width, height), startPoint, TreePVector.from((0 until width).map { x -> TreePVector.from((0 until height).map { y -> val point = Point(x, y) when (val char = lines[y][x]) { 'X' -> Node(point, isObstacle = true) 'w' -> Node(point, isObstacle = false, isWrapped = true) '.' -> Node(point, isObstacle = false) '@' -> Node(point, isObstacle = false) '*' -> Node(point, isObstacle = false, hasTeleporterPlanted = true, isWrapped = true) in Booster.parseChars -> Node(point, isObstacle = false, booster = Booster.fromChar(char)) else -> throw IllegalArgumentException("Unknown Char '$char'") } }) })) }
0
JavaScript
0
0
afcf5123ffb72ac10cfa6b0772574d9826f15e41
3,777
icfp-2019
The Unlicense
day-06/src/main/kotlin/Lanternfish.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") } private fun partOne(): Int { val fishes = readFishes() .toMutableList() for (day in 1..80) { val newFishes = mutableListOf<Fish>() fishes.forEach { fish -> fish.ageByOne()?.let { newFishes.add(it) } } fishes.addAll(newFishes) } return fishes.size } private fun partTwo(): Long { val fishes = readFishes() val fishTimers = LongArray(10) { 0 } fishes.forEach { fishTimers[it.timer] += 1L } for (day in 1..256) { for (i in fishTimers.indices) { if (i == 0) { // Adding to position 9 and 7 because they'll be processed in this loop and moved to the right positions fishTimers[9] += fishTimers[0] fishTimers[7] += fishTimers[0] fishTimers[0] = 0 } else { fishTimers[i - 1] += fishTimers[i] fishTimers[i] = 0 } } } return fishTimers.sum() } private fun readFishes() = readInputLines()[0] .split(",") .map { Fish(it.toInt()) } data class Fish( var timer: Int ) { fun ageByOne(): Fish? { return if (timer == 0) { timer = 6 Fish(8) } else { timer -= 1 null } } } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt") .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
1,643
aoc-2021
MIT License
src/Day05.kt
acunap
573,116,784
false
{"Kotlin": 23918}
import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { fun parseCrates(input: List<String>): MutableList<MutableList<String>> { return input.map { row -> row.chunked(4).map { it.trim().replace("[\\[\\]]".toRegex(), "") } } .dropLast(1) .reversed() .let { crates -> val transposed = MutableList<MutableList<String>>(crates.first().size) { mutableListOf() } crates.forEach { strings -> strings.forEachIndexed { index, s -> transposed[index].add(s) } } transposed.map { row -> row.filter { !it.isNullOrEmpty() } } as MutableList<MutableList<String>> } } fun parseMoves(input: List<String>): List<List<Int>> { val regex = "(\\d+)".toRegex() return input.map { regex.findAll(it) .map { matches -> matches.value.toInt() } .mapIndexed { index, i -> if (index != 0) i - 1 else i } .toList() } } fun part1(input: String): String { val parsedData = input.split("\n\n").map { it.lines() } val crates = parseCrates(parsedData[0]) val moves = parseMoves(parsedData[1]) moves.forEach { (move, from, to) -> (1..move).forEach { _ -> val moved = crates[from].removeLast() if (!moved.isNullOrEmpty()) { crates[to].add(moved) } } } return crates.joinToString("") { it.last() } } fun part2(input: String): String { val parsedData = input.split("\n\n").map { it.lines() } val crates = parseCrates(parsedData[0]) val moves = parseMoves(parsedData[1]) moves.forEach { (move, from, to) -> val moved = mutableListOf<String>() (1..move).forEach { _ -> moved.add(crates[from].removeLast()) } crates[to].addAll(moved.reversed()) } return crates.joinToString("") { it.last() } } val time = measureTime { val input = readText("Day05") println(part1(input)) println(part2(input)) } println("Real data time $time") val timeTest = measureTime { val testInput = readText("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") } println("Test data time $timeTest.") }
0
Kotlin
0
0
f06f9b409885dd0df78f16dcc1e9a3e90151abe1
2,697
advent-of-code-2022
Apache License 2.0
src/day24/Day24.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day24 import readInputString import java.lang.Math.abs import java.util.PriorityQueue import kotlin.system.measureNanoTime enum class Direction { UP, DOWN, LEFT, RIGHT } data class Blizzard(var x: Int, var y: Int, var dir: Direction) data class Point(var x: Int, var y: Int) fun main() { var maxX = 0 var maxY = 0 fun moveBlizzards(blizzards: List<Blizzard>) { for (blizzard in blizzards) { var nextX = blizzard.x var nextY = blizzard.y when (blizzard.dir) { Direction.LEFT -> nextX-- Direction.UP -> nextY-- Direction.RIGHT -> nextX++ Direction.DOWN -> nextY++ } if (nextX == 0) nextX = maxX if (nextX > maxX) nextX = 1 if (nextY == 0) nextY = maxY if (nextY > maxY) nextY = 1 blizzard.x = nextX blizzard.y = nextY } } // List of squares it's safe to stand on by turn val safetySquares = hashMapOf<Int, MutableList<Point>>() var safetyTurn = 0 fun incrementSafetySquares(blizzards: List<Blizzard>) { moveBlizzards(blizzards) safetyTurn++ val newSquares = mutableListOf<Point>() for (y in 1..maxY) { for (x in 1..maxX) { if (blizzards.filter { it.x == x && it.y == y }.count() == 0) { newSquares.add(Point(x, y)) } } } safetySquares[safetyTurn] = newSquares } fun printBlizzards(blizzards: List<Blizzard>) { for (y in 1..maxY) { for (x in 1..maxX) { val count = blizzards.filter { it.x == x && it.y == y}.count() if (count > 1) print(count) else if (count == 1) { val blizzard = blizzards.find { it.x == x && it.y == y}!! print(when (blizzard.dir) { Direction.UP -> '^' Direction.DOWN -> 'v' Direction.RIGHT -> '>' Direction.LEFT -> '<' }) } else { print('.') } } println() } println() } fun findPathBfs (blizzards: List<Blizzard>, x: Int, y: Int, goalX: Int, goalY: Int, turn: Int): Int { // val q = PriorityQueue<Triple<Int, Int, Int>> { t1, t2 -> (t1.third - t2.third) * 1_000 + t2.first + t2.second - t1.first - t1.second } val q = PriorityQueue<Triple<Int, Int, Int>> { t1, t2 -> (t1.third + abs(t1.first - goalX) + abs(t1.second - goalY)) - (t2.third + abs(t2.first - goalX) + abs(t2.second - goalY)) } q.add(Triple(x, y, turn)) var maxTurn = turn - 1 while (q.isNotEmpty()) { val next = q.remove() q.removeAll { it == next } if (next.third > maxTurn) { maxTurn = next.third // println("Turn $maxTurn - Queue size ${q.size} - Safety size ${safetySquares.values.sumOf { it.size }} - First X,Y ${next.first}, ${next.second}") } if (next.first == goalX && next.second == goalY) return next.third + 1 // Add safety squares if we don't have them while (safetySquares[maxTurn + 1] == null) { incrementSafetySquares(blizzards) } // If we can move a direction next turn // RIGHT if (safetySquares[next.third + 1]?.contains(Point(next.first + 1, next.second)) == true) q.add(Triple(next.first + 1, next.second, next.third + 1)) // DOWN if (safetySquares[next.third + 1]?.contains(Point(next.first, next.second + 1)) == true) q.add(Triple(next.first, next.second + 1, next.third + 1)) // LEFT if (safetySquares[next.third + 1]?.contains(Point(next.first - 1, next.second)) == true) q.add(Triple(next.first - 1, next.second, next.third + 1)) // UP if (safetySquares[next.third + 1]?.contains(Point(next.first, next.second - 1)) == true) q.add(Triple(next.first, next.second - 1, next.third + 1)) // WAIT if (safetySquares[next.third + 1]?.contains(Point(next.first, next.second)) == true || (next.first == x && next.second == y)) q.add(Triple(next.first, next.second, next.third + 1)) } return Int.MIN_VALUE } fun part1(input: List<String>): Int { safetyTurn = 0 safetySquares.clear() val blizzards = mutableListOf<Blizzard>() for (y in input.indices) { val line = input[y] for (x in line.indices) { when (line[x]) { '<' -> blizzards.add(Blizzard(x, y, Direction.LEFT)) '^' -> blizzards.add(Blizzard(x, y, Direction.UP)) '>' -> blizzards.add(Blizzard(x, y, Direction.RIGHT)) 'v' -> blizzards.add(Blizzard(x, y, Direction.DOWN)) } } } maxX = input[0].length - 2 maxY = input.size - 2 val min = findPathBfs( blizzards = blizzards, x = 1, y = 0, goalX = maxX, goalY = maxY, 0 ) return min } fun part2(input: List<String>): Int { safetyTurn = 0 safetySquares.clear() val blizzards = mutableListOf<Blizzard>() for (y in input.indices) { val line = input[y] for (x in line.indices) { when (line[x]) { '<' -> blizzards.add(Blizzard(x, y, Direction.LEFT)) '^' -> blizzards.add(Blizzard(x, y, Direction.UP)) '>' -> blizzards.add(Blizzard(x, y, Direction.RIGHT)) 'v' -> blizzards.add(Blizzard(x, y, Direction.DOWN)) } } } maxX = input[0].length - 2 maxY = input.size - 2 var min = findPathBfs( blizzards = blizzards, x = 1, y = 0, goalX = maxX, goalY = maxY, turn = 0 ) min = findPathBfs( blizzards = blizzards, x = maxX, y = maxY + 1, goalX = 1, goalY = 1, turn = min ) min = findPathBfs( blizzards = blizzards, x = 1, y = 0, goalX = maxX, goalY = maxY, turn = min ) return min } val testInput = readInputString("day24/test") val input = readInputString("day24/input") check(part1(testInput) == 18) val time1 = measureNanoTime { println(part1(input)) } println("Time for part 1 was ${"%,d".format(time1)} ns") check(part2(testInput) == 54) val time2 = measureNanoTime { println(part2(input)) } println("Time for part 2 was ${"%,d".format(time2)} ns") }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
7,199
Advent-Of-Code-2022
Apache License 2.0
day13/src/main/kotlin/aoc2015/day13/Day13.kt
sihamark
581,653,112
false
{"Kotlin": 263428, "Shell": 467, "Batchfile": 383}
package aoc2015.day13 import aoc2015.utility.allPermutations object Day13 { private val effects by lazy { Effects(input.map { Parser.parse(it) }) } fun calculateHighestEffectWithYou() = (effects.persons + Effects.YOU).calculateHighestHappiness() fun calculateHighestEffectWithoutYou() = effects.persons.calculateHighestHappiness() private fun List<String>.calculateHighestHappiness(): Int { if (this.isEmpty()) error("need at least one element") val allSeatingArrangements = this .allPermutations() .map { SeatingArrangement(it) } return allSeatingArrangements.map { it.calculateHappiness(effects) } .max()!! } data class SeatingEffect( val person: String, val neighbor: String, val effect: Int ) data class SeatingArrangement( private val persons: List<String> ) { private fun get(index: Int): String { val adjusted = index.rem(persons.size) .let { if (it >= 0) it else persons.size + it } return persons[adjusted] } fun calculateHappiness(effects: Effects): Int = persons.mapIndexed { index: Int, person: String -> effects[person, get(index - 1)] + effects[person, get(index + 1)] }.sum() } class Effects( private val effects: List<SeatingEffect> ) { val persons get() = effects.flatMap { listOf(it.person, it.neighbor) }.distinct() operator fun get(person: String, neighbor: String) = if (person == YOU || neighbor == YOU) { 0 } else { effects .find { it.person == person && it.neighbor == neighbor } ?.effect ?: error("did not find effect for person $person and neighbor $neighbor") } companion object { const val YOU = "you" } } object Parser { private val validEffect = Regex("""(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)\.""") fun parse(rawEffect: String): SeatingEffect { val parsedValues = validEffect.find(rawEffect)?.groupValues ?: error("invalid effect: $rawEffect") val signum = if (parsedValues[2] == "gain") 1 else -1 return SeatingEffect( parsedValues[1], parsedValues[4], signum * parsedValues[3].toInt() ) } } }
0
Kotlin
0
0
6d10f4a52b8c7757c40af38d7d814509cf0b9bbb
2,523
aoc2015
Apache License 2.0
advent-of-code-2022/src/main/kotlin/year_2022/Day15.kt
rudii1410
575,662,325
false
{"Kotlin": 37749}
package year_2022 import util.Pos2 import util.Runner import util.Triangle import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign fun main() { /* Part 1 */ fun part1(input: List<String>): Int { var xRange = Pair(Int.MAX_VALUE, Int.MIN_VALUE) val rowPos = 2_000_000 input.map { r -> r.split('=', ',', ':') .mapNotNull { it.toIntOrNull() } .chunked(2) .map { Pos2(it[0], it[1]) } .let { val delta = abs(it[0].x - it[1].x) + abs(it[0].y - it[1].y) val y = delta - abs(it[0].y - rowPos) xRange = Pair( min(xRange.first, it[0].x - y), max(xRange.second, it[0].x + y) ) } } return xRange.second - xRange.first } Runner.run(::part1) /* Part 2 */ fun createTriangles(signal: Pos2, size: Int): List<Triangle> { return listOf( Triangle(Pos2(signal.x - size, signal.y), Pos2(signal.x, signal.y - size), Pos2(signal.x + size, signal.y)), Triangle(Pos2(signal.x - size, signal.y), Pos2(signal.x, signal.y + size), Pos2(signal.x + size, signal.y)), ) } fun part2(input: List<String>): Int { val maxSize = 4_000_000 val a = input.map { r -> r.split('=', ',', ':') .mapNotNull { it.toIntOrNull() } .chunked(2) .map { Pos2(it[0], it[1]) } .let { createTriangles(it[0], abs(it[0].x - it[1].x) + abs(it[0].y - it[1].y)) } } val size = a.size var foundPos: Pos2? = null for (x in 1000000 .. maxSize) { for (y in 1000000 .. maxSize) { var tmp = 0 val pos = Pos2(x, y) for (signal in a) { for (t in signal) { if (!t.isInside(pos)) tmp++ } } if (size * 2 == tmp) { println(pos) foundPos = pos // break } } // if (foundPos != null) break } println(foundPos) return foundPos?.let { (it.x * 4_000_000) + it.y } ?: 0 } Runner.run(::part2, 24) }
1
Kotlin
0
0
ab63e6cd53746e68713ddfffd65dd25408d5d488
2,442
advent-of-code
Apache License 2.0
src/main/kotlin/net/hiddevb/advent/advent2019/day02/main.kt
hidde-vb
224,606,393
false
null
package net.hiddevb.advent.advent2019.day02 import net.hiddevb.advent.advent2019.intcodeMachine.getDefaultInstructionList import net.hiddevb.advent.common.initialize import kotlin.math.floor /** * --- Day 2: 1202 Program Alarm --- * * REFACTORING * ----------- * * - Make a seperate class for the computer */ const val EXCEPTED_OUTPUT = 19690720 fun main() { val fileStrings = initialize("Day 2: 1202 Program Alarm", arrayOf("day2.txt")) println("Part 1: Basic") val solution1 = solveBasic(fileStrings[0]) println("Solution: $solution1\n") println("Part 2: Advanced") val solution2 = solveAdvanced(fileStrings[0]) println("Solution: $solution2\n") } // Part 1 fun solveBasic(input: String): Int { var intCodes = input.split(",").map { it.trim().toInt() }.toTypedArray() intCodes = setVerbAndNoun(intCodes, 12, 2) return runComputer(intCodes) } // Part 2 fun solveAdvanced(input: String): Int { for (verb in 0..100) { for (noun in 0..100) { var intCodes = input.split(",").map { it.trim().toInt() }.toTypedArray() intCodes = setVerbAndNoun(intCodes, noun, verb) if (runComputerWith(intCodes) == EXCEPTED_OUTPUT) { println("SOLVED") return 100 * noun + verb } } } println("WARN: no solution found.") return 0 } fun runComputer(input: Array<Int>): Int { var intCodes = input var pointer = 0 val instructions = getDefaultInstructionList() while (true) { intCodes = instructions .find { ins -> ins.optCode == intCodes[pointer] } ?.execute(intCodes, pointer) ?: return intCodes[0] val instruction = instructions.find { ins -> ins.optCode == intCodes[pointer] } if (instruction != null) { intCodes = instruction.execute(intCodes, pointer) pointer = instruction.nextInstruction(pointer) } else { return intCodes[0] } } } fun runComputerWith(input: Array<Int>): Int { var intCodes = input var pointer = 0 while (true) { intCodes = when (intCodes[pointer]) { 1 -> sumInstruction(intCodes, pointer) 2 -> productInstruction(intCodes, pointer) 99 -> { println("DONE: ${intCodes[0]} for ${intCodes[1]},${intCodes[2]}") return intCodes[0] } else -> { println("ERR: unknown instruction $intCodes[pointer] at pointer $pointer") return 0 } } pointer = pointer.nextInstruction() } } // Instructions fun sumInstruction(intCodes: Array<Int>, pointer: Int): Array<Int> { intCodes[intCodes[pointer + 3]] = intCodes[intCodes[pointer + 1]] + intCodes[intCodes[pointer + 2]] return intCodes } fun productInstruction(intCodes: Array<Int>, pointer: Int): Array<Int> { intCodes[intCodes[pointer + 3]] = intCodes[intCodes[pointer + 1]] * intCodes[intCodes[pointer + 2]] return intCodes } fun Int.nextInstruction() = this + 4 fun setVerbAndNoun(intCodes: Array<Int>, noun: Int, verb: Int): Array<Int> { intCodes[1] = noun intCodes[2] = verb return intCodes }
0
Kotlin
0
0
d2005b1bc8c536fe6800f0cbd05ac53c178db9d8
3,258
advent-of-code-2019
MIT License
src/Day05.kt
graesj
572,651,121
false
{"Kotlin": 10264}
import kotlin.math.min fun main() { fun List<List<String>>.transpose(): MutableList<MutableList<String>> { val colList = mutableListOf<MutableList<String>>() (0..this.last().size).map { col -> colList.add(col, mutableListOf()) this.indices.forEach { height -> val element = this[height].getOrElse(col) { "" } if (element.isNotBlank()) { colList[col].add(element) } } } return colList } val instructionRegex = """move ([0-9]+) from ([0-9]+) to ([0-9]+)""".toRegex() fun getInstructionStartIndexAndBoxes(input: List<String>): Pair<Int, MutableList<MutableList<String>>> { val lines = input .takeWhile { instructionRegex.matches(it).not() } .filterNot { it.isEmpty() } .map { it.windowed(size = 4, step = 4, partialWindows = true) } val instructionStartIndex = lines.size + 1 val boxes: MutableList<MutableList<String>> = lines.transpose() return Pair(instructionStartIndex, boxes) } fun part1(input: List<String>): String { val (instructionStartIndex, boxes) = getInstructionStartIndexAndBoxes(input) input.drop(instructionStartIndex).forEach { val (amount, fromCol, toCol) = instructionRegex.matchEntire(it)!!.destructured val columnToTakeFrom = boxes[fromCol.toInt() - 1] val boxesToMove = columnToTakeFrom.subList(0, min(amount.toInt(), columnToTakeFrom.size)) boxes[toCol.toInt() - 1].addAll(0, boxesToMove.reversed()) boxesToMove.clear() } return boxes.dropLast(1).joinToString("") { it.first().trim().removeSurrounding("[", "]") } } fun part2(input: List<String>): String { val (instructionStartIndex, boxes) = getInstructionStartIndexAndBoxes(input) input.drop(instructionStartIndex).forEach { val (amount, fromCol, toCol) = instructionRegex.matchEntire(it)!!.destructured val columnToTakeFrom = boxes[fromCol.toInt() - 1] val boxesToMove = columnToTakeFrom.subList(0, min(amount.toInt(), columnToTakeFrom.size)) boxes[toCol.toInt() - 1].addAll(0, boxesToMove) boxesToMove.clear() } return boxes.dropLast(1).joinToString("") { it.first().trim().removeSurrounding("[", "]") } } // test if implementation meets criteria from the description, like: val testInput = readLines("Day05_test") check(part1(testInput) == "CMZ") val input = readLines("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df7f855a14c532f3af7a8dc86bd159e349cf59a6
2,661
aoc-2022
Apache License 2.0
src/Day04.kt
realpacific
573,561,400
false
{"Kotlin": 59236}
fun main() { fun convertToRange(text: String): IntRange { val range = text.split("-").map(String::toInt) return range.first()..range.last() } fun splitInput(text: String): Pair<IntRange, IntRange> { val input = text.split(",") val firstElf = convertToRange(input.first()) val secondElf = convertToRange(input.last()) return firstElf to secondElf } fun IntRange.completelyOverlap(other: IntRange): Boolean = (first in other && last in other) || (other.first in this && other.last in this) fun IntRange.hasAnyOverlap(other: IntRange): Boolean = first in other || last in other || other.first in this || other.last in this fun part1(input: List<String>): Int { var overlapsCount = 0 input.forEach { line -> val (first, second) = splitInput(line) if (first.completelyOverlap(second)) { overlapsCount += 1 } } return overlapsCount } fun part2(input: List<String>): Int { var overlapsCount = 0 input.forEach { line -> val (first, second) = splitInput(line) if (first.hasAnyOverlap(second)) { overlapsCount += 1 } } return overlapsCount } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f365d78d381ac3d864cc402c6eb9c0017ce76b8d
1,399
advent-of-code-2022
Apache License 2.0
src/Day23.kt
janbina
112,736,606
false
null
package Day23 import getInput import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt import kotlin.math.sqrt import kotlin.test.assertEquals fun main(args: Array<String>) { val input = getInput(23).readLines().map { Instruction.fromString(it) } assertEquals(6241, part1(input)) assertEquals(909, part2()) } sealed class Instruction { companion object { fun fromString(input: String): Instruction { val instr = input.split(Regex("\\s+")) return when (instr[0]) { "set" -> Set(instr[1], instr[2]) "sub" -> BinaryOperation("sub", instr[1], instr[2], { a, b -> a - b }) "mul" -> BinaryOperation("mul", instr[1], instr[2], { a, b -> a * b }) "jnz" -> Jump(instr[1], instr[2], { it != 0L }) else -> throw IllegalArgumentException("Invalid instruction $input") } } } data class Set(val op1: String, val op2: String): Instruction() data class BinaryOperation(val name: String, val op1: String, val op2: String, val execute: (Long, Long) -> Long): Instruction() data class Jump(val op1: String, val op2: String, val shouldJump: (Long) -> Boolean): Instruction() } fun part1(instructions: List<Instruction>): Int { return execute(instructions) } fun part2(): Int { var b = 81 * 100 + 100_000 val c = b + 17_000 var h = 0 while (true) { if (!isPrime(b)) { h++ } if (b == c) break b += 17 } return h } fun isPrime(num: Int): Boolean { if (num <= 1) return false if (num % 2 == 0 && num > 2) return false return (3..floor(sqrt(num.toDouble())).toInt()).none { num % it == 0 } } fun execute(instructions: List<Instruction>, registers: MutableMap<String, Long> = mutableMapOf()): Int { var pc = 0 var mulCounter = 0 while (pc in instructions.indices) { val inst = instructions[pc] pc++ when (inst) { is Instruction.Set -> { registers.put(inst.op1, registers.getOperandValue(inst.op2)) } is Instruction.BinaryOperation -> { registers.put(inst.op1, inst.execute(registers.getOperandValue(inst.op1), registers.getOperandValue(inst.op2))) if (inst.name == "mul") mulCounter++ } is Instruction.Jump -> { if (inst.shouldJump(registers.getOperandValue(inst.op1))) pc += registers.getOperandValue(inst.op2).toInt() - 1 } } } return mulCounter } fun Map<String, Long>.getOperandValue(operand: String): Long { return operand.toLongOrNull() ?: getOrDefault(operand, 0) }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
2,726
advent-of-code-2017
MIT License