kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
kevindcp__smart--calc__e2efb90/src/main/kotlin/smartcalc.kt
package calculator import java.math.BigInteger fun defineOperator( operatorString: String ): String { var isValid = operatorString.toIntOrNull() when{ isValid != null -> return "-1" } when{ operatorString.length % 2 == 0 -> return "+" operatorString == "=" -> return "-2" else -> return "-" } } fun defineLimits ( expression: List<String>, start: Int) : Int { var need = 0 var end = start for ( i in start..expression.size ) { if (expression[i] == ")") { need -= 1 } if (expression[i] == "("){ need += 1 } end = i if (need == 0) return end } return -1 } fun evaluate( expressionList: List<String> ) : String { try { var i = 0 var expression = expressionList.toMutableList() var size = expression.size var flag = 0 while (i < size ) { if (expression[i] == "(") { flag = 1 var subexpinicio = i var subexpfin = defineLimits(expression, subexpinicio) if ( subexpfin == -1 ){ throw IllegalArgumentException("Operator not valid") } else { var subexp = expression.subList(subexpinicio+1, subexpfin).toMutableList() var eval = evaluate(subexp) var z = subexpinicio while (z < subexpfin) { expression.removeAt(subexpinicio) z += 1 size -=1 } expression[subexpinicio] = eval } i = 0 } else if (expression[i] == ")" && flag == 0){ throw IllegalArgumentException("Operator not valid") }else i++ } i = 0 size = expression.size while ( i < size - 2 ) { var op1 = expression[i].toBigInteger() var op2 = expression[i + 2].toBigInteger() var operator = expression[i + 1] when(operator) { "*" -> { expression[i+2] = (op1 * op2).toString() expression.removeAt(i) expression.removeAt(i) size -= 2 i = 0 } "/" -> { expression[i+2] = (op1 / op2).toString() expression.removeAt(i) expression.removeAt(i) size -= 2 i = 0 } else -> i += 2 } } i = 0 while ( i < size - 2 ) { var op1 = expression[i].toBigInteger() var op2 = expression[i + 2].toBigInteger() var operator = expression[i + 1] if( operator.length > 1 ) { operator = defineOperator(operator) } when(operator) { "+" -> expression[i+2] = (op1 + op2).toString() "-" -> expression[i+2] = (op1 - op2).toString() else -> throw IllegalArgumentException("Operator not valid") } i += 2 } return expression.last() } catch (e : Exception) { return "Invalid expression" } } fun isLetters(string: String): Boolean { return string.all { it in 'A'..'Z' || it in 'a'..'z' } } fun isNumbers(string: String): Boolean { return string.all { it in '0'..'9' } } fun main() { var variables = mutableMapOf<String, BigInteger>() loop@ while(true) { var input = readLine()!!.replace("\\=".toRegex(), "eq=eq").replace("\\(".toRegex(), "(par").replace("\\)".toRegex(), "par)").replace("\\++".toRegex(), "plus+plus").replace("(?<!-)-(--)*(?!-|\\d)".toRegex(), "minus-minus").replace("\\--+".toRegex(), "plus+plus").replace("\\*".toRegex(), "mul*mul").replace("\\/(?!\\d|\\w)".toRegex(), "div/div").replace("\\s".toRegex(), "") var expression = input.split("plus|minus|eq|mul|div|par".toRegex()).toMutableList() var eval: String = "" when { expression[0] == "/help" -> { println("sdads") continue } expression[0] == "/exit" -> break expression[0].startsWith('/') -> { println("Unknown Command") continue } expression.size == 1 && expression[0] == "" -> continue expression.size == 1 && isLetters(expression[0]) -> { when { variables.containsKey(expression[0]) -> { println(variables[expression[0]]) continue } else -> { println("Unknown variable") continue } } } expression.size == 3 && expression[1] == "=" -> { when { isLetters(expression[0]) && !isLetters(expression[2]) -> { try { variables[expression[0]] = expression[2].toBigInteger() continue } catch (e: Exception){ println("Invalid expression") continue } } isLetters(expression[0]) && isLetters(expression[2]) -> { when { variables.containsKey(expression[2]) ->{ variables[expression[0]] = variables[expression[2]]!! continue } else -> { println("Invalid assignment") continue } } } else -> { println("Invalid identifier") continue } } } expression.size == 3 -> { println(evaluate(expression)) continue } expression.size > 3 -> { for (i in expression.indices) { if ( i > 1 && expression[i] == "="){ println("Invalid assignment") continue@loop } } when { expression[1] == "=" -> when { isLetters(expression[0]) -> { variables[expression[0]] = evaluate(expression.subList(2, expression.size - 1)).toBigInteger() continue } else -> continue } else->{ for (i in expression.indices) { if (isLetters(expression[i])) { when { variables.containsKey(expression[i]) -> expression[i] = variables[expression[i]].toString() else -> { continue } } } } println(evaluate(expression)) continue } } } else -> println(expression) } break } println("Bye") }
[ { "class_path": "kevindcp__smart--calc__e2efb90/calculator/SmartcalcKt.class", "javap": "Compiled from \"smartcalc.kt\"\npublic final class calculator.SmartcalcKt {\n public static final java.lang.String defineOperator(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ...
rieckpil__learning-samples__33d8f11/kotlin-examples/src/main/kotlin/de/rieckpil/learning/fpbook/fpBook.kt
package de.rieckpil.learning.fpbook fun main() { println(fib(10)) println(fib(2)) println(fib(1)) println(fib(0)) println(factorial(7)) println(findFirst(arrayOf("Duke", "Foo", "Mike", "Phil", "Tom")) { it == "Phil" }) println(findFirst(arrayOf(true, false, true, false)) { !it }) println(isSorted(listOf(1, 10, 20, 30)) { x, y -> x < y }) println(isSorted(listOf("Mike", "Hansi", "Dukeduke", "Alphabetz")) { x, y -> x.length < y.length }) val curry = curry { i: Int, s: String -> s[i] } println(curry(1)("Hello")) val uncurry = uncurry { i: Int -> { s: String -> s[i] } } println(uncurry(1, "Hello")) } /** * Chapter II */ fun factorial(i: Int): Int { tailrec fun go(n: Int, acc: Int): Int = if (n <= 0) acc else go(n - 1, n * acc) return go(i, 1) } fun fib(i: Int): Int { tailrec fun go(n: Int): Int = if (n <= 1) n else go(n - 1) + go(n - 2) return go(i) } fun <A> findFirst(xs: Array<A>, p: (A) -> Boolean): Int { tailrec fun loop(n: Int): Int = when { n >= xs.size -> -1 p(xs[n]) -> n else -> loop(n + 1) } return loop(0) } val <T> List<T>.tail: List<T> get() = drop(1) val <T> List<T>.head: T get() = first() fun <A> isSorted(aa: List<A>, ordered: (A, A) -> Boolean): Boolean { tailrec fun loop(head: A, tail: List<A>): Boolean = when { head == null -> true tail.isEmpty() -> true ordered(head, tail.head) -> loop(tail.head, tail.tail) else -> false } return loop(aa.head, aa.tail) } fun <A, B, C> partiall(a: A, f: (A, B) -> C): (B) -> C = { b -> f(a, b) } fun <A, B, C> curry(f: (A, B) -> C): (A) -> (B) -> C = { a -> { b -> f(a, b) } } fun <A, B, C> uncurry(f: (A) -> (B) -> C): (A, B) -> C = { a: A, b: B -> f(a)(b) } fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C = { f(g(it)) }
[ { "class_path": "rieckpil__learning-samples__33d8f11/de/rieckpil/learning/fpbook/FpBookKt.class", "javap": "Compiled from \"fpBook.kt\"\npublic final class de.rieckpil.learning.fpbook.FpBookKt {\n public static final void main();\n Code:\n 0: bipush 10\n 2: invokestatic #10 ...
rieckpil__learning-samples__33d8f11/kotlin-examples/src/main/kotlin/de/rieckpil/learning/fpbook/datatypes/FunctionalTreeDataStructure.kt
package de.rieckpil.learning.fpbook.datatypes sealed class Tree<out A> { companion object { fun <A> size(tree: Tree<A>): Int = when (tree) { is Leaf -> 1 is Branch -> 1 + size(tree.left) + size(tree.right) } fun maximum(tree: Tree<Int>): Int = when (tree) { is Leaf -> tree.value is Branch -> maxOf(maximum(tree.left), maximum(tree.right)) } fun <A> depth(tree: Tree<A>): Int = when (tree) { is Leaf -> 0 is Branch -> 1 + maxOf(depth(tree.left), depth(tree.left)) } fun <A, B> map(tree: Tree<A>, f: (A) -> B): Tree<B> = when (tree) { is Leaf -> Leaf(f(tree.value)) is Branch -> Branch(map(tree.left, f), map(tree.right, f)) } fun <A, B> fold(tree: Tree<A>, l: (A) -> B, f: (B, B) -> B): B = when (tree) { is Leaf -> l(tree.value) is Branch -> f(fold(tree.left, l, f), fold(tree.right, l, f)) } fun <A> sizeFold(tree: Tree<A>): Int = fold(tree, { 1 }, { a, b -> a + b + 1 }) fun <A> maximumFold(tree: Tree<Int>): Int = fold(tree, { it }, { a, b -> maxOf(a, b) }) fun <A> depthFold(tree: Tree<A>): Int = fold(tree, { 0 }, { a, b -> 1 + maxOf(a, b) }) fun <A, B> mapFold(tree: Tree<A>, f: (A) -> B): Tree<B> = fold(tree, { a: A -> Leaf(f(a)) }, { a: Tree<B>, b: Tree<B> -> Branch(a, b) }) } } data class Leaf<A>(val value: A) : Tree<A>() data class Branch<A>(val left: Tree<A>, val right: Tree<A>) : Tree<A>() fun main() { // println(Tree.size(Branch(Branch(Leaf(1), Leaf(2)), Leaf(2)))) // println(Tree.maximum(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) // println(Tree.depth(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) // println(Tree.map(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7))) { it * it }) println(Tree.sizeFold(Branch(Branch(Leaf(4), Leaf(2)), Leaf(7)))) }
[ { "class_path": "rieckpil__learning-samples__33d8f11/de/rieckpil/learning/fpbook/datatypes/FunctionalTreeDataStructureKt.class", "javap": "Compiled from \"FunctionalTreeDataStructure.kt\"\npublic final class de.rieckpil.learning.fpbook.datatypes.FunctionalTreeDataStructureKt {\n public static final void ma...
rieckpil__learning-samples__33d8f11/kotlin-examples/src/main/kotlin/de/rieckpil/learning/fpbook/propertytesting/Boilerplate.kt
package de.rieckpil.learning.fpbook.propertytesting interface RNG { fun nextInt(): Pair<Int, RNG> } data class SimpleRNG(val seed: Long) : RNG { override fun nextInt(): Pair<Int, RNG> { val newSeed = (seed * 0x5DEECE66DL + 0xBL) and 0xFFFFFFFFFFFFL val nextRNG = SimpleRNG(newSeed) val n = (newSeed ushr 16).toInt() return Pair(n, nextRNG) } } fun nonNegativeInt(rng: RNG): Pair<Int, RNG> { val (i1, rng2) = rng.nextInt() return Pair(if (i1 < 0) -(i1 + 1) else i1, rng2) } fun nextBoolean(rng: RNG): Pair<Boolean, RNG> { val (i1, rng2) = rng.nextInt() return Pair(i1 >= 0, rng2) } fun double(rng: RNG): Pair<Double, RNG> { val (i, rng2) = nonNegativeInt(rng) return Pair(i / (Int.MAX_VALUE.toDouble() + 1), rng2) } data class State<S, out A>(val run: (S) -> Pair<A, S>) { companion object { fun <S, A> unit(a: A): State<S, A> = State { s: S -> Pair(a, s) } fun <S, A, B, C> map2( ra: State<S, A>, rb: State<S, B>, f: (A, B) -> C ): State<S, C> = ra.flatMap { a -> rb.map { b -> f(a, b) } } fun <S, A> sequence( fs: List<State<S, A>> ): State<S, List<A>> = fs.foldRight(unit(emptyList())) { f, acc -> map2(f, acc) { h, t -> listOf(h) + t } } } fun <B> map(f: (A) -> B): State<S, B> = flatMap { a -> unit<S, B>(f(a)) } fun <B> flatMap(f: (A) -> State<S, B>): State<S, B> = State { s: S -> val (a: A, s2: S) = this.run(s) f(a).run(s2) } }
[ { "class_path": "rieckpil__learning-samples__33d8f11/de/rieckpil/learning/fpbook/propertytesting/BoilerplateKt.class", "javap": "Compiled from \"Boilerplate.kt\"\npublic final class de.rieckpil.learning.fpbook.propertytesting.BoilerplateKt {\n public static final kotlin.Pair<java.lang.Integer, de.rieckpil....
iJKENNEDY__kotlin_code_101__08f08f7/src/kotlin/kt_101/Lambdas_111.kt
package kt_101 class Lambdas_111 { fun iterando_lambdas(){ // val values = listOf(1,3,4,6,7,8,9,13,23,59,50) // values.forEach{ // println("$it: ${it*it}") // } println() var prices = listOf(1.3,4.94,99.95,55.49) val largePrices = prices.filter { it > 45.0 } println(largePrices) println() val salesPrices = prices.map { it*0.5 } println(salesPrices) println() val userInput = listOf("0","123","enigma","945") val numbers = userInput.map { it.toIntOrNull() } println("numbers: ${numbers}") println() var sum123 = prices.fold(0.0){ a,b -> a+b } println("sum = ${sum123}") println() val stock = mapOf(1.0 to 43, 1.4 to 49, 2.4 to 44.4 ,59.9 to 490, 6.0 to 684) var stockSum = 0.0 } fun lambda_basico(){ val multiplyLambda: (Int,Int)-> Int multiplyLambda = {a: Int, b: Int -> Int a*b } val lambdaResult = multiplyLambda(123,99) println("lambda result = $lambdaResult") println() val lambdaResultSum2:(Int, Int)-> Int= { a, b -> a+b } val ss3 = lambdaResultSum2(45,85) val lambdaResta:(Int, Int)->Int={a, b -> a-b} val rest = lambdaResta(544,111) println("sum2 = $ss3") println("resta = $rest") var doubleLambda = {a: Double -> a*4} doubleLambda = {2.3 * it} val resDouble = doubleLambda(33.33) println("rdl = $resDouble") val square:(Int)->Int = {it* it} val cubeNum:(Int)->Int = {it*it*it} println("square = ${square(12)}") println("cubeNum = ${cubeNum(4)}") } fun operateOnNumbers(a:Int, b:Int, operation:(Int,Int)->Int):Int{ val result = operation(a,b) println("result: $result") return result } }
[ { "class_path": "iJKENNEDY__kotlin_code_101__08f08f7/kt_101/Lambdas_111.class", "javap": "Compiled from \"Lambdas_111.kt\"\npublic final class kt_101.Lambdas_111 {\n public kt_101.Lambdas_111();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\"...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day07/Solution.kt
package advent.of.code.day07 import java.io.File import java.util.* val lineRegex = Regex("^Step ([A-Z]) must.+step ([A-Z]) can begin.$") fun part1(): String { val dependsOn = mutableMapOf<Char, String>() val steps = TreeSet<Char>() File("day07.txt").readLines().forEach { line -> val res = lineRegex.find(line) steps += res!!.groupValues[1][0] steps += res!!.groupValues[2][0] dependsOn.compute(res!!.groupValues[2][0]) { _, v -> (v ?: "") + res.groupValues[1][0] } } var stepOrder = "" while (steps.isNotEmpty()) { val nextSteps = TreeSet<Char>() nextSteps.addAll(dependsOn.filter { it.value.isEmpty() }.keys.sorted()) nextSteps.addAll(steps.filter { !dependsOn.contains(it) }) val step = nextSteps.first() stepOrder += step steps.remove(step) dependsOn.remove(step) dependsOn.forEach { k, v -> dependsOn[k] = v.replace(step.toString(), "") } } return stepOrder } fun part2(): Int { val dependsOn = mutableMapOf<Char, String>() val steps = TreeSet<Char>() File("day07.txt").readLines().forEach { line -> val res = lineRegex.find(line) steps += res!!.groupValues[1][0] steps += res!!.groupValues[2][0] dependsOn.compute(res!!.groupValues[2][0]) { _, v -> (v ?: "") + res.groupValues[1][0] } } val workerCount = 5 val workers = MutableList(workerCount) { Pair('-', 0) } while (steps.isNotEmpty()) { if (workers.any { it.first != '-' }) { val nextFreeWorker = workers.filter { it.first != '-' }.minBy { it.second } val nextWorker = Pair('-', nextFreeWorker!!.second) workers.remove(nextFreeWorker) workers.add(nextWorker) val lateWorkers = workers.filter { it.second < nextFreeWorker.second } workers.removeAll(lateWorkers) while (workers.size < workerCount) workers.add(nextWorker.copy()) steps.remove(nextFreeWorker.first) dependsOn.remove(nextFreeWorker.first) dependsOn.forEach { k, v -> dependsOn[k] = v.replace(nextFreeWorker.first.toString(), "") } } while (workers.any { it.first == '-' }) { val nextSteps = TreeSet<Char>() nextSteps.addAll(dependsOn.filter { it.value.isEmpty() }.keys.sorted()) nextSteps.addAll(steps.filter { !dependsOn.contains(it) }) workers.forEach { nextSteps.remove(it.first) } if (nextSteps.isEmpty()) break val step = nextSteps.first() val freeWorker = workers.first { it.first == '-' } val newWorker = Pair(step, freeWorker.second + 60 + step.toInt() - 'A'.toInt() + 1) workers.remove(freeWorker) workers.add(newWorker) } } return workers.maxBy { it.second }!!.second }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day07/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day07.SolutionKt {\n private static final kotlin.text.Regex lineRegex;\n\n public static final kotlin.text.Regex getLineRegex();\n ...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day08/Solution.kt
package advent.of.code.day08 import java.io.File data class Node( val children: List<Node>, val metadata: List<Int> ) { val length: Int = 2 + metadata.size + children.sumBy { it.length } val metadataSum: Int = metadata.sum() + children.sumBy { it.metadataSum } val metadataValue: Int = if (children.isEmpty()) metadataSum else metadata.sumBy { if (it <= children.size) children[it - 1].metadataValue else 0 } } private val tree = tree(File("day08.txt") .readText() .trim() .split(" ") .map { it.toInt() }) fun tree(input: List<Int>): Node { val childCount = input[0] val metadataCount = input[1] val children = mutableListOf<Node>() var childInput = input.drop(2) for (s in (1..childCount)) { val child = tree(childInput) children += child childInput = childInput.drop(child.length) } return Node(children, input.drop(2 + children.sumBy { it.length }).take(metadataCount)) } fun part1() = tree.metadataSum fun part2() = tree.metadataValue
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day08/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day08.SolutionKt {\n private static final advent.of.code.day08.Node tree;\n\n public static final advent.of.code.day08.Node tree(java....
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day06/Solution.kt
package advent.of.code.day06 import java.io.File import kotlin.math.abs data class Point(val x: Int, val y: Int) { fun distance(b: Point) = abs(x - b.x) + abs(y - b.y) } val input: List<Point> = File("day06.txt").readLines().map { val parts = it.split(",") Point(parts[0].trim().toInt(), parts[1].trim().toInt()) } fun part1(): Int { val topLeftBig = Point( input.map { it.x }.min()!! - 10, input.map { it.y }.min()!! - 10 ) val topLeft = Point( input.map { it.x }.min()!!, input.map { it.y }.min()!! ) val bottomRightBig = Point( input.map { it.x }.max()!! + 10, input.map { it.y }.max()!! + 10 ) val bottomRight = Point( input.map { it.x }.max()!!, input.map { it.y }.max()!! ) val areas = mutableMapOf<Point, Int>() for (x in (topLeft.x..bottomRight.x)) for (y in (topLeft.y..bottomRight.y)) { val current = Point(x, y) val distances = input.sortedBy { current.distance(it) }.map { Pair(it, it.distance(current)) } if (distances[0].second != distances[1].second) areas.compute(distances[0].first) { _, a -> (a ?: 0) + 1 } } val areasBig = mutableMapOf<Point, Int>() for (x in (topLeftBig.x..bottomRightBig.x)) for (y in (topLeftBig.y..bottomRightBig.y)) { val current = Point(x, y) val distances = input.sortedBy { current.distance(it) }.map { Pair(it, it.distance(current)) } if (distances[0].second != distances[1].second) areasBig.compute(distances[0].first) { _, a -> (a ?: 0) + 1 } } return areas.filter { areasBig[it.key] == it.value }.values.max()!! } fun part2(): Int { val topLeft = Point( input.map { it.x }.min()!!, input.map { it.y }.min()!! ) val bottomRight = Point( input.map { it.x }.max()!!, input.map { it.y }.max()!! ) var area = 0 for (x in (topLeft.x..bottomRight.x)) for (y in (topLeft.y..bottomRight.y)) { val current = Point(x, y) val allDists = input.map { it.distance(current) }.sum() if (allDists <= 10000) area++ } return area }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day06/SolutionKt$part1$$inlined$sortedBy$2.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class advent.of.code.day06.SolutionKt$part1$$inlined$sortedBy$2<T> implements java.util.Comparator {\n final advent.of.code.day...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day12/Solution.kt
package advent.of.code.day12 import java.io.File // STILL WRONG :( data class PlantsInPots(val data: MutableSet<Long> = mutableSetOf()) { companion object { fun build(init: String): PlantsInPots { val instance = PlantsInPots() init.forEachIndexed { index, c -> instance[index.toLong()] = c } return instance } } fun copy() = PlantsInPots(data.toMutableSet()) operator fun get(index: Long) = if (data.contains(index)) '#' else '.' operator fun set(index: Long, c: Char) = if (c == '#') data.add(index) else data.remove(index) fun sumPlantIndexes() = data.sum() fun plantCount() = data.size fun min() = data.min() ?: 0 fun max() = data.max() ?: 0 fun slice(middle: Long, borderSize: Long) = ((middle - borderSize)..(middle + borderSize)).map { get(it) }.joinToString("") override fun toString() = (-10..max()).joinToString("") { idx -> if (idx == 0L) get(idx).toString() .replace('#', 'X') .replace('.', 'o') else get(idx).toString() } } const val initState = "#...##.#...#..#.#####.##.#..###.#.#.###....#...#...####.#....##..##..#..#..#..#.#..##.####.#.#.###" val rules = File("day12.txt").readLines().drop(2) .map { it.substring((0..4)) to it[9] } fun calculate(lasIteration: Int): Long { val generation = PlantsInPots.build(initState) // println(info(0, generation)) for (g in (1..lasIteration)) { val before = generation.copy() ((before.min() - 5)..(before.max() + 5)) .map { pos -> val pattern = before.slice(pos, 2) val rule = rules.firstOrNull { pattern == it.first } generation[pos] = rule?.second ?: '.' } // println(info(g, generation)) } return generation.sumPlantIndexes() } fun part1() = calculate(20) fun part2(): Long { val res200 = calculate(200) val res300 = calculate(300) // val res400 = calculate(400) val diff = res300 - res200 // println("${res400 - res300} ${res300 - res200}") return (50_000_000_000 - 200) / 100 * diff + res200 } fun info(g: Int, gen: PlantsInPots) = g.toString().padStart(4, '0') + " - $gen" + " - ${gen.sumPlantIndexes()}" + " - ${gen.plantCount()}" + " - ${gen.min()}" + " - ${gen.max()}"
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day12/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day12.SolutionKt {\n public static final java.lang.String initState;\n\n private static final java.util.List<kotlin.Pair<java.lang.Str...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day15/Solution.kt
package advent.of.code.day15 import java.io.File import java.util.* import kotlin.collections.LinkedHashSet import kotlin.math.abs data class Position(val x: Int, val y: Int) : Comparable<Position> { override fun compareTo(other: Position): Int { return compareBy<Position>({ it.y }, { it.x }).compare(this, other) } override fun toString(): String { return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})" } private fun up() = copy(y = y - 1) private fun down() = copy(y = y + 1) private fun left() = copy(x = x - 1) private fun right() = copy(x = x + 1) fun around(near: Position? = null) = listOf(up(), left(), right(), down()) .filter { it.x >= 0 && it.y >= 0 } .sortedWith(compareBy({ it.distance(near ?: it) }, { it.y }, { it.x })) fun distance(b: Position) = abs(x - b.x) + abs(y - b.y) } fun Piece?.isDead() = (this?.hitPoints ?: 0) <= 0 sealed class Piece(open var position: Position, open val symbol: Char, open var hitPoints: Int = 200) : Comparable<Piece> { val y: Int get() = position.y val x: Int get() = position.x override fun compareTo(other: Piece) = position.compareTo(other.position) } abstract class Creature( override var position: Position, open val attack: Int = 3, override val symbol: Char ) : Piece(position, symbol) { fun damage(hit: Int) { hitPoints -= hit } abstract fun enemy(crit: Creature?): Boolean } const val WALL = '#' const val ELF = 'E' const val GOBLIN = 'G' data class Elf(override var position: Position, override val attack: Int = 3, override var hitPoints: Int = 200) : Creature(position, attack, ELF) { override fun enemy(crit: Creature?) = crit is Goblin } data class Goblin(override var position: Position, override val attack: Int = 3, override var hitPoints: Int = 200) : Creature(position, attack, GOBLIN) { override fun enemy(crit: Creature?) = crit is Elf } data class Wall(override var position: Position) : Piece(position, WALL) class GameBoard(initFile: File) { var pieces: MutableSet<Piece> = TreeSet() val elves: Set<Elf> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Elf) } val goblins: Set<Goblin> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Goblin) } val creatures: Set<Creature> get() = pieces.mapNotNullTo(LinkedHashSet()) { (it as? Creature) } init { initFile.readLines().forEachIndexed { y, line -> line.forEachIndexed { x, symbol -> val pos = Position(x, y) when (symbol) { WALL -> Wall(pos) ELF -> Elf(pos) GOBLIN -> Goblin(pos) else -> null }?.let { pieces.add(it) } } } } fun inRange(crit: Creature): Pair<Creature, Set<Position>> = crit to pieces.mapNotNull { it as? Creature } .filter { crit.enemy(it) } .flatMap { it.position.around() } .filterTo(TreeSet()) { (piece(it) !is Creature) and (piece(it) !is Wall) } private fun distance( pos1: Position, pos2: Position, pastPos: MutableList<Position> = mutableListOf(), distance: Int = 0 ): Int? = when { piece(pos1) is Wall -> null (piece(pos1) is Creature) and !piece(pos1).isDead() -> null pos1 in pastPos -> null pos1 == pos2 -> distance else -> pos1.around(pos2) .mapNotNull { distance(it, pos2, pastPos.apply { this += pos1 }, distance + 1) }.min() } fun nearestReachable(data: Pair<Creature, Set<Position>>) = data.second.flatMap { data.first.position.around(it) .map { a -> a to distance(a, it) } .filter { p -> p.second != null } }.minWith(compareBy({ it.second ?: Int.MAX_VALUE }, { it.first.y }, { it.first.x })) ?.first fun buryDead() { pieces = pieces.filterTo(TreeSet()) { it.hitPoints > 0 } } fun piece(pos: Position?) = pieces.firstOrNull { it.position == pos } override fun toString(): String { var output = "" for (y in (0..(pieces.map { it.y }.max() ?: 0))) { for (x in (0..(pieces.map { it.x }.max() ?: 0))) output += piece(Position(x, y))?.symbol ?: '.' output += '\n' } return output } } val input = File("day15-test.txt") fun part1(): Int { val board = GameBoard(input) var round = 0 println("init") println(board) while (board.elves.isNotEmpty() and board.goblins.isNotEmpty()) { round++ for (crit in board.creatures) { if (crit.isDead()) continue //move if (crit.position.around().none { crit.enemy(board.piece(it) as? Creature) }) { val chosenPos = board.nearestReachable(board.inRange(crit)) if (chosenPos != null) crit.position = chosenPos } val target = crit.position.around().filter { crit.enemy(board.piece(it) as? Creature) } .mapNotNull { board.piece(it) as? Creature } .sortedWith(compareBy({ it.hitPoints }, { it.y }, { it.x })) .firstOrNull() target?.damage(crit.attack) } board.buryDead() println("$round (${board.creatures.size}) -> ${round * board.creatures.map { it.hitPoints }.sum()}") println(board) println(board.creatures.joinToString("\n")) println() } return 0 } fun part2() = 2
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day15/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day15.SolutionKt {\n public static final char WALL;\n\n public static final char ELF;\n\n public static final char GOBLIN;\n\n priva...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day14/Solution.kt
package advent.of.code.day14 fun processUntil10(e1: Byte, e2: Byte, created: Int): String { val recipes = mutableListOf(e1, e2) var elf1 = 0 var elf2 = 1 while (recipes.size < created + 10) { val combine = recipes[elf1] + recipes[elf2] val recipe1 = if (combine > 9) 1.toByte() else null val recipe2 = (combine % 10.toByte()).toByte() if (recipe1 != null) recipes += recipe1 recipes += recipe2 elf1 = (elf1 + recipes[elf1].toInt() + 1) % recipes.size elf2 = (elf2 + recipes[elf2].toInt() + 1) % recipes.size } return recipes.takeLast(10).joinToString("") } fun findSize(e1: Byte, e2: Byte, search: List<Byte>): Int { val recipes = mutableListOf(e1, e2) var elf1 = 0 var elf2 = 1 while (true) { val combine = recipes[elf1] + recipes[elf2] val recipe1 = if (combine > 9) 1.toByte() else null val recipe2 = (combine % 10.toByte()).toByte() if (recipe1 != null) { recipes += recipe1 if (recipes.takeLast(search.size) == search) return recipes.size - search.size } recipes += recipe2 if (recipes.takeLast(search.size) == search) return recipes.size - search.size elf1 = (elf1 + recipes[elf1].toInt() + 1) % recipes.size elf2 = (elf2 + recipes[elf2].toInt() + 1) % recipes.size } } fun part1() = processUntil10(3, 7, 920831) fun part2() = findSize(3, 7, listOf(9, 2, 0, 8, 3, 1))
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day14/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day14.SolutionKt {\n public static final java.lang.String processUntil10(byte, byte, int);\n Code:\n 0: iconst_2\n 1: an...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day04/Solution.kt
package advent.of.code.day04 import advent.of.code.day04.State.* import java.io.File enum class State(val match: Regex) { SHIFT(Regex(".+Guard #([0-9]+) begins shift")), SLEEP(Regex(".+:([0-9]{2})\\] falls asleep")), AWAKE(Regex(".+:([0-9]{2})\\] wakes up")) } fun commonPart(selector: (Map.Entry<Int, Array<Int>>) -> Int): Int { val guardSleep = mutableMapOf<Int, Array<Int>>() var currentGuard = 0 var asleep = 0 val lines = File("day04.txt").readLines().sorted() for (line in lines) { when { SHIFT.match matches line -> { currentGuard = SHIFT.match.find(line)?.groups!![1]!!.value.toInt() if (guardSleep[currentGuard] == null) guardSleep[currentGuard] = Array(60) { 0 } } SLEEP.match matches line -> { asleep = SLEEP.match.find(line)!!.groups[1]!!.value.toInt() } AWAKE.match matches line -> { val awake = AWAKE.match.find(line)!!.groups[1]!!.value.toInt() for (b in (asleep until awake)) guardSleep[currentGuard]!![b]++ } } } val guardMostSleep = guardSleep.maxBy(selector)!!.key return guardMostSleep * guardSleep[guardMostSleep]!! .mapIndexed { index, i -> Pair(index, i) } .maxBy { it.second }!!.first } fun part1() = commonPart { it.value.sum() } fun part2() = commonPart { it.value.max() ?: 0 }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day04/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day04.SolutionKt {\n public static final int commonPart(kotlin.jvm.functions.Function1<? super java.util.Map$Entry<java.lang.Integer, j...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day18/Solution.kt
package advent.of.code.day18 import advent.of.code.day18.Acre.* import java.io.File data class Position(val x: Int, val y: Int) : Comparable<Position> { override fun compareTo(other: Position): Int { return compareBy<Position>({ it.y }, { it.x }).compare(this, other) } override fun toString(): String { return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})" } fun up() = copy(y = y - 1) fun down() = copy(y = y + 1) fun left() = copy(x = x - 1) fun right() = copy(x = x + 1) fun upLeft() = copy(x = x - 1, y = y - 1) fun upRight() = copy(x = x + 1, y = y - 1) fun downLeft() = copy(y = y + 1, x = x - 1) fun downRight() = copy(y = y + 1, x = x + 1) fun around() = listOf(up(), down(), left(), right(), upLeft(), upRight(), downLeft(), downRight()) } val input = File("day18.txt") enum class Acre(val symbol: Char) { TREES('|'), LUMBERYARD('#'), OPEN('.') } class ForestField(input: File) { var acres = mapOf<Position, Acre>() init { var y = 0 acres = input.readLines().flatMap { line -> var x = 0 line.mapNotNull { symbol -> val pos = Position(x++, y) when (symbol) { TREES.symbol -> Pair(pos, TREES) LUMBERYARD.symbol -> Pair(pos, LUMBERYARD) else -> null } }.apply { y++ } }.toMap() } fun around(position: Position) = position.around().mapNotNull { acres[it] } fun plots() = (0..(acres.map { it.key.y }.max() ?: 0)).flatMap { y -> (0..(acres.map { it.key.x }.max() ?: 0)).map { x -> val pos = Position(x, y) Pair(pos, acres[pos] ?: OPEN) } } override fun toString(): String { var output = "" for (y in (0..(acres.map { it.key.y }.max() ?: 0))) { for (x in (0..(acres.map { it.key.x }.max() ?: 0))) output += (acres[Position(x, y)] ?: OPEN).symbol output += '\n' } return output } } // 1000000000 fun part1(): Int { val forest = ForestField(input) println((1..1000000000).map { idx -> forest.acres = forest.plots().mapNotNull { when (it.second) { TREES -> { if (forest.around(it.first).count { near -> near == LUMBERYARD } >= 3) Pair(it.first, LUMBERYARD) else it } LUMBERYARD -> { if (forest.around(it.first).count { near -> near == LUMBERYARD } >= 1 && forest.around(it.first).count { near -> near == TREES } >= 1) Pair(it.first, LUMBERYARD) else null } else -> { if (forest.around(it.first).count { near -> near == TREES } >= 3) Pair(it.first, TREES) else it } } }.toMap() val wood = forest.plots().count { it.second == TREES } val yards = forest.plots().count { it.second == LUMBERYARD } if (((idx - 1000) % 7000 in listOf(6999, 0, 1))) println("$idx -> $wood -> $yards -> ${wood * yards}") idx to wood * yards }.last()) return forest.plots().count { it.second == LUMBERYARD } * forest.plots().count { it.second == TREES } }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day18/SolutionKt$WhenMappings.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day18.SolutionKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: in...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day11/Solution.kt
package advent.of.code.day11 const val id = 5535 val squareResults = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() fun powerLevel(x: Int, y: Int) = (((((x + 10) * y + id) * (x + 10)) / 100) % 10) - 5 fun part1(): String { val result = (1..298).map { x -> (1..298).map { y -> val power = (0..2).map { powerX -> (0..2).map { powerY -> powerLevel(x + powerX, y + powerY) }.sum() }.sum() Triple(x, y, power) }.maxBy { it.third } }.maxBy { it?.third ?: 0 } return "${result?.first},${result?.second}" } fun part2(): String { var max = 0 var maxRegion: Triple<Int, Int, Int>? = null for (size in (1..300)) { for (x in (1..(301 - size))) { for (y in (1..(301 - size))) { val power = if (size > 1) { squareResults[Pair(x, y)]?.first!! + (x..(x + size - 2)).map { powerLevel(it, y + size - 1) }.sum() + (y..(y + size - 2)).map { powerLevel(x + size - 1, it) }.sum() + powerLevel(x + size - 1, y + size - 1) } else { (x..(x + size - 1)).map { innerX -> (y..(y + size - 1)).map { innerY -> powerLevel(innerX, innerY) }.sum() }.sum() } if (power > max) { max = power maxRegion = Triple(x, y, size) } squareResults[Pair(x, y)] = Pair(power, size) } } } return "${maxRegion?.first},${maxRegion?.second},${maxRegion?.third}" }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day11/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day11.SolutionKt {\n public static final int id;\n\n private static final java.util.Map<kotlin.Pair<java.lang.Integer, java.lang.Integ...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day10/Solution.kt
package advent.of.code.day10 import java.io.File private val lineRegex = Regex("position=<([- ]?[0-9]+), ([- ]?[0-9]+)> velocity=<([- ]?[0-9]+), ([- ]?[0-9]+)>") private var input = File("day10.txt").readLines().map { val res = lineRegex.find(it.trim()) listOf( res?.groupValues?.get(1)?.trim()?.toInt() ?: 0, res?.groupValues?.get(2)?.trim()?.toInt() ?: 0, res?.groupValues?.get(3)?.trim()?.toInt() ?: 0, res?.groupValues?.get(4)?.trim()?.toInt() ?: 0 ) }.toList() fun List<List<Int>>.move() = map { listOf(it[0] + it[2], it[1] + it[3], it[2], it[3]) }.toList() fun List<List<Int>>.height() = map { it[1] }.max()!! - map { it[1] }.min()!! fun part1() { var result = input.toList() var before = input.toList() var min = Int.MAX_VALUE for (s in (0..10000000)) { val current = result.height() if (current > min) { var msg = "\n" val minX = before.map { it[0] }.min()!! val maxX = before.map { it[0] }.max()!! val minY = before.map { it[1] }.min()!! val maxY = before.map { it[1] }.max()!! for (y in (minY..maxY)) { for (x in (minX..maxX)) msg += if (before.any { it[0] == x && it[1] == y }) '#' else ' ' msg += '\n' } println(s - 1) println(msg) break } min = current before = result result = result.move() } }
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day10/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day10.SolutionKt {\n private static final kotlin.text.Regex lineRegex;\n\n private static java.util.List<? extends java.util.List<java...
brunorene__advent_of_code_2018__0cb6814/src/main/kotlin/advent/of/code/day17/Solution.kt
package advent.of.code.day17 import java.io.File import java.util.* class Position(name1: String, val1: Int, val2: Int) : Comparable<Position> { val x: Int val y: Int init { if (name1 == "x") { x = val1 y = val2 } else { x = val2 y = val1 } } override fun compareTo(other: Position): Int { return compareBy<Position>({ it.y }, { it.x }).compare(this, other) } override fun toString(): String { return "(${x.toString().padStart(3, ' ')},${y.toString().padStart(3, ' ')})" } } val input = File("day17.txt") val multipleCoord = Regex("(x|y)=([.0-9]+)\\.\\.([.0-9]+)") val oneCoord = Regex("(x|y)=([.0-9]+)") class Underground(input: File) { val clay: MutableSet<Position> = TreeSet() init { input.readLines().forEach { line -> val parts = line.split(",").map { it.trim() } var multiResult = multipleCoord.find(parts[0]) if (multiResult != null) { val coordName1 = multiResult.groupValues[1] val startCoord1 = multiResult.groupValues[2].toInt() val endCoord1 = multiResult.groupValues[3].toInt() val oneResult = oneCoord.find(parts[1]) val startCoord2 = oneResult!!.groupValues[2].toInt() for (c in (startCoord1..endCoord1)) clay.add(Position(coordName1, c, startCoord2)) } else { val oneResult = oneCoord.find(parts[0]) val coordName1 = oneResult!!.groupValues[1] val startCoord1 = oneResult.groupValues[2].toInt() multiResult = multipleCoord.find(parts[1]) val startCoord2 = multiResult!!.groupValues[2].toInt() val endCoord2 = multiResult.groupValues[3].toInt() for (c in (startCoord2..endCoord2)) clay.add(Position(coordName1, startCoord1, c)) } } } } fun part1(): Int { val underground = Underground(input) println(underground.clay) return 1 } fun part2() = 2
[ { "class_path": "brunorene__advent_of_code_2018__0cb6814/advent/of/code/day17/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class advent.of.code.day17.SolutionKt {\n private static final java.io.File input;\n\n private static final kotlin.text.Regex multipleCoord;\n\n private s...
tmdroid__kotlin-puzzles__f828252/src/test/kotlin/com/igorwojda/string/issubstring/solution.kt
package com.igorwojda.string.issubstring //Kotlin Idiomatic Approach private object Solution1 { private fun isSubstring(str: String, subStr: String): Boolean { return str.contains(subStr) && str.isNotEmpty() && subStr.isNotEmpty() } } // Time complexity: O(n+m) // Space complexity: O(1) // // Optimal solution using double pointer. private object Solution2 { private fun isSubstring(str: String, subStr: String): Boolean { if (str.isEmpty() || subStr.isEmpty()) return false if (str.length <= subStr.length) return false var pointer1 = 0 var pointer2 = 0 while (pointer1 <= str.lastIndex) { if (str[pointer1] == subStr[pointer2]) { pointer2++ } if (pointer2 == subStr.length) { return true } pointer1++ } return false } } // Time complexity: O(n+m) // Space complexity: ??, but more than O(1) // Number of iterations (n) is bounded by the length of the first string // and String.drop requires copying the entire remaining string (on it's own it has O(m) complexity) // First of 5 chars, needs 5 iterations at most and 15 character copied (5+4+3+2+1=15). Second is copied less often. // // Recursive solution private object Solution3 { private fun isSubstring(str: String, subStr: String): Boolean { if (subStr.length > str.length) { return false } if (str.isEmpty() || subStr.isEmpty()) { return false } return if (str.first() == subStr.first()) { val localStr = str.drop(1) val localSubStr = subStr.drop(1) if (localStr.first() == localSubStr.first()) { true } else { isSubstring(localStr, localSubStr.drop(1)) } } else { isSubstring(str.drop(1), subStr) } } } // Time complexity: O(n) // Space complexity: O(1) // This recursive solution is faster than solution with String.drop because it uses double pointer // // Recursive solution private fun isSubstring(str: String, subStr: String): Boolean { if (str.isEmpty() || subStr.isEmpty()) { return false } fun helper(first: String, second: String, firstPointer1: Int = 0, secondPointer2: Int = 0): Boolean { if (firstPointer1 > first.lastIndex) { return false } return if (first[firstPointer1] == second[secondPointer2]) { val localPointer1 = firstPointer1 + 1 val localPointer2 = secondPointer2 + 1 if (localPointer1 > first.lastIndex || localPointer2 > second.lastIndex) { return true } else { helper(first, second, localPointer1, localPointer2) } } else { val p1 = firstPointer1 + 1 if (p1 > first.lastIndex) { return false } else { helper(first, second, p1, secondPointer2) } } } return helper(str, subStr) }
[ { "class_path": "tmdroid__kotlin-puzzles__f828252/com/igorwojda/string/issubstring/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class com.igorwojda.string.issubstring.SolutionKt {\n private static final boolean isSubstring(java.lang.String, java.lang.String);\n Code:\n ...
NiksonJD__Kotlin_WordsVirtuoso__a3a9cdd/src/main/kotlin/Main.kt
package wordsvirtuoso import java.io.File fun input(prompt: String) = println(prompt).run { readln() } fun check(f: Set<String>) = f.filter { it.length != 5 || !it.matches(Regex("[a-z]{5}")) || it.toSet().size != 5 } class Statistics() { val start = System.currentTimeMillis() val badChar = mutableSetOf<String>() val variants = mutableListOf<MutableMap<String, Color>>() var count = 0 fun addMap(wordMap: MutableMap<String, Color>) = variants.add(wordMap) fun addChar(bad: String) = badChar.add(bad) fun addWord(word: String) = word.asSequence().map { it.toString() to Color.GREEN }.toMap().toMutableMap().also { addMap(it) } fun printV() = variants.forEach { ml -> ml.forEach { (key, value) -> print(value.dye(key)) }.run { println() } } } enum class Color(private val value: String) { GREEN("\u001B[48:5:10m"), YELLOW("\u001B[48:5:11m"), GREY("\u001B[48:5:7m"), AZURE("\u001B[48:5:14m"); fun dye(string: String) = "$value$string\u001B[0m" } fun output(input: String, x: String, statistics: Statistics) { val m = mutableMapOf<String, Color>() input.mapIndexed { i, c -> if (c == x[i]) m.put(c.toString(), Color.GREEN) else if (x.contains(c)) m.put(c.toString(), Color.YELLOW) else { statistics.addChar(c.toString()); m.put(c.toString(), Color.GREY) } } statistics.addMap(m).also { println() }.run { statistics.printV() } println("\n" + statistics.badChar.sorted().joinToString("").let { Color.AZURE.dye(it) }) } fun game(candidateWords: Set<String>, allWords: Set<String>) { val x = candidateWords.random().uppercase() val statistics = Statistics() while (true) { val i = input("Input a 5-letter word:").uppercase().also { statistics.count++ } if (i.equals("exit", true)) { println("The game is over."); break } else if (i == x) { if (statistics.count == 1) { x.forEach { print(Color.GREEN.dye(it.toString())) } println("\n\nCorrect!\nAmazing luck! The solution was found at once.") } else { statistics.addWord(x).also { println() }.also { statistics.printV() } val seconds = (System.currentTimeMillis() - statistics.start) / 1000 println("\nCorrect!\nThe solution was found after ${statistics.count} tries in $seconds seconds.") }; break } else if (i.length != 5) println("The input isn't a 5-letter word.") else if (!i.matches(Regex("[A-Z]{5}"))) println("One or more letters of the input aren't valid.") else if (i.toSet().size != 5) println("The input has duplicate letters.") else if (!allWords.contains(i.lowercase())) println("The input word isn't included in my words list.") else output(i, x, statistics) } } fun start(args: Array<String>) { if (args.size != 2) println("Error: Wrong number of arguments.").also { return } val (w, c) = arrayOf(File(args[0]), File(args[1])) if (!w.exists()) println("Error: The words file $w doesn't exist.").also { return } if (!c.exists()) println("Error: The candidate words file $c doesn't exist.").also { return } val (a, d) = arrayOf(w.readLines().map { it.lowercase() }.toSet(), c.readLines().map { it.lowercase() }.toSet()) if (!check(a).isEmpty()) println("Error: ${check(a).size} invalid words were found in the $w file.").also { return } if (!check(d).isEmpty()) println("Error: ${check(d).size} invalid words were found in the $c file.").also { return } val r = d.toMutableSet(); r.removeAll(a) if (r.isNotEmpty()) println("Error: ${r.size} candidate words are not included in the $w file.").also { return } println("Words Virtuoso").also { game(d, a) } } fun main(args: Array<String>) = start(args)
[ { "class_path": "NiksonJD__Kotlin_WordsVirtuoso__a3a9cdd/wordsvirtuoso/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class wordsvirtuoso.MainKt {\n public static final java.lang.String input(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 // ...
TommyRed__AoC2017__2c8b7c5/src/tommyred/days/Day2.kt
package cz.tommyred.days /** * Created by Rechtig on 06.12.2017. */ val sample = "5 1 9 5\n7 5 3\n2 4 6 8" val hardInput = "4347 3350 196 162 233 4932 4419 3485 4509 4287 4433 4033 207 3682 2193 4223\n648 94 778 957 1634 2885 1964 2929 2754 89 972 112 80 2819 543 2820\n400 133 1010 918 1154 1008 126 150 1118 117 148 463 141 940 1101 89\n596 527 224 382 511 565 284 121 643 139 625 335 657 134 125 152\n2069 1183 233 213 2192 193 2222 2130 2073 2262 1969 2159 2149 410 181 1924\n1610 128 1021 511 740 1384 459 224 183 266 152 1845 1423 230 1500 1381\n5454 3936 250 5125 244 720 5059 202 4877 5186 313 6125 172 727 1982 748\n3390 3440 220 228 195 4525 1759 1865 1483 5174 4897 4511 5663 4976 3850 199\n130 1733 238 1123 231 1347 241 291 1389 1392 269 1687 1359 1694 1629 1750\n1590 1394 101 434 1196 623 1033 78 890 1413 74 1274 1512 1043 1103 84\n203 236 3001 1664 195 4616 2466 4875 986 1681 152 3788 541 4447 4063 5366\n216 4134 255 235 1894 5454 1529 4735 4962 220 2011 2475 185 5060 4676 4089\n224 253 19 546 1134 3666 3532 207 210 3947 2290 3573 3808 1494 4308 4372\n134 130 2236 118 142 2350 3007 2495 2813 2833 2576 2704 169 2666 2267 850\n401 151 309 961 124 1027 1084 389 1150 166 1057 137 932 669 590 188\n784 232 363 316 336 666 711 430 192 867 628 57 222 575 622 234" val xsample = "5 9 2 8\n9 4 7 3\n3 8 6 5" fun main(args: Array<String>) { println(solve2(parseInput(xsample))) } fun solve(list: List<List<Int>>): Int = list.map { it.max()!! - it.min()!! }.reduce { a, b -> a + b } fun solve2(list: List<List<Int>>): Int = list.map { getFirstDivisor(it) }.reduce { a, b -> run { println("a $a b $b"); a + b } } fun getFirstDivisor(list: List<Int>): Int { return 1 } fun parseInput(input: String): List<List<Int>> = input.split("\n").map { it.split(" ").map { it.toInt() } }
[ { "class_path": "TommyRed__AoC2017__2c8b7c5/cz/tommyred/days/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class cz.tommyred.days.Day2Kt {\n private static final java.lang.String sample;\n\n private static final java.lang.String hardInput;\n\n private static final java.lang.String xsam...
NiksonJD__Kotlin_NumericMatrixProcessor__823db67/src/main/kotlin/Main.kt
package processor import kotlin.math.pow fun input(prompt: String) = println(prompt).run { readln() } fun inputList(prompt: String) = input(prompt).split(" ").map { it.toInt() } val inputListDouble = { readln().split(" ").map { it.toDouble() } } val menuMap = mapOf( "1" to ::addMatrices, "2" to ::multiplyByConstant, "3" to ::multiplyMatrices, "4" to ::transposeMatrix, "5" to ::determinantMatrix, "6" to ::inverseMatrix ) fun addMatrices() { val (a, b) = inputMatrices(2).also { println("The result is:") } a.zip(b) { row1, row2 -> println(row1.zip(row2) { value1, value2 -> value1.plus(value2) }.joinToString(" ")) } } fun multiplyByConstant() { val a = inputMatrices(1)[0] val constant = input("Enter constant:").toDouble().also { println("The result is:") } a.map { row -> println(row.map { v -> v.times(constant) }.joinToString(" ")) } } fun multiplyMatrices() { val (a, b) = inputMatrices(2).also { println("The result is:") } val c = List(a.size) { i -> List(b[0].size) { j -> a[i].zip(b.map { row -> row[j] }).sumOf { (a, b) -> a * b } } } c.forEach { row -> println(row.joinToString(" ")) } } fun transposeMatrix() { val choice = input("\n1. Main diagonal\n2. Side diagonal\n3. Vertical line\n4. Horizontal line\nYour choice:") val a = inputMatrices(1)[0] val transposed = List(a.size) { Array(a[0].size) { 0.0 } } val (s, column) = a.run { size to get(0).size } when (choice) { "1" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[j][i] = v } } "2" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[column - j - 1][s - i - 1] = v } } "3" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[i][column - j - 1] = v } } "4" -> a.forEachIndexed { i, row -> row.forEachIndexed { j, v -> transposed[s - i - 1][j] = v } } } transposed.forEach { row -> println(row.joinToString(" ")) } } fun determinantMatrix() = println("The result is:\n${determinant(inputMatrices(1)[0])}") fun determinant(m: List<List<Double>>): Double { return if (m.size == 1) m[0][0] else { (m.indices).sumOf { j -> (-1.0).pow(j) * m[0][j] * determinant(m.subList(1, m.size).map { it.subList(0, j) + it.subList(j + 1, it.size) }) } } } fun inverseMatrix() { val m = inputMatrices(1)[0].map { it }.toMutableList() if (determinant(m) == 0.0) println("This matrix doesn't have an inverse.").also { return } val im = MutableList(m.size) { i -> List(m.size) { j -> if (i == j) 1.0 else 0.0 } } (0 until m.size).forEach { i -> val pivot = m[i][i] m[i] = m[i].map { it / pivot } im[i] = im[i].map { it / pivot } (0 until m.size).filter { it != i }.forEach { k -> val factor = m[k][i] m[k] = m[k].zip(m[i]).map { (a, b) -> a - b * factor } im[k] = im[k].zip(im[i]).map { (a, b) -> a - b * factor } } } println("The result is:").also { im.forEach { row -> println(row.joinToString(" ")) } } } fun inputMatrices(count: Int): Array<List<List<Double>>> { val array = Array(count) { listOf<List<Double>>() } for (i in 1..count) { val order = if (count == 2) if (i == 1) "first" else "second" else "" inputList("Enter size of $order matrix:").also { println("Enter matrix:") } .let { array[i - 1] = List(it[0]) { inputListDouble() } } } return array } fun main() { val menu = "\n1. Add matrices\n2. Multiply matrix by a constant\n3. Multiply matrices\n4. Transpose matrix" + "\n5. Calculate a determinant\n6. Inverse matrix\n0. Exit\nYour choice:" while (true) { val answer = input(menu); if (answer == "0") break else menuMap[answer]?.invoke() } }
[ { "class_path": "NiksonJD__Kotlin_NumericMatrixProcessor__823db67/processor/MainKt$menuMap$6.class", "javap": "Compiled from \"Main.kt\"\nfinal class processor.MainKt$menuMap$6 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<kotlin.Unit> {\n public static final p...
chalup__elmish-kt-parser__ab20887/src/main/java/org/chalup/parser/Parser.kt
package org.chalup.parser import org.chalup.parser.Json.JsonBool import org.chalup.parser.Json.JsonInt import org.chalup.parser.Json.JsonNull import org.chalup.parser.LeBoolean.LeFalse import org.chalup.parser.LeBoolean.LeOr import org.chalup.parser.LeBoolean.LeTrue import org.chalup.parser.LoopStep.Done import org.chalup.parser.LoopStep.Loop import org.chalup.parser.ParserStep.Bad import org.chalup.parser.ParserStep.Good import org.chalup.parser.Problem.Custom import org.chalup.parser.Problem.ExpectedKeyword import org.chalup.parser.Problem.ExpectedSymbol import org.chalup.parser.Problem.ExpectingFloat import org.chalup.parser.Problem.ExpectingInt import org.chalup.parser.Problem.UnexpectedChar import org.chalup.parser.Result.Error import org.chalup.parser.Result.Ok import org.chalup.parser.TrailingSeparatorTreatment.FORBIDDEN import org.chalup.parser.TrailingSeparatorTreatment.MANDATORY import org.chalup.parser.TrailingSeparatorTreatment.OPTIONAL sealed class Result<out ErrorT, out OkT> { data class Error<T>(val error: T) : Result<T, Nothing>() data class Ok<T>(val value: T) : Result<Nothing, T>() } data class State(val src: String, val offset: Int, val indent: Int, val row: Int, val col: Int) sealed class ParserStep<out T> { data class Good<T>(val progress: Boolean, val value: T, val state: State) : ParserStep<T>() data class Bad(val progress: Boolean, val problems: List<DeadEnd>) : ParserStep<Nothing>() } sealed class Problem { data class ExpectedSymbol(val str: String) : Problem() data class ExpectedKeyword(val str: String) : Problem() object ExpectingInt : Problem() object ExpectingFloat : Problem() object UnexpectedChar : Problem() data class Custom(val message: String) : Problem() } data class Token(val str: String, val problem: Problem, val delimiterPredicate: (Char) -> Boolean) data class DeadEnd(val row: Int, val col: Int, val problem: Problem) { constructor(state: State, problem: Problem) : this(state.row, state.col, problem) } class Parser<T>(val parse: (State) -> ParserStep<T>) { fun run(input: String): Result<List<DeadEnd>, T> = when (val step = parse(State(src = input, offset = 0, indent = 1, row = 1, col = 1))) { is Good -> Ok(step.value) is Bad -> Error(step.problems) } } fun isSubstring(str: String, offset: Int, row: Int, col: Int, bigString: String): Triple<Int, Int, Int> { var newOffset = offset var newRow = row var newCol = col var isGood = offset + str.length <= bigString.length var i = 0 while (isGood && i < str.length) { val isNewline = bigString[newOffset] == '\n' isGood = str[i++] == bigString[newOffset++] if (isNewline) { newRow++; newCol = 1 } else { newCol++ } } return Triple(if (isGood) newOffset else -1, newRow, newCol) } val int: Parser<Int> = number(NumberContext( int = Ok { n: Int -> n }, float = Error(ExpectingInt), invalid = ExpectingInt, expecting = ExpectingInt )) val float: Parser<Float> = number(NumberContext( int = Ok { n: Int -> n.toFloat() }, float = Ok { n: Float -> n }, invalid = ExpectingFloat, expecting = ExpectingFloat )) data class NumberContext<out T>(val int: Result<Problem, (Int) -> T>, val float: Result<Problem, (Float) -> T>, val invalid: Problem, val expecting: Problem) fun <T> number(context: NumberContext<T>): Parser<T> = Parser { s -> val (intOffset, n) = consumeBase(10, s.offset, s.src) finalizeFloat(context, intOffset, n, s) } fun consumeBase(base: Int, offset: Int, string: String): Pair<Int, Int> { var total = 0 var newOffset = offset while (newOffset < string.length) { val digit = string[newOffset] - '0' if (digit < 0 || digit >= base) break total = base * total + digit newOffset++ } return newOffset to total } fun <T> finalizeFloat(context: NumberContext<T>, intOffset: Int, n: Int, s: State): ParserStep<T> { val floatOffset = consumeDotAndExp(intOffset, s.src) return when { floatOffset < 0 -> Bad(progress = true, problems = listOf(DeadEnd(row = s.row, col = s.col - (floatOffset + s.offset), problem = context.invalid))) s.offset == floatOffset -> Bad(progress = false, problems = fromState(s, context.expecting)) intOffset == floatOffset -> finalizeInt(context.invalid, context.int, s.offset, intOffset, n, s) else -> when (context.float) { is Error -> Bad(progress = true, problems = listOf(DeadEnd(s, context.invalid))) // shouldn't we take the problem from the handler? is Ok -> s.src.substring(s.offset, floatOffset).toFloatOrNull() ?.let { Good(progress = true, value = context.float.value(it), state = s.bumpOffset(floatOffset)) } ?: Bad(progress = true, problems = fromState(s, context.invalid)) } } } fun <T> finalizeInt(invalid: Problem, handler: Result<Problem, (Int) -> T>, startOffset: Int, endOffset: Int, n: Int, s: State): ParserStep<T> = when (handler) { is Error -> Bad(progress = true, problems = fromState(s, handler.error)) is Ok -> if (startOffset == endOffset) Bad(progress = s.offset < startOffset, problems = fromState(s, invalid)) else Good(progress = true, value = handler.value(n), state = s.bumpOffset(endOffset)) } private fun State.bumpOffset(newOffset: Int) = copy( offset = newOffset, col = col + (newOffset - offset) ) fun fromState(s: State, x: Problem) = listOf(DeadEnd(s, x)) fun consumeDotAndExp(offset: Int, src: String): Int = if (src.at(offset) == '.') consumeExp(chompBase10(offset + 1, src), src) else consumeExp(offset, src) fun chompBase10(offset: Int, src: String): Int { var newOffset = offset while (newOffset < src.length) { val char = src[newOffset] if (char < '0' || char > '9') break newOffset++ } return newOffset } fun consumeExp(offset: Int, src: String): Int { if (src.at(offset) == 'e' || src.at(offset) == 'E') { val eOffset = offset + 1 val expOffset = if (src[eOffset] == '+' || src[eOffset] == '-') eOffset + 1 else eOffset val newOffset = chompBase10(expOffset, src) if (expOffset == newOffset) { return -newOffset } else { return newOffset } } else { return offset } } // Elm version uses under the hood some Javascript method which returns 'NaN' when reaching // outside of the valid offset range. I'm duplicating this logic here to keep the reset of // the code the same. fun String.at(offset: Int) = if (offset >= length) null else get(offset) fun symbol(str: String): Parser<Unit> = token(Token(str, ExpectedSymbol(str), delimiterPredicate = { false })) fun keyword(str: String): Parser<Unit> = token(Token(str, ExpectedKeyword(str), delimiterPredicate = { it.isLetterOrDigit() || it == '_' })) fun token(token: Token) = Parser { s -> val (newOffset, newRow, newCol) = isSubstring(token.str, s.offset, s.row, s.col, s.src) if (newOffset == -1 || isSubChar(token.delimiterPredicate, newOffset, s.src) >= 0) Bad(progress = false, problems = fromState(s, token.problem)) else Good(progress = token.str.isNotEmpty(), value = Unit, state = s.copy(offset = newOffset, row = newRow, col = newCol)) } val spaces: Parser<Unit> = chompWhile { it.isWhitespace() } fun chompWhile(predicate: (Char) -> Boolean): Parser<Unit> = Parser { state -> tailrec fun helper(offset: Int, row: Int, col: Int): ParserStep<Unit> = when (val newOffset = isSubChar(predicate, offset, state.src)) { -1 -> Good(progress = state.offset < offset, value = Unit, state = state.copy(offset = offset, row = row, col = col)) -2 -> helper(offset + 1, row + 1, 1) else -> helper(newOffset, row, col + 1) } helper(state.offset, state.row, state.col) } fun chompIf(predicate: (Char) -> Boolean): Parser<Unit> = Parser { s -> when (val newOffset = isSubChar(predicate, s.offset, s.src)) { -1 -> Bad(progress = false, problems = fromState(s, UnexpectedChar)) -2 -> Good(progress = true, value = Unit, state = s.copy(offset = s.offset + 1, row = s.row + 1, col = 1)) else -> Good(progress = true, value = Unit, state = s.copy(offset = newOffset, col = s.col + 1)) } } fun isSubChar(predicate: (Char) -> Boolean, offset: Int, string: String): Int = when { string.length <= offset -> -1 predicate(string[offset]) -> if (string[offset] == '\n') -2 else offset + 1 else -> -1 } fun <T> succeed(v: T): Parser<T> = Parser { state -> Good(progress = false, value = v, state = state) } fun problem(message: String): Parser<Nothing> = Parser { s -> Bad(progress = false, problems = fromState(s, Custom(message))) } fun <T> oneOf(parsers: List<Parser<out T>>): Parser<T> = Parser { s -> tailrec fun helper(problems: List<DeadEnd>, parsers: List<Parser<out T>>): ParserStep<T> = if (parsers.isEmpty()) Bad(progress = false, problems = problems) else when (val step = parsers.first().parse(s)) { is Good -> step is Bad -> if (step.progress) step else helper(problems + step.problems, parsers.drop(1)) } helper(problems = emptyList(), parsers = parsers) } fun <T> oneOf(vararg parsers: Parser<out T>): Parser<T> = oneOf(parsers.asList()) fun <T> parser(block: (self: Parser<T>) -> Parser<T>): Parser<T> { var stubParser: Parser<T> = Parser { throw IllegalStateException("Using stubbed parser!") } val selfParser: Parser<T> = Parser { s -> stubParser.parse(s) } return block(selfParser).also { stubParser = it } } fun <T, R> map(func: (T) -> R, parser: Parser<T>): Parser<R> = Parser { s -> when (val step = parser.parse(s)) { is Good -> Good(progress = step.progress, value = func(step.value), state = step.state) is Bad -> step } } infix fun <T, R> Parser<T>.mapTo(func: (T) -> R): Parser<R> = map(func, this) fun <T1, T2, R> map2(func: (T1, T2) -> R, parserA: Parser<T1>, parserB: Parser<T2>): Parser<R> = Parser { s -> when (val stepA = parserA.parse(s)) { is Bad -> stepA is Good -> when (val stepB = parserB.parse(stepA.state)) { is Bad -> Bad(progress = stepA.progress || stepB.progress, problems = stepB.problems) is Good -> Good(progress = stepA.progress || stepB.progress, value = func(stepA.value, stepB.value), state = stepB.state) } } } fun getChompedString(parser: Parser<*>): Parser<String> = Parser { s -> when (val step = parser.parse(s)) { is Bad -> step is Good -> Good(progress = step.progress, value = s.src.substring(s.offset, step.state.offset), state = step.state) } } infix fun <T, R> Parser<T>.andThen(func: (T) -> Parser<out R>): Parser<R> = Parser { s -> when (val stepA = parse(s)) { is Bad -> stepA is Good -> when (val stepB = func(stepA.value).parse(stepA.state)) { is Bad -> Bad(progress = stepA.progress || stepB.progress, problems = stepB.problems) is Good -> Good(progress = stepA.progress || stepB.progress, value = stepB.value, state = stepB.state) } } } infix fun <T, R> Parser<(T) -> R>.keep(keepParser: Parser<T>): Parser<R> = map2( func = { f, arg -> f(arg) }, parserA = this, parserB = keepParser ) infix fun <T1, T2, R> Parser<(T1, T2) -> R>.keep2(keepParser: Parser<T1>): Parser<(T2) -> R> = map2( func = { f, a1 -> { a2: T2 -> f(a1, a2) } }, parserA = this, parserB = keepParser ) infix fun <KeepT, SkipT> Parser<KeepT>.skip(skip: Parser<SkipT>): Parser<KeepT> = map2( func = { a: KeepT, _: SkipT -> a }, parserA = this, parserB = skip ) sealed class LoopStep<out S, out T> { data class Loop<S>(val state: S) : LoopStep<S, Nothing>() data class Done<T>(val result: T) : LoopStep<Nothing, T>() } fun <S, T> loop(loopState: S, callback: (S) -> Parser<LoopStep<S, T>>): Parser<T> = Parser { s -> tailrec fun helper(progress: Boolean, loopState: S, parserState: State): ParserStep<T> = when (val step = callback(loopState).parse(parserState)) { is Good -> when (val nextLoopStep = step.value) { is Loop -> helper(progress = progress || step.progress, loopState = nextLoopStep.state, parserState = step.state) is Done -> Good(progress = progress || step.progress, value = nextLoopStep.result, state = step.state) } is Bad -> Bad(progress = progress || step.progress, problems = step.problems) } helper(false, loopState, s) } enum class TrailingSeparatorTreatment { FORBIDDEN, OPTIONAL, MANDATORY } // TODO mark internal? infix fun <SkipT, KeepT> Parser<SkipT>.skipThen(keep: Parser<KeepT>): Parser<KeepT> = map2( func = { _: SkipT, b: KeepT -> b }, parserA = this, parserB = keep ) fun <T> sequence(start: String, separator: String, end: String, trailingSeparatorTreatment: TrailingSeparatorTreatment, itemParser: Parser<T>, spacesParser: Parser<Unit> = spaces): Parser<List<T>> { return symbol(start) skipThen spacesParser skipThen sequenceEnd(endParser = symbol(end), spacesParser = spacesParser, separatorParser = symbol(separator), trailingSeparatorTreatment = trailingSeparatorTreatment, itemParser = itemParser) } fun <T> sequenceEnd(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, trailingSeparatorTreatment: TrailingSeparatorTreatment): Parser<List<T>> { val chompRest: (T) -> Parser<List<T>> = { item: T -> when (trailingSeparatorTreatment) { FORBIDDEN -> loop(listOf(item), { s -> sequenceEndForbidden(endParser, spacesParser, itemParser, separatorParser, s) }) OPTIONAL -> loop(listOf(item), { s -> sequenceEndOptional(endParser, spacesParser, itemParser, separatorParser, s) }) MANDATORY -> (spacesParser skipThen separatorParser skipThen spacesParser skipThen loop(listOf(item), { s -> sequenceEndMandatory(spacesParser, itemParser, separatorParser, s)})) skip endParser } } return oneOf( itemParser andThen chompRest, endParser mapTo { emptyList<T>() } ) } fun <T> sequenceEndForbidden(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> = spacesParser skipThen oneOf(separatorParser skipThen spacesParser skipThen (itemParser mapTo { item -> Loop(items + item) }), endParser mapTo { Done(items) }) fun <T> sequenceEndOptional(endParser: Parser<Unit>, spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> { val parseEnd = endParser mapTo { Done(items) } return spacesParser skipThen oneOf(separatorParser skipThen spacesParser skipThen oneOf(itemParser mapTo { item -> Loop(items + item) }, parseEnd), parseEnd) } fun <T> sequenceEndMandatory(spacesParser: Parser<Unit>, itemParser: Parser<T>, separatorParser: Parser<Unit>, items: List<T>): Parser<LoopStep<List<T>, List<T>>> { return oneOf( itemParser skip spacesParser skip separatorParser skip spacesParser mapTo { item -> Loop(items + item) }, succeed(Unit) mapTo { Done(items) } ) } enum class Suite(val symbol: Char) { CLUBS('c'), HEARTS('h'), DIAMONDS('d'), SPADES('s') } enum class Rank(val symbol: Char) { TWO('2'), THREE('3'), FOUR('4'), FIVE('5'), SIX('6'), SEVEN('7'), EIGHT('8'), NINE('9'), TEN('T'), JACK('J'), QUEEN('Q'), KING('K'), ACE('A') } data class Card(val rank: Rank, val suite: Suite) { override fun toString(): String = "${rank.symbol}${suite.symbol}" } data class Point(val x: Int, val y: Int) sealed class Json { data class JsonInt(val int: Int) : Json() data class JsonBool(val boolean: Boolean) : Json() object JsonNull : Json() { override fun toString() = "null" } } sealed class LeBoolean { object LeTrue : LeBoolean() { override fun toString() = "true" } object LeFalse : LeBoolean() { override fun toString() = "false" } data class LeOr(val lhs: LeBoolean, val rhs: LeBoolean) : LeBoolean() { override fun toString() = "($lhs || $rhs)" } } fun main() { val leBooleanParser: Parser<LeBoolean> = parser { leBoolean -> oneOf( succeed(LeTrue) skip keyword("true"), succeed(LeFalse) skip keyword("false"), (succeed { l: LeBoolean, r: LeBoolean -> LeOr(l, r) } skip symbol("(") skip spaces keep2 leBoolean skip spaces skip symbol("||") skip spaces keep leBoolean skip spaces skip symbol(")") ) ) } val jsonParser: Parser<Json> = oneOf( int mapTo { JsonInt(it) }, keyword("true") mapTo { JsonBool(true) }, keyword("false") mapTo { JsonBool(false) }, keyword("null") mapTo { JsonNull } ) val parser: Parser<Point> = ( succeed { x: Int, y: Int -> Point(x, y) } skip symbol("(") skip spaces keep2 int skip spaces skip symbol(",") skip spaces keep int skip spaces skip symbol(")") ) val phpParser = getChompedString( succeed(Unit) skip chompIf { it == '$' } skip chompIf { it.isLetter() || it == '_' } skip chompWhile { it.isLetterOrDigit() || it == '_' } ) val zipCodeParser = getChompedString(chompWhile { it.isDigit() }) .andThen { code -> if (code.length == 5) succeed(code) else problem("a U.S. zip code has exactly 5 digits, but I found '$code'") } val letKeywordParser = keyword("let") val suiteParser = oneOf(Suite.values().map { suite -> symbol("${suite.symbol}") mapTo { suite } }) val rankParser = oneOf(Rank.values().map { rank -> symbol("${rank.symbol}") mapTo { rank } }) val cardParser = ( succeed { rank: Rank, suite: Suite -> Card(rank, suite) } keep2 rankParser keep suiteParser ) val handsParser = sequence( start = "[", end = "]", separator = ",", trailingSeparatorTreatment = MANDATORY, itemParser = cardParser ) println(parser.run("(10,20)")) println(int.run("123")) println(float.run("123")) println(float.run("123.123")) println(jsonParser.run("10")) println(jsonParser.run("null")) println(leBooleanParser.run("(true || (true || false))")) println(letKeywordParser.run("let")) println(letKeywordParser.run("letters")) println(phpParser.run("\$txt")) println(phpParser.run("\$x")) println(zipCodeParser.run("12345")) println(zipCodeParser.run("test")) println(zipCodeParser.run("123456789")) println(cardParser.run("Kh")) println(cardParser.run("Qs")) println(cardParser.run("*K")) println(cardParser.run("KK")) println(handsParser.run("[Kh, Qs]")) println(handsParser.run("[Kh, Qs,]")) }
[ { "class_path": "chalup__elmish-kt-parser__ab20887/org/chalup/parser/ParserKt$WhenMappings.class", "javap": "Compiled from \"Parser.kt\"\npublic final class org.chalup.parser.ParserKt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 ...
aimok04__grocy-for-wear-os__9796c5e/app/src/main/java/de/kauker/unofficial/grocy/utils/StringUtils.kt
package de.kauker.unofficial.grocy.utils import java.util.* fun String.distanceTo(c: String): Double { return similarity(this, c) } fun similarity(s1: String, s2: String): Double { var longer = s1 var shorter = s2 if (s1.length < s2.length) { // longer should always have greater length longer = s2 shorter = s1 } val longerLength = longer.length return if (longerLength == 0) { 1.0 /* both strings are zero length */ } else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble() } fun editDistance(is1: String, is2: String): Int { var s1 = is1 var s2 = is2 s1 = s1.lowercase(Locale.getDefault()) s2 = s2.lowercase(Locale.getDefault()) val costs = IntArray(s2.length + 1) for (i in 0..s1.length) { var lastValue = i for (j in 0..s2.length) { if (i == 0) costs[j] = j else { if (j > 0) { var newValue = costs[j - 1] if (s1[i - 1] != s2[j - 1]) newValue = Math.min( Math.min(newValue, lastValue), costs[j] ) + 1 costs[j - 1] = lastValue lastValue = newValue } } } if (i > 0) costs[s2.length] = lastValue } return costs[s2.length] }
[ { "class_path": "aimok04__grocy-for-wear-os__9796c5e/de/kauker/unofficial/grocy/utils/StringUtilsKt.class", "javap": "Compiled from \"StringUtils.kt\"\npublic final class de.kauker.unofficial.grocy.utils.StringUtilsKt {\n public static final double distanceTo(java.lang.String, java.lang.String);\n Code:...
odiapratama__Android-Playground__cf1a9a0/app/src/main/java/com/problemsolver/androidplayground/utils/SortAlgorithm.kt
package com.problemsolver.androidplayground.utils import java.util.* object SortAlgorithm { /** * TIME COMPLEXITY * Best : Ω(n) * Average : Θ(n^2) * Worst : O(n^2) * */ fun <T : Comparable<T>> bubbleSort(array: List<T>, asc: Boolean = true) { val length = array.size - 1 var count = 0 if (asc) { while (count < length) { for (i in 0 until length) { if (array[i] > array[i + 1]) { Collections.swap(array, i, i + 1) count = 0 break } else { count++ } } } } else { while (count < length) { for (i in 0 until length) { if (array[i] < array[i + 1]) { Collections.swap(array, i, i + 1) count = 0 break } else { count++ } } } } } /** * TIME COMPLEXITY * Best : Ω(n^2) * Average : Θ(n^2) * Worst : O(n^2) * */ fun <T : Comparable<T>> selectionSort(array: List<T>, asc: Boolean = true) { for (i in 0..array.size - 2) { var pointer = i for (j in (i + 1) until array.size) { if (asc) { if (array[pointer] > array[j]) { pointer = j } } else { if (array[pointer] < array[j]) { pointer = j } } } if (asc) { if (array[pointer] < array[i]) { Collections.swap(array, i, pointer) } } else { if (array[pointer] > array[i]) { Collections.swap(array, i, pointer) } } } } /** * TIME COMPLEXITY * Best : Ω(n log(n)) * Average : Θ(n log(n)) * Worst : O(n^2) * */ fun <T : Comparable<T>> quickSort(array: List<T>, l: Int, r: Int) { if (l < r) { val p = partition(array, l, r) quickSort(array, l, p - 1) quickSort(array, p, r) } } private fun <T : Comparable<T>> partition(array: List<T>, l: Int, r: Int): Int { var left = l var right = r val mid = (left + right) / 2 val pivot = array[mid] while (left <= right) { while (array[left] < pivot) { left++ } while (array[right] > pivot) { right-- } if (left <= right) { Collections.swap(array, left, right) left++ right-- } } return left } /** * TIME COMPLEXITY * Best : Ω(n log(n)) * Average : Θ(n log(n)) * Worst : O(n log(n)) * */ fun <T : Comparable<T>> mergeSort(array: Array<T>, l: Int, r: Int) { if (l >= r) return val mid = (l + r) / 2 val temp = arrayOfNulls<Comparable<T>>(array.size) mergeSort(array, l, mid) mergeSort(array, mid + 1, r) mergeHalves(array, temp, l, r) } private fun <T : Comparable<T>> mergeHalves( array: Array<T>, temp: Array<Comparable<T>?>, leftStart: Int, rightEnd: Int ) { val leftEnd = (leftStart + rightEnd) / 2 val rightStart = leftEnd + 1 val size = rightEnd - leftStart + 1 var left = leftStart var index = leftStart var right = rightStart while (left <= leftEnd && right <= rightEnd) { if (array[left] < array[right]) { temp[index] = array[left] left++ } else { temp[index] = array[right] right++ } index++ } System.arraycopy(array, left, temp, index, leftEnd - left + 1) System.arraycopy(array, right, temp, index, rightEnd - right + 1) System.arraycopy(temp, leftStart, array, leftStart, size) } }
[ { "class_path": "odiapratama__Android-Playground__cf1a9a0/com/problemsolver/androidplayground/utils/SortAlgorithm.class", "javap": "Compiled from \"SortAlgorithm.kt\"\npublic final class com.problemsolver.androidplayground.utils.SortAlgorithm {\n public static final com.problemsolver.androidplayground.util...
ShMPMat__GenerationUtils__c5368fa/src/utils/OutputFun.kt
package shmp.utils import kotlin.math.max import kotlin.math.pow /** * Adds right text to the left text. right text will be lined up with * consideration to longest line from the left text. * * @param guarantiedLength if left fragment is already has equal length of lines. * @return left and right text merged in one. */ fun addToRight(left: String, right: String, guarantiedLength: Boolean): StringBuilder { if (left.isEmpty()) return StringBuilder(right) val stringBuilder = StringBuilder() val lineLength: Int = (left.lines().map { it.length }.maxOrNull() ?: 0) + 4 val linesAmount = max(left.lines().count(), right.lines().count()) val list1 = left.lines() + ((0 until linesAmount - left.lines().size).map { "" }) val list2 = right.lines() + ((0 until linesAmount - right.lines().size).map { "" }) for (i in 0 until linesAmount) { val ss1 = list1[i] val ss2 = list2[i] stringBuilder .append(ss1) .append(" ".repeat(if (guarantiedLength) 4 else lineLength - ss1.length)) .append(ss2) if (i != linesAmount - 1) stringBuilder.append("\n") } return stringBuilder } fun addToRight(left: StringBuilder, right: StringBuilder, guarantiedLength: Boolean) = addToRight(left.toString(), right.toString(), guarantiedLength) /** * Edits text via carrying lines which are longer than size. * @param text text which will be edited. * @param size maximal acceptable length of a line. * @return edited text, each line in it is not longer than size. Words can be cut in the middle. */ fun chompToSize(text: String, size: Int): StringBuilder { val stringBuilder = StringBuilder() for (_line in text.lines()) { var line = _line while (line.isNotEmpty()) if (size >= line.length) { stringBuilder.append(line) break } else { var part = line.substring(0, size) if (part.lastIndexOf(" ") != -1) { line = line.substring(part.lastIndexOf(" ") + 1) part = (if (part.lastIndexOf(" ") == 0) part.substring(1) else part.substring(0, part.lastIndexOf(" "))) } else line = line.substring(size) stringBuilder.append(part).append("\n") } stringBuilder.append("\n") } return stringBuilder } /** * Edits text via adding lines after size + 1 recursively to the right. * @param text text which will be modified. * @param size maximal acceptable number of lines. * @return edited text, has no more than size lines, greater lines added to the right. */ fun chompToLines(text: String, size: Int): StringBuilder { val prefix = text.lines().take(size).joinToString("\n") val postfix = text.lines().drop(size).joinToString("\n") if (postfix == "") return java.lang.StringBuilder(prefix) return addToRight( prefix, chompToLines(postfix, size).toString(), false ) } fun chompToLines(text: StringBuilder, size: Int) = chompToLines(text.toString(), size) fun getTruncated(t: Double, signs: Int) = 10.0.pow(signs).toInt().let { p -> (t * p).toInt().toDouble() / p }.toString() fun <E> E.addLinePrefix(prefix: String = " ") = this.toString().lines() .joinToString("\n") { prefix + it }
[ { "class_path": "ShMPMat__GenerationUtils__c5368fa/shmp/utils/OutputFunKt.class", "javap": "Compiled from \"OutputFun.kt\"\npublic final class shmp.utils.OutputFunKt {\n public static final java.lang.StringBuilder addToRight(java.lang.String, java.lang.String, boolean);\n Code:\n 0: aload_0\n ...
korlibs__korge__11993ae/korlibs-datastructure/src/korlibs/datastructure/_GenericSort.kt
package korlibs.datastructure import kotlin.math.min fun <T> genericSort(subject: T, left: Int, right: Int, ops: SortOps<T>): T = genericSort(subject, left, right, ops, false) fun <T> genericSort(subject: T, left: Int, right: Int, ops: SortOps<T>, reversed: Boolean): T = subject.also { timSort(subject, left, right, ops, reversed) } private fun Int.negateIf(doNegate: Boolean) = if (doNegate) -this else this private fun <T> insertionSort(arr: T, left: Int, right: Int, ops: SortOps<T>, reversed: Boolean) { for (n in left + 1..right) { var m = n - 1 while (m >= left) { if (ops.compare(arr, m, n).negateIf(reversed) <= 0) break m-- } m++ if (m != n) ops.shiftLeft(arr, m, n) } } private fun <T> merge(arr: T, start: Int, mid: Int, end: Int, ops: SortOps<T>, reversed: Boolean) { var s = start var m = mid var s2 = m + 1 if (ops.compare(arr, m, s2).negateIf(reversed) <= 0) return while (s <= m && s2 <= end) { if (ops.compare(arr, s, s2).negateIf(reversed) <= 0) { s++ } else { ops.shiftLeft(arr, s, s2) s++ m++ s2++ } } } private fun <T> mergeSort(arr: T, l: Int, r: Int, ops: SortOps<T>, reversed: Boolean) { if (l < r) { val m = l + (r - l) / 2 mergeSort(arr, l, m, ops, reversed) mergeSort(arr, m + 1, r, ops, reversed) merge(arr, l, m, r, ops, reversed) } } private fun <T> timSort(arr: T, l: Int, r: Int, ops: SortOps<T>, reversed: Boolean, RUN: Int = 32) { val n = r - l + 1 for (i in 0 until n step RUN) { insertionSort(arr, l + i, l + min((i + RUN - 1), (n - 1)), ops, reversed) } var size = RUN while (size < n) { for (left in 0 until n step (2 * size)) { val rize = min(size, n - left - 1) val mid = left + rize - 1 val right = min((left + 2 * rize - 1), (n - 1)) merge(arr, l + left, l + mid, l + right, ops, reversed) } size *= 2 } } abstract class SortOps<T> { abstract fun compare(subject: T, l: Int, r: Int): Int abstract fun swap(subject: T, indexL: Int, indexR: Int) open fun shiftLeft(subject: T, indexL: Int, indexR: Int) { for (n in indexR downTo indexL + 1) swap(subject, n - 1, n) } open fun reverse(subject: T, indexL: Int, indexR: Int) { val count = indexR - indexL + 1 for (n in 0 until count / 2) { swap(subject, indexL + n, indexR - n) } } } object SortOpsComparable : SortOps<MutableList<Comparable<Any>>>() { override fun compare(subject: MutableList<Comparable<Any>>, l: Int, r: Int): Int = subject[l].compareTo(subject[r]) override fun swap(subject: MutableList<Comparable<Any>>, indexL: Int, indexR: Int) { val tmp = subject[indexL] subject[indexL] = subject[indexR] subject[indexR] = tmp } } fun <T : Comparable<T>> MutableList<T>.genericSort(left: Int = 0, right: Int = size - 1): MutableList<T> = genericSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) fun <T : Comparable<T>> List<T>.genericSorted(left: Int = 0, right: Int = size - 1): List<T> = this.subList(left, right + 1).toMutableList().genericSort() fun <T : Comparable<T>> List<T>.timSorted(): List<T> = this.toMutableList().also { it.timSort() } fun <T : Comparable<T>> MutableList<T>.timSort(left: Int = 0, right: Int = size - 1): MutableList<T> { timSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) //genericSort(this, left, right, SortOpsComparable as SortOps<MutableList<T>>, false) return this }
[ { "class_path": "korlibs__korge__11993ae/korlibs/datastructure/_GenericSortKt.class", "javap": "Compiled from \"_GenericSort.kt\"\npublic final class korlibs.datastructure._GenericSortKt {\n public static final <T> T genericSort(T, int, int, korlibs.datastructure.SortOps<T>);\n Code:\n 0: aload_3\...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day4/Day4.kt
package day4 import java.io.File class BingoBoard(private val numbers: List<List<Int>>) { private var visited = MutableList(numbers.size) { MutableList(numbers[0].size) { false } } fun visit(number: Int) { val traversingCellsIndices = visited.indices.flatMap { r -> visited[0].indices.map { c -> Pair(r, c) } } val maybeCell = traversingCellsIndices.firstOrNull { (r, c) -> numbers[r][c] == number } if (maybeCell != null) visited[maybeCell.first][maybeCell.second] = true } val isCompleted: Boolean get() = hasRowCompleted || hasColumnCompleted private val hasRowCompleted: Boolean get() = visited.any { row -> row.all { it /* it == true */ } } private val hasColumnCompleted: Boolean get() { val traversingColumnsIndices = visited[0].indices.map { c -> visited.indices.map { r -> Pair(r, c) } } return traversingColumnsIndices.any { column -> column.all { (r, c) -> visited[r][c] } } } fun sumUnvisited(): Int { val traversingCellsIndices = visited.indices.flatMap { r -> visited[0].indices.map { c -> Pair(r, c) } } return traversingCellsIndices .filterNot { (r, c) -> visited[r][c] } .sumOf { (r, c) -> numbers[r][c] } } } fun findWinnerBoardScore(drawNumbers: List<Int>, boards: List<BingoBoard>): Int { drawNumbers.forEach { number -> boards.forEach { board -> board.visit(number) if (board.isCompleted) return number * board.sumUnvisited() } } return 0 // should never reach this point } fun findLoserBoardScore(drawNumbers: List<Int>, boards: List<BingoBoard>): Int { val mutBoards = boards.toMutableList() drawNumbers.forEach { number -> mutBoards.forEach { board -> board.visit(number) if (mutBoards.size == 1 && board.isCompleted) return mutBoards.first().sumUnvisited() * number } mutBoards.removeAll { it.isCompleted } } return 0 // should never reach this point } fun parseBingoData(data: List<String>): Pair<List<Int>, List<BingoBoard>> { fun parseLine(line: String) = line.split(" ").filterNot(String::isEmpty).map(String::toInt) fun parseBoard(boardRaw: List<String>) = BingoBoard(boardRaw.map(::parseLine)) val drawNumbers = data.first().split(",").map(String::toInt) val boards = data .drop(1) // remove draw numbers .filterNot(String::isBlank) .chunked(5) .map(::parseBoard) return Pair(drawNumbers, boards) } fun main() { File("./input/day4.txt").useLines { lines -> val data = lines.toList() val (drawNumbers, boards) = parseBingoData(data) println("First value: ${findWinnerBoardScore(drawNumbers, boards)}") println("Second value: ${findLoserBoardScore(drawNumbers, boards)}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day4/Day4Kt.class", "javap": "Compiled from \"Day4.kt\"\npublic final class day4.Day4Kt {\n public static final int findWinnerBoardScore(java.util.List<java.lang.Integer>, java.util.List<day4.BingoBoard>);\n Code:\n 0: aload_0\n 1: ldc...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day3/Day3.kt
package day3 import java.io.File fun computeGammaAndEpsilon(diagnosticReport: List<String>): Pair<Int, Int> { val p = List(diagnosticReport[0].length) { -diagnosticReport.size / 2 } val sums = diagnosticReport.fold(p) { acc, s -> s.map { it - '0' }.zip(acc){ a, b -> a + b } } val (gammaRaw, epsilonRaw) = sums .map { if (it >= 0) 1 else 0 } .fold(Pair("", "")) { acc, d -> Pair(acc.first + d, acc.second + (1 - d)) } return Pair(gammaRaw.toInt(2), epsilonRaw.toInt(2)) } fun computeOxygenGenerator(diagnosticReport: List<String>): Int { tailrec fun rec(remaining: List<String>, bitPosition: Int): String { // assuming input has always a single answer although after processing last bit // the remaining values are the same return if (remaining.size == 1) remaining.first() else { val (ones, zeros) = remaining.partition { it[bitPosition] == '1' } // assuming it's either 0 or 1) rec(if (ones.size >= zeros.size) ones else zeros, bitPosition + 1) } } return rec(diagnosticReport, 0).toInt(2) } fun computeCO2Scrubber(diagnosticReport: List<String>): Int { tailrec fun rec(remaining: List<String>, bitPosition: Int): String { // assuming input has always a single answer although after processing last bit // the remaining values are the same return if (remaining.size == 1) remaining.first() else { val (ones, zeros) = remaining.partition { it[bitPosition] == '1' } // assuming it's either 0 or 1) rec(if (ones.size < zeros.size) ones else zeros, bitPosition + 1) } } return rec(diagnosticReport, 0).toInt(2) } fun printProduct(pair: Pair<Int, Int>): Int = pair.first * pair.second fun main() { File("./input/day3.txt").useLines { lines -> val diagnosticReport = lines.toList() println("First value: ${printProduct(computeGammaAndEpsilon(diagnosticReport))}") println("Second value: ${computeOxygenGenerator(diagnosticReport) * computeCO2Scrubber(diagnosticReport)}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day3/Day3Kt.class", "javap": "Compiled from \"Day3.kt\"\npublic final class day3.Day3Kt {\n public static final kotlin.Pair<java.lang.Integer, java.lang.Integer> computeGammaAndEpsilon(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day2/Day2.kt
package day2 import java.io.File sealed interface SubmarineActions<out S : SubmarineActions<S>> { fun moveForward(delta: Int): S fun goUp(delta: Int): S fun goDown(delta: Int): S = goUp(-delta) } data class Submarine1(val horizontal: Int, val depth: Int): SubmarineActions<Submarine1> { companion object { val fromStart: Submarine1 get() = Submarine1(0, 0) } override fun moveForward(delta: Int) = this.copy(horizontal = horizontal + delta) override fun goUp(delta: Int) = this.copy(depth = depth - delta) } data class Submarine2(val horizontal: Int, val depth: Int, val aim: Int): SubmarineActions<Submarine2> { companion object { val fromStart: Submarine2 get() = Submarine2(0, 0, 0) } override fun moveForward(delta: Int) = this.copy(horizontal = horizontal + delta, depth = depth + aim * delta) override fun goUp(delta: Int) = this.copy(aim = aim - delta) } fun <S : SubmarineActions<S>> processInstruction(current: S, instruction: String): S { val (word, number) = instruction.split(" ") val delta = number.toInt() return when (word) { "forward" -> current.moveForward(delta) "up" -> current.goUp(delta) "down" -> current.goDown(delta) else -> current // ignore unrecognized command } } fun computeFinalHorizontalPositionAndDepthProduct(instructions: List<String>): Int { val s = instructions.fold(Submarine1.fromStart, ::processInstruction) return s.horizontal * s.depth } fun computeFinalHorizontalPositionAndDepthProduct2(instructions: List<String>): Int { val s = instructions.fold(Submarine2.fromStart, ::processInstruction) return s.horizontal * s.depth } fun main() { File("./input/day2.txt").useLines { lines -> val instructions = lines.toList() println("First value: ${computeFinalHorizontalPositionAndDepthProduct(instructions)}") println("Second value: ${computeFinalHorizontalPositionAndDepthProduct2(instructions)}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day2/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2Kt {\n public static final <S extends day2.SubmarineActions<? extends S>> S processInstruction(S, java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day5/Day5.kt
package day5 import java.io.File typealias Coordinates = Pair<Int, Int> typealias Matrix = Map<Coordinates, Int> private val regex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex() fun parseLine(line: String): List<Int> = regex.matchEntire(line)!! .groupValues.drop(1) // dropping first item because it's the whole line .map(String::toInt) private fun expandRange(start: Int, end: Int) = if (start <= end) start.rangeTo(end) else start.downTo(end) // required for part 1 fun expandSegmentRangeWithoutDiagonals(x1: Int, y1: Int, x2: Int, y2: Int): Iterable<Coordinates> = when { x1 == x2 -> expandRange(y1, y2).map { x1 to it } y1 == y2 -> expandRange(x1, x2).map { it to y1 } else -> emptyList() // ignore } fun expandSegmentRange(x1: Int, y1: Int, x2: Int, y2: Int): Iterable<Coordinates> = when { x1 == x2 -> expandRange(y1, y2).map { x1 to it } y1 == y2 -> expandRange(x1, x2).map { it to y1 } else -> expandRange(x1, x2).zip(expandRange(y1, y2)) // diagonal, update both coordinates } fun buildMatrix(segments: List<String>): Matrix = segments .map { segment -> parseLine(segment) } .flatMap { (x1, y1, x2, y2) -> expandSegmentRange(x1, y1, x2, y2) } .groupingBy { it }.eachCount() fun countCloudSegmentOverlappingPoints(matrix: Matrix): Int = matrix.values.count { it > 1 } fun main() { File("./input/day5.txt").useLines { lines -> val matrix = buildMatrix(lines.toList()) println(countCloudSegmentOverlappingPoints(matrix)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day5/Day5Kt$buildMatrix$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class day5.Day5Kt$buildMatrix$$inlined$groupingBy$1 implements kotlin.collections.Grouping<kotlin.Pair<? extends java.lang.Integer, ? exten...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day12/Day12.kt
package day12 import java.io.File fun parseInput(lines: List<String>): Map<String, List<String>> = lines.flatMap { val (cave1, cave2) = it.split("-") listOf(cave1 to cave2, cave2 to cave1) }.groupBy({ it.first }, { it.second }) private fun String.isCaveSmall(): Boolean = this.first().isLowerCase() fun countDistinctPathsThatVisitSmallCavesAtMostOnce(map: Map<String, List<String>>): Int { fun rec(cave: String, visited: Set<String>): Int = when { cave == "end" -> 1 visited.contains(cave) -> 0 else -> { map[cave]?.sumOf { rec(it, if (cave.isCaveSmall()) visited + cave else visited) } ?: 0 } } return rec("start", setOf()) } fun countDistinctPathsThatVisitSmallCavesAtMostOnceExceptOneRepetition(map: Map<String, List<String>>): Int { fun rec(cave: String, smallCavesVisited: Set<String>, repetitionUsed: Boolean): Int { return when { cave == "end" -> 1 smallCavesVisited.contains(cave) -> if (repetitionUsed || cave == "start") 0 else map[cave]?.sumOf { rec(it, smallCavesVisited, true) } ?: 0 else -> { val next = if (cave.isCaveSmall()) smallCavesVisited + cave else smallCavesVisited map[cave]?.sumOf { rec(it, next, repetitionUsed) } ?: 0 } } } return rec("start", setOf(), false) } fun main() { File("./input/day12.txt").useLines { lines -> val map = parseInput(lines.toList()) println(countDistinctPathsThatVisitSmallCavesAtMostOnce(map)) println(countDistinctPathsThatVisitSmallCavesAtMostOnceExceptOneRepetition(map)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day12/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class day12.Day12Kt {\n public static final java.util.Map<java.lang.String, java.util.List<java.lang.String>> parseInput(java.util.List<java.lang.String>);\n Code:\n 0:...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day15/Day15.kt
package day15 import java.io.File import java.util.PriorityQueue // Syntax sugar typealias Matrix<T> = Array<Array<T>> typealias RiskFn = (Pair<Int, Int>) -> Int private fun <T> Matrix<T>.get(pair: Pair<Int, Int>) = this[pair.first][pair.second] private fun <T> Matrix<T>.put(pair: Pair<Int, Int>, element: T) { this[pair.first][pair.second] = element } fun parseInput(lines: List<String>): Matrix<Int> = lines .map { it.map(Char::digitToInt).toTypedArray() } .toTypedArray() private fun Pair<Int, Int>.withinBoundaries(limit: Int) = (0 until limit).let { range -> range.contains(this.first) && range.contains(this.second) } // I decided to navigate from destination to start: (N, N) to (0, 0) // Let's try to go up and left first even though there is a priority queue that // will ultimately decide the order private fun Pair<Int, Int>.adjacent(boundaries: Int) = listOf(-1 to 0, 0 to -1, 0 to 1, 1 to 0) // up, left, right, down .map { (first, second) -> (first + this.first) to (second + this.second) } .filter { it.withinBoundaries(boundaries) } private fun solve(dimension: Int, riskFn: RiskFn): Int { val minPathRiskTabulation = Array(dimension) { Array(dimension) { Int.MAX_VALUE } } val toVisit = PriorityQueue<Pair<Pair<Int, Int>, Int>> { (_, risk1), (_, risk2) -> risk1.compareTo(risk2) } val start = 0 to 0 val destination = (dimension - 1) to (dimension - 1) toVisit.add(destination to 0) do { val (current, accumulatedRisk) = toVisit.poll() if (current == start) return accumulatedRisk val pathRisk = riskFn(current) + accumulatedRisk val minPathRisk = minPathRiskTabulation.get(current) if (pathRisk < minPathRisk) { minPathRiskTabulation.put(current, pathRisk) toVisit.addAll(current.adjacent(dimension).associateWith { pathRisk }.toList()) } } while (true) } fun solve1(riskMatrix: Matrix<Int>): Int = solve(riskMatrix.size, riskMatrix::get) fun riskFn2(riskMatrix: Matrix<Int>): RiskFn = { (r, c) -> val additionalRisk = (r / riskMatrix.size) + (c / riskMatrix.size) val risk = riskMatrix[r % riskMatrix.size][c % riskMatrix.size] + additionalRisk if (risk > 9) risk - 9 else risk // only 1..9 (10 resets to 1) } fun solve2(riskMatrix: Matrix<Int>): Int = solve(riskMatrix.size * 5, riskFn2(riskMatrix)) fun main() { File("./input/day15.txt").useLines { lines -> val riskMatrix = parseInput(lines.toList()) println(solve1(riskMatrix)) println(solve2(riskMatrix)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day15/Day15Kt.class", "javap": "Compiled from \"Day15.kt\"\npublic final class day15.Day15Kt {\n private static final <T> T get(T[][], kotlin.Pair<java.lang.Integer, java.lang.Integer>);\n Code:\n 0: aload_0\n 1: aload_1\n 2: inv...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day14/Day14.kt
package day14 import java.io.File fun parseInput(lines: List<String>): Pair<String, Map<String, Char>> { val initial = lines.first() val insertions = lines.drop(2).associate { val (pattern, addition) = it.split(" -> ") pattern to addition.first() } return initial to insertions } private fun combineAllMaps(vararg maps: Map<Char, Long>): Map<Char, Long> = maps.flatMap { it.toList() } .groupBy { it.first } .mapValues { (_, v) -> v.fold(0L) { acc, (_, v) -> acc + v } } private fun combine2(map1: Map<Char, Long>, map2: Map<Char, Long>): Map<Char, Long> = combineAllMaps(map1, map2) val memoizeCountDescendantChars = { insertions: Map<String, Char> -> // intermediate steps will be stored here val cache = mutableMapOf<Pair<String, Int>, Map<Char, Long>>() // Recursively build the count, storing all intermediate steps // in 'cache' so that they can be reused later on fun getAdditionCount(pair: String, steps: Int): Map<Char, Long> = when { steps == 0 -> emptyMap() cache.containsKey(pair to steps) -> cache[pair to steps]!! insertions.containsKey(pair) -> { val c = insertions[pair]!! val result = combineAllMaps( mapOf(c to 1L), getAdditionCount("${pair[0]}$c", steps - 1), getAdditionCount("$c${pair[1]}", steps - 1) ) cache[pair to steps] = result result } else -> emptyMap() } ::getAdditionCount } fun solve(polymer: String, insertions: Map<String, Char>, steps: Int): Long { val memoizedGetDescendants = memoizeCountDescendantChars(insertions) val finalCount = sequence { // Count initial chars val initialCharCount = polymer .groupingBy { it }.eachCount() .mapValues { (_, v) -> v.toLong() } .toMutableMap() yield(initialCharCount) // Count descendant chars generated by each pair or chars ('abc' -> 'ab','bc') for (i in 0..(polymer.length - 2)) { val pair = polymer.substring(i, i + 2) yield(memoizedGetDescendants(pair, steps)) } }.reduce(::combine2) val max = finalCount.maxOf { it.value } val min = finalCount.minOf { it.value } return max - min } fun main() { File("./input/day14.txt").useLines { lines -> val (initialPolymer, insertions) = parseInput(lines.toList()) println(solve(initialPolymer, insertions, 10)) println(solve(initialPolymer, insertions, 40)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day14/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class day14.Day14Kt {\n private static final kotlin.jvm.functions.Function1<java.util.Map<java.lang.String, java.lang.Character>, kotlin.reflect.KFunction<java.util.Map<java.lan...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day13/Day13.kt
package day13 import java.io.File /* Syntax sugar */ typealias Dot = Pair<Int, Int> typealias PaperFold = Pair<Char, Int> private val Dot.x: Int get() = this.first private val Dot.y: Int get() = this.second /* end */ fun parseInput(lines: List<String>): Pair<List<Dot>, List<PaperFold>> { val dots = lines .takeWhile { it.isNotEmpty() && it.first().isDigit() } .map { val (x, y) = it.split(",").map(String::toInt) x to y } fun extractAxisAndValue(string: String): Pair<Char, Int> { val (sentence, value) = string.split("=") return (sentence.last() to value.toInt()) } val paperFolds = lines .drop(dots.size + 1) // removing also the empty line separator .map(::extractAxisAndValue) return Pair(dots, paperFolds) } fun fold(dots: List<Dot>, paperFold: PaperFold): List<Dot> { val (axis, value) = paperFold return when (axis) { 'x' -> { val (base, foldingSide) = dots .filterNot { it.x == value } .partition { it.x < value } (base + foldingSide.map { (value - (it.x - value)) to it.y }).distinct() } 'y' -> { val (base, foldingSide) = dots .filterNot { it.y == value } .partition { it.y < value } (base + foldingSide.map { it.x to (value - (it.y - value)) }).distinct() } else -> TODO("Not supported axis :)") } } // Actually not needed fun countVisibleDotsAfterFolding(dots: List<Dot>, paperFolds: List<PaperFold>): Int = paperFolds.fold(dots, ::fold).size fun countVisibleDotsAfterFirstFolding(dots: List<Dot>, paperFolds: List<PaperFold>): Int = fold(dots, paperFolds.first()).size fun printAfterAllFolds(dots: List<Dot>, paperFolds: List<PaperFold>) { fun print(dots: List<Dot>) { val rowMax = dots.maxOf { it.y } val columnMax = dots.maxOf { it.x } (0..rowMax).forEach { y -> (0..columnMax).forEach { x -> if (dots.contains(x to y)) print('#') else print('.') } println() } } print(paperFolds.fold(dots, ::fold)) } fun main() { File("./input/day13.txt").useLines { lines -> val (dots, folds) = parseInput(lines.toList()) println(countVisibleDotsAfterFirstFolding(dots, folds)) printAfterAllFolds(dots, folds) } } // ARHZPCUH
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day13/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class day13.Day13Kt {\n private static final int getX(kotlin.Pair<java.lang.Integer, java.lang.Integer>);\n Code:\n 0: aload_0\n 1: invokevirtual #13 ...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day22/Day22.kt
package day22 import java.io.File private const val OFF = false private const val ON = true typealias Cube = Triple<Int, Int, Int> data class RebootStep(val x: IntRange, val y: IntRange, val z: IntRange, val state: Boolean) data class LitRegion(val x: IntRange, val y: IntRange, val z: IntRange) { private fun isEmptyRegion(): Boolean = x.isEmpty() || y.isEmpty() || z.isEmpty() private fun overlapsWith(other: LitRegion): Boolean = TODO() fun subtract(other: LitRegion): List<LitRegion> { if (other.isEmptyRegion() || !overlapsWith(other)) return listOf(this) else { TODO() } } } fun parseInput(lines: List<String>): List<RebootStep> { fun parseRange(range: String): IntRange { val (n1, n2) = range.split("..").map(String::toInt) return n1..n2 } fun extractRanges(ranges: String): Triple<IntRange, IntRange, IntRange> { val (x, y, z) = ranges.split(",").map { parseRange(it.drop(2)) } return Triple(x, y, z) } return lines.map { line -> when { line.startsWith("on") -> { val (x, y, z) = extractRanges(line.removePrefix("on ")) RebootStep(x, y, z, ON) } line.startsWith("off") -> { val (x, y, z) = extractRanges(line.removePrefix("off ")) RebootStep(x, y, z, OFF) } else -> TODO() } } } fun countCubesOnRestricted(steps: List<RebootStep>): Int { fun isOutOfRange(step: RebootStep): Boolean = listOf(step.x, step.y, step.z).any { it.first < -50 || it.last > 50 } val cubes = Array(101) { Array(101) { Array(101) { OFF } } } for (step in steps.filterNot(::isOutOfRange)) { step.x.forEach { x -> step.y.forEach { y -> step.z.forEach { z -> cubes[x + 50][y + 50][z + 50] = step.state } } } } return cubes.sumOf { it.sumOf { it.count { it == ON } } } } fun countCubesUnbounded(steps: List<RebootStep>): Long { val cubesOn = HashSet<Cube>() for (step in steps) { println(step) val cubes = step.x.flatMap { x -> step.y.flatMap { y -> step.z.map { z -> Cube(x, y, z) } } } if (step.state == ON) cubesOn.addAll(cubes) else cubesOn.removeAll(cubes) } return cubesOn.sumOf { 1L } } fun main() { File("./input/day22.txt").useLines { lines -> val rebootSteps = parseInput(lines.toList()) println(countCubesOnRestricted(rebootSteps)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day22/Day22Kt.class", "javap": "Compiled from \"Day22.kt\"\npublic final class day22.Day22Kt {\n private static final boolean OFF;\n\n private static final boolean ON;\n\n public static final java.util.List<day22.RebootStep> parseInput(java.util.Li...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day7/Day7.kt
package day7 import java.io.File import kotlin.math.abs fun parseInput(input: String) = input.split(",").groupingBy(String::toInt).eachCount() private fun minFuelSpentToAlignedPosition(data: Map<Int, Int>, costFn: (Int, Int) -> Int): Int { val min = data.keys.minOf { it } val max = data.keys.maxOf { it } return (min..max) .map { destination -> data.map { (currentPosition, crabs) -> costFn(destination, currentPosition) * crabs } } .minOf { it.sum() } } fun minFuelSpentToAlignedPosition(data: Map<Int, Int>): Int = minFuelSpentToAlignedPosition(data){ destination, currentPosition -> abs(destination - currentPosition)} fun minFuelSpentToAlignedPositionPart2(data: Map<Int, Int>): Int = minFuelSpentToAlignedPosition(data){ destination: Int, currentPosition: Int -> val steps = abs(currentPosition - destination) ((steps * (steps + 1)) / 2) } fun main() { File("./input/day7.txt").useLines { lines -> val crabsMap = parseInput(lines.first()) println("First part: ${minFuelSpentToAlignedPosition(crabsMap)}") println("Second part: ${minFuelSpentToAlignedPositionPart2(crabsMap)}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day7/Day7Kt$parseInput$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class day7.Day7Kt$parseInput$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.String, java.lang.Integer> {\n final ja...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day9/Day9.kt
package day9 import java.io.File fun parseMap(rows: List<String>): Array<IntArray> = rows.map { row -> row.trim().map { it - '0' }.toIntArray() }.toTypedArray() fun expandAdjacent(row: Int, column: Int, map: Array<IntArray>): List<Pair<Int, Int>> = listOf(0 to -1, -1 to 0, 0 to 1, 1 to 0) .map { (r, c) -> (r + row) to (c + column) } .filterNot { (r, c) -> r < 0 || c < 0 || r >= map.size || c >= map[0].size } fun findLocalMinimums(map: Array<IntArray>): List<Pair<Int, Int>> { fun isLocalMinimum(row: Int, column: Int): Boolean { val adjacent = expandAdjacent(row, column, map) val current = map[row][column] return adjacent.all { (r, c) -> map[r][c] > current } } val rows = map.indices val columns = map[0].indices val traverseMapIndices = rows.flatMap { r -> columns.map { c -> r to c } } return traverseMapIndices.filter { (r, c) -> isLocalMinimum(r, c) } } fun sumOfLocalMinimums(map: Array<IntArray>): Int = findLocalMinimums(map).sumOf { (r, c) -> map[r][c] + 1 } fun computeBasinSize(row: Int, column: Int, map: Array<IntArray>): Int { val visited = mutableSetOf<Pair<Int, Int>>() val remaining = ArrayDeque(listOf(row to column)) var size = 0 do { val current = remaining.removeFirst() val currentValue = map[current.first][current.second] if (currentValue == 9 || visited.contains(current)) continue val nonVisitedAdjacent = expandAdjacent(current.first, current.second, map).filterNot { visited.contains(it) } val belongsToBasin = nonVisitedAdjacent.all { (r, c) -> map[r][c] >= currentValue } if (belongsToBasin) { size += 1 visited.add(current) remaining.addAll(nonVisitedAdjacent) } } while (!remaining.isEmpty()) return size } fun productOfSizeThreeLargestBasins(map: Array<IntArray>): Int = findLocalMinimums(map) .map { (r, c) -> computeBasinSize(r, c, map) } .sorted() .takeLast(3) .reduce(Int::times) fun main() { File("./input/day9.txt").useLines { lines -> val map = parseMap(lines.toList()) println(findLocalMinimums(map)) println(productOfSizeThreeLargestBasins(map)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day9/Day9Kt.class", "javap": "Compiled from \"Day9.kt\"\npublic final class day9.Day9Kt {\n public static final int[][] parseMap(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 // String r...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day8/Day8.kt
package day8 import java.io.File /* * An entry has the following format: <representation of the ten digits> | <display output> * i.e: * acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf */ fun parseOnlyDigitsOutput(entries: List<String>): List<List<String>> = entries.map { entry -> entry.split(" | ")[1].split(" ") } fun countOneFourSevenAndEights(listOfDisplayDigitRows: List<List<String>>): Int { val listOfSizes = listOf(2, 4, 3, 7) // The amount of signals that 1, 4, 7 and 8 require respectively return listOfDisplayDigitRows.sumOf { digitsRow -> digitsRow.count { digit -> listOfSizes.contains(digit.length) } } } /* * Digits representation * * 0: 1: 2: 3: 4: * aaaa .... aaaa aaaa .... * b c . c . c . c b c * b c . c . c . c b c * .... .... dddd dddd dddd * e f . f e . . f . f * e f . f e . . f . f * gggg .... gggg gggg .... * * 5: 6: 7: 8: 9: * aaaa aaaa aaaa aaaa aaaa * b . b . . c b c b c * b . b . . c b c b c * dddd dddd .... dddd dddd * . f e f . f e f . f * . f e f . f e f . f * gggg gggg .... gggg gggg */ private val digitMap = mapOf( "abcefg" to 0, "cf" to 1, "acdeg" to 2, "acdfg" to 3, "bcdf" to 4, "abdfg" to 5, "abdefg" to 6, "acf" to 7, "abcdefg" to 8, "abcdfg" to 9, ) /* * The input contains the representation of all digits. * With that information and the `digitMap` above we can already infer a few things: * - Only edge 'b' appears 6 times * - Only edge 'e' appears 4 times * - Only edge 'f' appears 9 times * - Edges 'a' and 'c' appear 8 times * - Edges 'd' and 'g' appear 7 times * * Also comparing the edges of numbers we can disambiguate edges in the last two statements: * - 7.edges - 4.edges = 'a' * - 4.edges - 7.edges = 'b' and 'd' * * Although the last subtraction will produce two edges, we've already inferred 'b' so we can discard it in favour of 'd' */ fun computeEquivalenceMap(digitsSignals: String): Map<Char, Char> { val translations = mutableMapOf<Char, Char>() // Get some equivalences due to unique number of occurrences val occurrences = digitsSignals.replace(" ", "").groupingBy { it }.eachCount() occurrences.forEach { (c, n) -> if (n == 4) translations[c] = 'e' if (n == 6) translations[c] = 'b' if (n == 9) translations[c] = 'f' } // Get the rest by comparing numbers with subtle differences val signals = digitsSignals.split(" ").groupBy { it.length } val four = signals[4]!!.first().toSet() // 4 the only digit that requires four signals to be represented val seven = signals[3]!!.first().toSet() // 7 the only digit that requires three signals to be represented // 7 - 4 will output edge 'a' val a = (seven - four).first() translations[a] = 'a' // 'c' is the other edge with 8 occurrences that is not 'a' val c = occurrences.entries.first { (c, n) -> n == 8 && c != a }.key translations[c] = 'c' // 4 - 7 will generate edges 'b' and 'd' but 'b' is already in the translations map val d = (four - seven).first { c -> !translations.contains(c) } translations[d] = 'd' // 'g' is the other edge with 7 occurrences that is not 'd' val g = occurrences.entries.first { (c, n) -> n == 7 && c != d }.key translations[g] = 'g' return translations } fun decipherSignal(entry: String): Int { val (signals, display) = entry.split(" | ") val equivalenceMap = computeEquivalenceMap(signals) val outputDigits = display .split(" ") .map { digit -> val translation = digit.map(equivalenceMap::get).sortedBy { it }.joinToString("") digitMap[translation] } return outputDigits.joinToString("").toInt() } fun main() { File("./input/day8.txt").useLines { lines -> val entries = lines.toList() val listOfDisplayDigitRows = parseOnlyDigitsOutput(entries) println("First part: ${countOneFourSevenAndEights(listOfDisplayDigitRows)}") println("First part: ${entries.sumOf { decipherSignal(it) }}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day8/Day8Kt$decipherSignal$lambda$10$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class day8.Day8Kt$decipherSignal$lambda$10$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public day8.Day8Kt$deciphe...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day6/Day6.kt
package day6 import java.io.File fun parseInput(line: String) = line.split(",").map { it.toInt() } data class LanternFish(val daysToEngender: Int) { fun ageOneDay(): List<LanternFish> = if (daysToEngender == 0) listOf(LanternFish(6), LanternFish(8)) else listOf(LanternFish(daysToEngender - 1)) } fun naivelyCountLanternfishPopulationAfterNDays(listOfDays: List<Int>, days: Int): Int { tailrec fun loop(lanternFish: List<LanternFish>, remainingDays: Int): List<LanternFish> = if (remainingDays == 0) lanternFish else loop(lanternFish.flatMap { it.ageOneDay() }, remainingDays - 1) return loop(listOfDays.map { LanternFish(it) }, days).count() } fun countLanternfishPopulationAfterNDays(listOfDays: List<Int>, days: Int): Long { // cluster population by remaining days to give birth; 9 days for the first time, then 7 days val clusters = listOfDays.groupingBy { it }.eachCount() val population = Array(9) { clusters.getOrDefault(it, 0).toLong() } repeat(days) { val births = population[0] (1..8).forEach { i -> population[i - 1] = population[i] } // reduce days to give birth of population population[6] += births population[8] = births } return population.sum() } fun main() { File("./input/day6.txt").useLines { lines -> val lanternFish = parseInput(lines.first()) println("First part: ${countLanternfishPopulationAfterNDays(lanternFish, 80)}") println("Second part: ${countLanternfishPopulationAfterNDays(lanternFish, 256)}") } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day6/Day6Kt$countLanternfishPopulationAfterNDays$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class day6.Day6Kt$countLanternfishPopulationAfterNDays$$inlined$groupingBy$1 implements kotlin.collections.Groupin...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day18/Day18.kt
package day18 import java.io.File sealed interface SnailFishNumber { val magnitude: Int } class SnailNumber(override var magnitude: Int) : SnailFishNumber { val isSplittable: Boolean get() = magnitude > 9 override fun toString(): String = magnitude.toString() fun split(parent: SnailPair): SnailPair = SnailPair(parent, SnailNumber(magnitude / 2), SnailNumber(magnitude - (magnitude / 2))) } class SnailPair(var parent: SnailPair?) : SnailFishNumber { constructor(parent: SnailPair?, left: SnailPair, right: SnailPair) : this(parent) { left.parent = this this.left = left right.parent = this this.right = right } constructor(parent: SnailPair?, left: SnailFishNumber, right: SnailFishNumber) : this(parent) { this.left = left this.right = right } lateinit var left: SnailFishNumber lateinit var right: SnailFishNumber private val isExploitable get() = left is SnailNumber && right is SnailNumber override val magnitude: Int get() = 3 * left.magnitude + 2 * right.magnitude override fun toString(): String = "[$left,$right]" fun reduceOnce(): Boolean = exploit(0) || split() fun reduce() { do { val hasReduced = reduceOnce() } while (hasReduced) } private fun split(): Boolean = when { // Returning true breaks the recursion (left as? SnailNumber)?.isSplittable ?: false -> { left = (left as SnailNumber).split(this) true } (left as? SnailPair)?.split() ?: false -> true (right as? SnailNumber)?.isSplittable ?: false -> { right = (right as SnailNumber).split(this) true } else -> (right as? SnailPair)?.split() ?: false } private fun exploit(level: Int): Boolean { fun sumToLeft(amount: Int, current: SnailPair, parent: SnailPair?) { if (parent == null) return else if (parent.left == current) sumToLeft(amount, parent, parent.parent) else { var leftNumber = parent.left while (leftNumber is SnailPair) leftNumber = leftNumber.right (leftNumber as SnailNumber).magnitude += amount } } fun sumToRight(amount: Int, current: SnailPair, parent: SnailPair?) { if (parent == null) return else if (parent.right == current) sumToRight(amount, parent, parent.parent) else { var rightNumber = parent.right while (rightNumber is SnailPair) rightNumber = rightNumber.left (rightNumber as SnailNumber).magnitude += amount } } fun exploit(pair: SnailPair) { sumToLeft((pair.left as SnailNumber).magnitude, pair, this) sumToRight((pair.right as SnailNumber).magnitude, pair, this) } return when { level >= 3 && (left as? SnailPair)?.isExploitable ?: false -> { exploit(left as SnailPair) left = SnailNumber(0) true } level >= 3 && (right as? SnailPair)?.isExploitable ?: false -> { exploit(right as SnailPair) right = SnailNumber(0) true } else -> (((left as? SnailPair)?.exploit(level + 1)) ?: false) || (((right as? SnailPair)?.exploit(level + 1)) ?: false) } } } fun parseSnailFishNumber(line: String): SnailPair { fun parseSnailFishNumber(input: Iterator<Char>, parent: SnailPair?): SnailFishNumber = when (val c = input.next()) { '[' -> { val pair = SnailPair(parent) pair.left = parseSnailFishNumber(input, pair) input.next() // ignoring comma pair.right = parseSnailFishNumber(input, pair) input.next() // consuming the closing ']' pair } // gotta be a digit since numbers greater than 9 are not allowed (must be split) else -> SnailNumber(c.digitToInt()) } return parseSnailFishNumber(line.iterator(), null) as SnailPair // The root is always a Pair } fun sum(n1: SnailPair, n2: SnailPair): SnailPair { val result = SnailPair(null, n1, n2) result.reduce() return result } fun main() { File("./input/day18.txt").useLines { lines -> val input = lines.toList() println(input.map { parseSnailFishNumber(it) }.reduce(::sum).magnitude) println(input .flatMap { x -> input.filterNot { it == x }.map { y -> x to y } } .maxOf { (x, y) -> sum(parseSnailFishNumber(x), parseSnailFishNumber(y)).magnitude }) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day18/Day18Kt.class", "javap": "Compiled from \"Day18.kt\"\npublic final class day18.Day18Kt {\n public static final day18.SnailPair parseSnailFishNumber(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 //...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day20/Day20.kt
package day20 import java.io.File private const val LIGHT_PIXEL = '#' private const val DARK_PIXEL = '.' fun parseInput(lines: List<String>): Pair<String, List<String>> = lines.first() to lines.drop(2) private fun square3x3(center: Pair<Int, Int>): List<Pair<Int, Int>> = listOf( // sorted according to the particular order in which the square has to be traversed -1 to -1, 0 to -1, 1 to -1, -1 to 0, 0 to 0, 1 to 0, -1 to 1, 0 to 1, 1 to 1, ).map { (x, y) -> center.first + x to center.second + y } fun enhanceImage(imageEnhancement: String, image: List<String>, iterations: Int): List<String> { fun computePixel(position: Pair<Int, Int>, image: List<String>, default: Char): Char { val index = square3x3(position) .map { (x, y) -> image.getOrNull(y)?.getOrNull(x) ?: default } .fold(0) { acc, pixel -> acc.shl(1) + if (pixel == LIGHT_PIXEL) 1 else 0 } return imageEnhancement[index] } fun iterate(image: List<String>, default: Char): List<String> { // the canvas extends in all directions indefinitely so the 'default' char in // the position 'out of the frame' is also subject to image enhancement effects // the default is the one that should be used when checking for an adjacent that's // out of the frame. This default will change depending on the algorithm val canvasWidth = image.firstOrNull()?.length ?: 0 val blankLine = listOf(default.toString().repeat(canvasWidth)) val expandedImage = blankLine + image + blankLine val outputImage = mutableListOf<String>() for ((y, line) in expandedImage.withIndex()) { val builder = StringBuilder() for (x in -1..(line.length + 1)) { builder.append(computePixel(x to y, expandedImage, default)) } outputImage.add(builder.toString()) } return outputImage } var default = DARK_PIXEL var outputImage = image repeat(iterations) { outputImage = iterate(outputImage, default) default = imageEnhancement[if (default == LIGHT_PIXEL) 511 else 0] } return outputImage } fun countLightPixels(image: List<String>): Int = image.sumOf { it.count { pixel -> pixel == LIGHT_PIXEL } } fun main() { File("./input/day20.txt").useLines { lines -> val (enhancement, image) = parseInput(lines.toList()) val output = enhanceImage(enhancement, image, 50) println(countLightPixels(output)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day20/Day20Kt.class", "javap": "Compiled from \"Day20.kt\"\npublic final class day20.Day20Kt {\n private static final char LIGHT_PIXEL;\n\n private static final char DARK_PIXEL;\n\n public static final kotlin.Pair<java.lang.String, java.util.List<j...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day16/Day16.kt
package day16 import java.io.File import java.util.Optional sealed interface Packet { val version: Int val value: Long } data class Literal(override val version: Int, override val value: Long) : Packet data class Op(override val version: Int, private val type: Int, val packets: List<Packet>) : Packet { override val value: Long get() = when (type) { 0 -> packets.sumOf { it.value } 1 -> packets.fold(1L) { acc, packet -> acc * packet.value } 2 -> packets.minOf { it.value } 3 -> packets.maxOf { it.value } 5 -> if (packets[0].value > packets[1].value) 1 else 0 6 -> if (packets[0].value < packets[1].value) 1 else 0 7 -> if (packets[0].value == packets[1].value) 1 else 0 else -> TODO("Operation $type is not supported") } } private val hexBinMap2 = (0..0xF).associate { n -> n.toString(16).first().uppercaseChar() to n.toString(2).padStart(4, '0') } fun hexToBits(input: String): Iterator<Char> = input.flatMap { hexBinMap2[it]!!.asIterable() }.iterator() // Syntax sugar methods that will carelessly throw exception if there aren't enough bits private fun Iterator<Char>.take(bits: Int): String = (1..bits).map { next() }.joinToString("") private fun Iterator<Char>.takeInt(bits: Int): Int = take(bits).toInt(2) fun decodePackets(input: Iterator<Char>): List<Packet> = sequence { while (input.hasNext()) { val next = decodeNextPacket(input) if (next.isPresent) yield(next.get()) } }.toList() fun decodeNPackets(input: Iterator<Char>, number: Int) = (1..number).map { decodeNextPacket(input).get() } fun decodeNextPacket(input: Iterator<Char>): Optional<Packet> = runCatching { val version = input.takeInt(3) val typeId = input.takeInt(3) return Optional.ofNullable( when (typeId) { 4 -> Literal(version, decodeLiteralPayload(input)) else -> Op(version, typeId, decodeOperatorPayload(input)) } ) }.getOrElse { Optional.empty() } private fun decodeLiteralPayload(input: Iterator<Char>): Long { tailrec fun rec(input: Iterator<Char>, number: Long): Long { val controlBit = input.next() val n = number.shl(4) + input.takeInt(4) return if (controlBit == '0') n else rec(input, n) } return rec(input, 0) } private fun decodeOperatorPayload(input: Iterator<Char>): List<Packet> = runCatching { when (input.next()) { '0' -> { // takes 15 bits to parse the size of the payload in bits decodePackets(boundedIteratorWrap(input, input.takeInt(15))) } '1' -> { // takes 11 bits to parse the number of packets in its payload decodeNPackets(input, input.takeInt(11)) } else -> TODO("Should never happen") } }.getOrElse { emptyList() } private fun boundedIteratorWrap(iterator: Iterator<Char>, limit: Int) = object : Iterator<Char> { private var counter = 0 override fun hasNext(): Boolean = iterator.hasNext() && counter < limit override fun next(): Char = if (hasNext()) { counter += 1 iterator.next() } else throw NoSuchElementException("End of bounded iterator") } fun sumAllVersionsOfTheTransmission(input: Iterator<Char>): Long { fun sumVersions(p: Packet): Long = when (p) { is Literal -> p.version.toLong() is Op -> p.packets.fold(p.version.toLong()) { acc, packet -> acc + sumVersions(packet) } } return decodePackets(input).fold(0L) { acc, packet -> acc + sumVersions(packet) } } fun evaluateTransmission(input: Iterator<Char>): Long = decodeNextPacket(input).get().value fun main() { File("./input/day16.txt").useLines { lines -> val transmission = lines.first() println(sumAllVersionsOfTheTransmission(hexToBits(transmission))) println(evaluateTransmission(hexToBits(transmission))) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day16/Day16Kt$decodePackets$1.class", "javap": "Compiled from \"Day16.kt\"\nfinal class day16.Day16Kt$decodePackets$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceSco...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day11/Day11.kt
package day11 import java.io.File import java.util.LinkedList fun parseMap(rows: List<String>): Array<IntArray> = rows.map { row -> row.trim().map { it - '0' }.toIntArray() }.toTypedArray() private fun expandAdjacentWithDiagonals(row: Int, column: Int, map: Array<IntArray>): List<Pair<Int, Int>> = (-1..1).flatMap { r -> (-1..1).map { c -> (r + row) to (c + column) } } .filterNot { (r, c) -> r < 0 || c < 0 || r >= map.size || c >= map[0].size || (r == row && c == column) } fun simulateStep(octopusMap: Array<IntArray>): Int { val traverseIndices = octopusMap.flatMapIndexed { index, row -> row.indices.map { index to it } } val cellsToVisit = LinkedList(traverseIndices) val visited = mutableSetOf<Pair<Int, Int>>() var flashes = 0 while (cellsToVisit.isNotEmpty()) { val current = cellsToVisit.removeFirst() val (x, y) = current when (octopusMap[x][y]) { 9 -> { octopusMap[x][y] = 0 visited.add(current) flashes += 1 cellsToVisit.addAll(expandAdjacentWithDiagonals(x, y, octopusMap)) } 0 -> if (!visited.contains(current)) octopusMap[x][y] += 1 // Can only flash once in (1..8) -> octopusMap[x][y] += 1 // 0 is intentionally ignored } } return flashes } fun simulateSteps(steps: Int, octopusMap: Array<IntArray>): Int = (1..steps).fold(0) { acc, _ -> acc + simulateStep(octopusMap) } fun countStepsUntilAllOctopusesSynchronize(octopusMap: Array<IntArray>): Int { fun allFlashed(map: Array<IntArray>): Boolean = map.all { energies -> energies.all { it == 0 } } return generateSequence(1) { it + 1 }.first { simulateStep(octopusMap) allFlashed(octopusMap) }.or(0) } fun main() { File("./input/day11.txt").useLines { lines -> val input = lines.toList() println(simulateSteps(100, parseMap(input))) println(countStepsUntilAllOctopusesSynchronize(parseMap(input))) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day11/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11Kt {\n public static final int[][] parseMap(java.util.List<java.lang.String>);\n Code:\n 0: aload_0\n 1: ldc #10 // Str...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day10/Day10.kt
package day10 import java.io.File import java.util.LinkedList // Poor man's Either -> Pair<A?, B?> fun findMissingSequenceOrOffendingChar(line: String): Pair<Char?, String?> { val missingSequence = LinkedList<Char>() line.forEach { c -> when (c) { '(' -> missingSequence.addFirst(')') '[' -> missingSequence.addFirst(']') '{' -> missingSequence.addFirst('}') '<' -> missingSequence.addFirst('>') ')', ']', '}', '>' -> if (missingSequence.firstOrNull() == c) missingSequence.removeFirst() else return (c to null) } } return null to missingSequence.joinToString("") } private val syntaxCheckerScoreMap = mutableMapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) fun sumScoreOfCorruptedLines(lines: List<String>): Int = lines .map { findMissingSequenceOrOffendingChar(it).first } .sumOf { maybeChar -> maybeChar?.let { c -> syntaxCheckerScoreMap[c] } ?: 0 } private val autocompleteScoreMap = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4, ) fun computeMiddleScoreOfIncompleteLinesMissingChars(lines: List<String>): Long { fun computeScoreOfAutocomplete(sequence: String): Long = sequence.map { autocompleteScoreMap[it]!! }.fold(0L) { acc, score -> (acc * 5L) + score } val scores = lines .map { findMissingSequenceOrOffendingChar(it).second } .filterNot { it.isNullOrBlank() } .map { computeScoreOfAutocomplete(it!!) } .sorted() return scores[scores.size / 2] } fun main() { File("./input/day10.txt").useLines { lines -> val input = lines.toList() println(sumScoreOfCorruptedLines(input)) println(computeMiddleScoreOfIncompleteLinesMissingChars(input)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day10/Day10Kt.class", "javap": "Compiled from \"Day10.kt\"\npublic final class day10.Day10Kt {\n private static final java.util.Map<java.lang.Character, java.lang.Integer> syntaxCheckerScoreMap;\n\n private static final java.util.Map<java.lang.Chara...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day17/Day17.kt
package day17 import java.io.File import kotlin.math.absoluteValue import kotlin.math.min import kotlin.math.sqrt fun parseInput(line: String): Pair<IntRange, IntRange> { val rawXRange = line.split("x=")[1].split(",")[0] val rawYRange = line.split("y=")[1] val (minX, maxX) = rawXRange.split("..").map(String::toInt) val (minY, maxY) = rawYRange.split("..").map(String::toInt) return minX..maxX to minY..maxY } private fun Double.hasDecimals(): Boolean = this % 1.0 != 0.0 /* * Solving t^2 - (2*C + 1)*t + 2*Y = 0; where * - C is the vertical velocity * - Y is any of the valid positions in rangeY * * There's probably a better way, but I'm only OK-ish with Maths * * Returns a map time => all vertical velocities that will make it to the target area */ fun samplingInitialVy(rangeY: IntRange): Map<Int, List<Int>> { val minTheoreticalVelocityY = rangeY.minOf { it } // going straight from S0 to SX in one unit of time /* With the current formula, given an initial Vy, when time = 2*Vy + 1 the vertical space travelled is 0 - If the target is below the Y axis then in the next 'moment' Vy(t) will be greater than the greatest distance from the Y axis which will cause the probe to miss the area - If the target is above the Y axis then we are in the same case but one step before reaching the 0 sum. The limit in that case will be the greatest distance to the Y axis as any greater speed will be short and then miss the target */ val maxTheoreticalVelocity = rangeY.maxOf { it.absoluteValue } // the furthest distance from the Y axis var candidate = minTheoreticalVelocityY // starting with the min velocity possible val solutionsByTime = mutableListOf<Pair<Int, Int>>() do { val b = -((2 * candidate) + 1) val squaredB = 1.0 * b * b val solutions = mutableListOf<Int>() for (y in rangeY) { val ac4 = 4 * 2 * y if (ac4 > squaredB) continue val root = sqrt(squaredB - ac4) val localSolutions = listOf( (-b + root) / 2, (-b - root) / 2 ).filterNot { it < 0 || it.hasDecimals() }.map { it.toInt() } // t can only be a positive integer because: // [a] can't travel back in time // [b] the granularity of the problem is in units of time solutions.addAll(localSolutions) } solutionsByTime.addAll(solutions.associateWith { candidate }.toList()) candidate += 1; } while (candidate <= maxTheoreticalVelocity) return solutionsByTime.groupBy { it.first }.mapValues { (_, v) -> v.map { it.second } } } /* * Values for initial horizontal velocity Vx, aka Vx(0), are determined by the elapsed time, given that: * - Vx(t) = min(0, Vx(t-1) - 1) * - After time t, * Sx(t) = Vx(0) * min(Vx(0), t) - [1, min(Vx(0), t)) # IMPORTANT, the range is end exclusive * * Sx(t) is the distance traveled at the given initial velocity during time t. For the velocity to be * considered valid, Sx(t) must belong to rangeX */ private fun samplingInitialVxForGivenTime(time: Int, rangeX: IntRange): List<Int> { val candidates = (rangeX.first / time)..rangeX.last return candidates.filter { vx -> val sx = vx * min(vx, time) - (1 until min(vx, time)).sum() sx in rangeX } } fun findAllPossibleSolutions(rangeX: IntRange, rangeY: IntRange): List<Pair<Int, Int>> = samplingInitialVy(rangeY).flatMap { (time, vys) -> val solutionSpaceForX = samplingInitialVxForGivenTime(time, rangeX) solutionSpaceForX.flatMap { vx -> vys.map { vy -> vx to vy } } }.distinct() fun findMaxInitialVerticalVelocity(rangeY: IntRange) = samplingInitialVy(rangeY).mapValues { (_, vs) -> vs.maxOf { it } }.maxByOrNull { it.value }!! fun computeMaxHeight(time: Int, initialVerticalVelocity: Int): Int = (initialVerticalVelocity downTo 0).take(time).sum() fun main() { File("./input/day17.txt").useLines { lines -> val areaDefinition = lines.first() val (rangeX, rangeY) = parseInput(areaDefinition) val (time, maxInitialVerticalSpeed) = findMaxInitialVerticalVelocity(rangeY) println(computeMaxHeight(time, maxInitialVerticalSpeed)) println(findAllPossibleSolutions(rangeX, rangeY).size) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day17/Day17Kt.class", "javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n public static final kotlin.Pair<kotlin.ranges.IntRange, kotlin.ranges.IntRange> parseInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ld...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day21/Day21.kt
package day21 // Syntax sugar private fun <N> Pair<N, N>.swap() = second to first private fun Pair<Long, Long>.max() = if (first > second) first else second private fun Pair<Long, Long>.addFirst(number: Long) = (first + number) to (second) private fun Pair<Long, Long>.timesEach(number: Long) = (first * number) to (second * number) private operator fun Pair<Long, Long>.plus(other: Pair<Long, Long>) = (first + other.first) to (second + other.second) data class GameState(val position: Int, val score: Int = 0) class GameRules(private val minScoreToWin: Int) { fun move(gameState: GameState, increment: Int): GameState { val newPosition = ((gameState.position - 1 + increment) % 10) + 1 return GameState(newPosition, gameState.score + newPosition) } fun hasWon(gameState: GameState): Boolean = gameState.score >= minScoreToWin } fun playDeterministicGame(initialPositionPlayer1: Int, initialPositionPlayer2: Int): Int { tailrec fun play( currentPlayer: GameState, otherPlayer: GameState, diceSeq: Sequence<Int>, diceRolledCount: Int, gameRules: GameRules ): Int { val p = gameRules.move(currentPlayer, diceSeq.take(3).sum()) return if (gameRules.hasWon(p)) otherPlayer.score * (diceRolledCount + 3) else play(otherPlayer, p, diceSeq.drop(3), diceRolledCount + 3, gameRules) } val deterministicDice = sequence { while (true) yieldAll(1..100) } return play(GameState(initialPositionPlayer1), GameState(initialPositionPlayer2), deterministicDice, 0, GameRules(1_000)) } fun countUniversesInWhichPlayerWins(initialPositionPlayer1: Int, initialPositionPlayer2: Int): Pair<Long, Long> { /* * Three dice with values 1, 2 and 3 generate the following 'universes' * - 1x sum = 3; 1x[1, 1, 1] * - 3x sum = 4; 3x[1, 1, 2] * - 6x sum = 5; 3x[1, 1, 3] + 3x[1, 2, 2] * - 7x sum = 6; 6x[1, 2, 3] + 1x[2, 2, 2] * - 6x sum = 7; 3x[2, 2, 3] + 3x[1, 3 ,3] * - 3x sum = 8; 3x[2, 3, 3] * - 1x sum = 9; 1x[3, 3, 3] */ fun incMultiplier(increment: Int): Long = when (increment) { 3, 9 -> 1 4, 8 -> 3 5, 7 -> 6 6 -> 7 else -> 0 } fun play(currentPlayer: GameState, otherPlayer: GameState, gameRules: GameRules): Pair<Long, Long> { var victoryCounter = 0L to 0L for (increment in 3..9) { val p = gameRules.move(currentPlayer, increment) if (gameRules.hasWon(p)) { victoryCounter = victoryCounter.addFirst(incMultiplier(increment)) } else { victoryCounter += play(otherPlayer, p, gameRules).swap().timesEach(incMultiplier(increment)) } } return victoryCounter } return play(GameState(initialPositionPlayer1), GameState(initialPositionPlayer2), GameRules(21)) } fun main() { // I'm not parsing such a small input :) // Starting point for player 1 is 2 // Starting point for player 2 is 5 println("Part one: ${playDeterministicGame(2, 5)}") println("Part two: ${countUniversesInWhichPlayerWins(2, 5).max()}") }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day21/Day21Kt.class", "javap": "Compiled from \"Day21.kt\"\npublic final class day21.Day21Kt {\n private static final <N> kotlin.Pair<N, N> swap(kotlin.Pair<? extends N, ? extends N>);\n Code:\n 0: aload_0\n 1: invokevirtual #13 ...
alxgarcia__advent-of-code-2021__d6b1009/src/main/kotlin/day19/Day19.kt
package day19 import java.io.File import kotlin.math.absoluteValue typealias Position = Triple<Int, Int, Int> typealias Transformation = (Triple<Int, Int, Int>) -> Triple<Int, Int, Int> private operator fun Position.plus(offset: Position): Position = Position(first + offset.first, second + offset.second, third + offset.third) private operator fun Position.minus(other: Position) = Position(first - other.first, second - other.second, third - other.third) data class Scanner(val beacons: List<Position>) { val distanceMatrix: Array<Array<Position>> get() = beacons.map { position -> beacons.map { (position - it) }.toTypedArray() }.toTypedArray() fun transform(t: Transformation): Scanner = this.copy(beacons = beacons.map(t)) } fun parseInput(lines: List<String>): List<Scanner> { fun parseBeacon(line: String): Position { val (x, y, z) = line.split(",").map(String::toInt) return Position(x, y, z) } val scanners = mutableListOf<Scanner>() val beacons = mutableListOf<Position>() for (line in lines) { when { line.isBlank() -> scanners.add(Scanner(beacons.toList())) line.startsWith("--- ") -> beacons.clear() else -> beacons.add(parseBeacon(line)) } } if (beacons.isNotEmpty()) scanners.add(Scanner(beacons.toList())) return scanners } /* Orientations over Z x y z y -x z -x -y z -y x z Orientations over -Z x -y -z -y -x -z -x y -z y x -z Orientations over X -z y x -y -z x z -y x y z x Orientations over -X z y -x y -z -x -z -y -x -y z -x Orientations over Y x -z y -z -x y -x z y z x y Orientations over -Y x z -y z -x -y -x -z -y -z x -y */ val orientations = listOf<Transformation>( // Orientations over Z { (x, y, z) -> Triple(x, y, z) }, { (x, y, z) -> Triple(y, -x, z) }, { (x, y, z) -> Triple(-x, -y, z) }, { (x, y, z) -> Triple(-y, x, z) }, // Orientations over -Z { (x, y, z) -> Triple(x, -y, -z) }, { (x, y, z) -> Triple(-y, -x, -z) }, { (x, y, z) -> Triple(-x, y, -z) }, { (x, y, z) -> Triple(y, x, -z) }, // Orientations over X { (x, y, z) -> Triple(-z, y, x) }, { (x, y, z) -> Triple(-y, -z, x) }, { (x, y, z) -> Triple(z, -y, x) }, { (x, y, z) -> Triple(y, z, x) }, // Orientations over -X { (x, y, z) -> Triple(z, y, -x) }, { (x, y, z) -> Triple(y, -z, -x) }, { (x, y, z) -> Triple(-z, -y, -x) }, { (x, y, z) -> Triple(-y, z, -x) }, // Orientations over Y { (x, y, z) -> Triple(x, -z, y) }, { (x, y, z) -> Triple(-z, -x, y) }, { (x, y, z) -> Triple(-x, z, y) }, { (x, y, z) -> Triple(z, x, y) }, // Orientations over -Y { (x, y, z) -> Triple(x, z, -y) }, { (x, y, z) -> Triple(z, -x, -y) }, { (x, y, z) -> Triple(-x, -z, -y) }, { (x, y, z) -> Triple(-z, x, -y) }, ) /* * For scanner s1, for every beacon compute the distance with the others * For scanner s2, apply one of the rotations and compute the distance matrix too * For each pair of matrix, check if for one row in s1 there's a matching row in s2 with at least minOverlap matching distances * If so, we got a pair of overlapping scanners given a certain orientation. * Subtracting both positions will return the distance between the position of the two scanners */ fun determineScannerLocation(s1: Scanner, s2: Scanner, minOverlaps: Int): Pair<Position, Scanner>? { val matrix1 = s1.distanceMatrix for (orientation in orientations) { val matrix2 = s2.transform(orientation).distanceMatrix val matchingBeacons = matrix1.mapIndexed { index, beaconDistances -> index to matrix2.indexOfFirst { distances -> beaconDistances.count { distances.contains(it) } >= minOverlaps } }.filterNot { it.second == -1 } if (matchingBeacons.size < minOverlaps) continue val (b1, b2) = matchingBeacons.first() val s2Center = s1.beacons[b1] - orientation(s2.beacons[b2]) // compute the discrepancy between the two positions of the same beacon val transformation = { position: Position -> orientation(position) + s2Center } // transforming to the PoV of scanner s1 return s2Center to s2.transform(transformation) } return null } /* * Returns the positions of the scanners and the position of the beacons from the PoV of the first scanner */ fun locateScannersAndBeacons(scanners: List<Scanner>, minOverlaps: Int): Pair<Set<Position>, Set<Position>> { val scannerPositions = mutableSetOf(Position(0, 0, 0)) // assuming the first scanner is at (0, 0, 0) val beaconPositions = scanners.first().beacons.toMutableSet() val recognisedScanners = mutableListOf(scanners.first()) val unrecognisedScanners = scanners.drop(1).toMutableList() while (unrecognisedScanners.isNotEmpty()) { val scanner = recognisedScanners.removeFirst() val scannersToCheck = unrecognisedScanners.listIterator() while (scannersToCheck.hasNext()) { val unrecognised = scannersToCheck.next() determineScannerLocation(scanner, unrecognised, minOverlaps)?.let { (position, transformedScanner) -> scannersToCheck.remove() recognisedScanners.add(transformedScanner) scannerPositions.add(position) beaconPositions.addAll(transformedScanner.beacons) } } } return scannerPositions to beaconPositions } private fun euclideanDistance(one: Position, other: Position): Int = (one.first - other.first).absoluteValue + (one.second - other.second).absoluteValue + (one.third - other.third).absoluteValue private fun findMaxEuclideanDistance(positions: Iterable<Position>): Int = positions.maxOf { p1 -> positions.maxOf { p2 -> euclideanDistance(p1, p2) } } fun findMaxEuclideanDistance(scanners: List<Scanner>, minOverlaps: Int): Int { val (centers, _) = locateScannersAndBeacons(scanners, minOverlaps) return findMaxEuclideanDistance(centers) } fun main() { File("./input/day19.txt").useLines { lines -> val scanners = parseInput(lines.toList()) val (scannerPositions, beaconPositions) = locateScannersAndBeacons(scanners, 12) println(beaconPositions.size) println(findMaxEuclideanDistance(scannerPositions)) } }
[ { "class_path": "alxgarcia__advent-of-code-2021__d6b1009/day19/Day19Kt.class", "javap": "Compiled from \"Day19.kt\"\npublic final class day19.Day19Kt {\n private static final java.util.List<kotlin.jvm.functions.Function1<kotlin.Triple<java.lang.Integer, java.lang.Integer, java.lang.Integer>, kotlin.Triple<...
JIghtuse__numeric-matrix-processor__15f4e0d/src/processor/Main.kt
package processor fun toIntList(s: String): List<Int> { return s.split(" ").filter { it.isNotEmpty() }.map { it.toInt() } } fun toDoubleList(s: String): List<Double> { return s.split(" ").filter { it.isNotEmpty() }.map { it.toDouble() } } class Matrix(val items: Array<List<Double>>) { val rows: Int = items.size val columns: Int = if (items.isEmpty()) 0 else items[0].size operator fun plus(other: Matrix): Matrix { if (rows != other.rows) throw Exception("Could not sum matrix of different dimensions (rows)") if (columns != other.columns) throw Exception("Could not sum matrix of different dimensions (columns)") return Matrix(Array(rows) { items[it].zip(other.items[it]) { x, y -> x + y } }) } operator fun times(scalar: Int): Matrix { return Matrix(Array(rows) { i -> List(columns) { j -> items[i][j] * scalar } }) } operator fun times(other: Matrix): Matrix { if (columns != other.rows) throw Exception("Invalid matrix dimensions") return Matrix(Array(rows) { i -> List(other.columns) { j -> dotProduct(other.items, i, j) } }) } private fun dotProduct(otherItems: Array<List<Double>>, thisRow: Int, otherColumn: Int): Double { var p = 0.0 for (k in 0 until columns) { p += items[thisRow][k] * otherItems[k][otherColumn] } return p } override fun toString(): String { return items.joinToString("\n") { it.joinToString(" ") } } companion object { fun readFromStdin(name: String): Matrix { print("Enter size of $name matrix: ") val (rows, columns) = toIntList(readLine()!!) println("Enter $name matrix:") return Matrix(Array(rows) { toDoubleList(readLine()!!) }) } } } fun main() { val actions = arrayListOf( "Exit", "Add matrices", "Multiply matrix to a constant", "Multiply matrices") val fs = arrayListOf( fun() { val a = Matrix.readFromStdin("first") val b = Matrix.readFromStdin("second") println("The sum result is: ") println(a + b) }, fun() { val a = Matrix.readFromStdin("a") print("Enter a constant: ") val c = readLine()!!.toInt() println("The multiplication result is: ") println(a * c) }, fun() { val a = Matrix.readFromStdin("first") val b = Matrix.readFromStdin("second") println("The multiplication result is: ") println(a * b) } ) fun printActions() { for (i in 1..actions.lastIndex) { println("$i. ${actions[i]}") } println("0. ${actions[0]}") } runLoop@ while (true) { printActions() val action = readLine()!!.toInt() try { when (action) { in 1..3 -> fs[action - 1]() 0 -> break@runLoop else -> throw Exception("Unknown action $action") } } catch (e: java.lang.Exception) { println("Error: ${e.message}") } } }
[ { "class_path": "JIghtuse__numeric-matrix-processor__15f4e0d/processor/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class processor.MainKt {\n public static final java.util.List<java.lang.Integer> toIntList(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 ...
jhreid__AdventOfCode2016__8eeb2bc/src/main/kotlin/day08/Main.kt
package day08 import java.io.File fun main() { val input = File("./day08.txt").readLines(Charsets.UTF_8) val screen = Array(6) { Array(50) { '.' } } val rectDigits = """.* (\d+)x(\d+)""".toRegex() val rotateDigits = """.*=(\d+) by (\d+)""".toRegex() input.forEach { instruction -> when { instruction.startsWith("rect") -> { val matchResult = rectDigits.find(instruction)!! val (xStr, yStr) = matchResult.destructured val x = xStr.toInt() - 1 val y = yStr.toInt() - 1 for (i in 0 .. y) { for (j in 0 .. x) { screen[i][j] = '#' } } } instruction.startsWith("rotate row") -> { val matchResult = rotateDigits.find(instruction)!! val (indexStr, amountStr) = matchResult.destructured val index = indexStr.toInt() val amount = amountStr.toInt() screen[index] = screen[index].slice(50 - amount..49).toTypedArray() + screen[index].slice(0..49 - amount).toTypedArray() } instruction.startsWith("rotate column") -> { val matchResult = rotateDigits.find(instruction)!! val (indexStr, amountStr) = matchResult.destructured val index = indexStr.toInt() val amount = amountStr.toInt() var col = CharArray(6) { '.' } for (i in 0 .. 5) { col[i] = screen[i][index] } col = col.slice(6 - amount .. 5).toCharArray() + col.slice(0 .. 5 - amount) for (i in 0 .. 5) { screen[i][index] = col[i] } } } } val totalLit = screen.flatten().fold(0) { acc, next -> acc + if (next == '#') 1 else 0 } println(totalLit) screen.forEach { println(it.joinToString("")) } }
[ { "class_path": "jhreid__AdventOfCode2016__8eeb2bc/day08/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class day08.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
jhreid__AdventOfCode2016__8eeb2bc/src/main/kotlin/day03/Main.kt
package day03 import java.io.File fun main() { val input = File("./day03.txt").readLines(Charsets.UTF_8) val valid = input.filter { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } val (one, two, three) = Triple(sides[0], sides[1], sides[2]) one + two > three && one + three > two && two + three > one } println("Part 1 valid: ${valid.size}") val valid1 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[0] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size val valid2 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[1] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size val valid3 = input.map { line -> val sides = line.trim().split("\\s+".toRegex()).map { it.toInt() } sides[2] }.chunked(3).filter { chunk -> val (one, two, three) = Triple(chunk[0], chunk[1], chunk[2]) one + two > three && one + three > two && two + three > one }.size println("Part 2 valid ${valid1 + valid2 + valid3}") }
[ { "class_path": "jhreid__AdventOfCode2016__8eeb2bc/day03/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class day03.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
philspins__adventofcode__138eac7/src/main/kotlin/twentytwenty/DayOne.kt
package twentytwenty import java.io.File import java.nio.file.Paths class DayOne { private var inputList: ArrayList<Int> = ArrayList<Int>() internal var partOneAnswer: Int = 0 internal var partTwoAnswer: Int = 0 fun loadInputFile(filename: String) { val path = Paths.get("").toAbsolutePath().toString() File("$path/$filename").forEachLine { inputList.add(it.toInt()) } } private fun quickSort(input: ArrayList<Int>): ArrayList<Int> { if (input.count() < 2) { return input } val pivot = input[input.count()/2] val equal = input.filter { it == pivot } as ArrayList<Int> val less = input.filter { it < pivot } as ArrayList<Int> val greater = input.filter { it > pivot } as ArrayList<Int> return (quickSort(less) + equal + quickSort(greater)) as ArrayList<Int> } fun solvePartOne() { if (inputList.count()==0) { loadInputFile("src/data/DayOneInput.txt") } var filtered = inputList.filter { it < 2020 } var sorted = quickSort(filtered as ArrayList<Int>) loop@ for (lowVal in sorted) { for (highVal in sorted.reversed()) { if (lowVal + highVal == 2020) { partOneAnswer = lowVal * highVal break@loop } } } } fun solvePartTwo() { if (inputList.count()==0) { loadInputFile("src/data/DayOneInput.txt") } var filtered = inputList.filter { it < 2020} var sorted = quickSort(filtered as ArrayList<Int>) loop@ for(first in sorted) { for(second in sorted.filter { it != first}) { for(third in sorted.filter { it != first && it != second }) { if (first + second + third == 2020) { partTwoAnswer = first * second * third break@loop } } } } } }
[ { "class_path": "philspins__adventofcode__138eac7/twentytwenty/DayOne.class", "javap": "Compiled from \"DayOne.kt\"\npublic final class twentytwenty.DayOne {\n private java.util.ArrayList<java.lang.Integer> inputList;\n\n private int partOneAnswer;\n\n private int partTwoAnswer;\n\n public twentytwenty....
hcknl__detekt__565d86d/detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/OffsetsToLineColumn.kt
package io.gitlab.arturbosch.detekt.formatting import java.util.ArrayList /** * Extracted and adapted from KtLint. */ internal fun calculateLineColByOffset(text: String): (offset: Int) -> Pair<Int, Int> { var i = -1 val e = text.length val arr = ArrayList<Int>() do { arr.add(i + 1) i = text.indexOf('\n', i + 1) } while (i != -1) arr.add(e + if (arr.last() == e) 1 else 0) val segmentTree = SegmentTree(arr.toTypedArray()) return { offset -> val line = segmentTree.indexOf(offset) if (line != -1) { val col = offset - segmentTree.get(line).left line + 1 to col + 1 } else { 1 to 1 } } } internal fun calculateLineBreakOffset(fileContent: String): (offset: Int) -> Int { val arr = ArrayList<Int>() var i = 0 do { arr.add(i) i = fileContent.indexOf("\r\n", i + 1) } while (i != -1) arr.add(fileContent.length) return if (arr.size != 2) { SegmentTree(arr.toTypedArray()).let { return { offset -> it.indexOf(offset) } } } else { _ -> 0 } } internal class SegmentTree(sortedArray: Array<Int>) { private val segments: List<Segment> fun get(i: Int): Segment = segments[i] fun indexOf(v: Int): Int = binarySearch(v, 0, this.segments.size - 1) private fun binarySearch(v: Int, l: Int, r: Int): Int = if (l > r) -1 else { val i = l + (r - l) / 2 val s = segments[i] if (v < s.left) binarySearch(v, l, i - 1) else (if (s.right < v) binarySearch(v, i + 1, r) else i) } init { require(sortedArray.size > 1) { "At least two data points are required" } sortedArray.reduce { r, v -> require(r <= v) { "Data points are not sorted (ASC)" }; v } segments = sortedArray.take(sortedArray.size - 1) .mapIndexed { i: Int, v: Int -> Segment(v, sortedArray[i + 1] - 1) } } } internal data class Segment(val left: Int, val right: Int)
[ { "class_path": "hcknl__detekt__565d86d/io/gitlab/arturbosch/detekt/formatting/OffsetsToLineColumnKt.class", "javap": "Compiled from \"OffsetsToLineColumn.kt\"\npublic final class io.gitlab.arturbosch.detekt.formatting.OffsetsToLineColumnKt {\n public static final kotlin.jvm.functions.Function1<java.lang.I...
minielectron__data-structure-and-coding-problems__f2aaff0/src/day7/FindSubarrayWithSumK.kt
package day7 import kotlin.math.min // Problem: You are given with an datastructure.array [1,4,5,3,6,8,4,0,8] // 1. find the subarray of length 3 whose sum is equal to 12. // fixed length problem // 2. find the minimum subarray whose sum is equal to 12. // dynamic window size length problem // 3. find how many subarray whose sum is equal to 12. // dynamic window size length problem fun fixedSizeSubArraySum(arr : IntArray, targetSum : Int) : Int{ var runningSum = 0 val windowSize = 3 for ((index, value) in arr.withIndex()){ runningSum += value if (index >= windowSize-1){ if (runningSum == targetSum) { return index - (windowSize -1) } runningSum -= arr[index - (windowSize -1)] } } return -1 // If no datastructure.array found } fun minimumSubarrayWithTargetSum(arr: IntArray, targetSum: Int) : Int { // returns size of minimum subarray var windowSum = 0 var windowStart = 0 var minSubarraySize = Integer.MAX_VALUE arr.forEachIndexed{ windowEnd, value -> windowSum += value while (windowSum >= targetSum){ if (windowSum == targetSum){ minSubarraySize = min(minSubarraySize, windowEnd - windowStart + 1) } windowSum -= arr[windowStart] windowStart++ } } return minSubarraySize // If no subarray with given sum found } fun howManySubarrayWithSumK(arr: IntArray, targetSum: Int) : Int { // returns size of minimum subarray var windowSum = 0 var windowStart = 0 var count = 0 arr.forEachIndexed{ windowEnd, value -> windowSum += value while (windowSum >= targetSum){ if (windowSum == targetSum){ count++ } windowSum -= arr[windowStart] windowStart++ } } return count // If no subarray with given sum found } fun main(){ val arr = intArrayOf(1,4,5,3,6,8,4,0,8) // case 1: // val index = fixedSizeSubArraySum( arr, 12) // if (index != -1){ // println(arr.slice(index..index+2)) // }else{ // print("No subarray with given sum found.") // } // case 2: // val size = minimumSubarrayWithTargetSum(arr, 8) // if (size == Integer.MAX_VALUE){ // println("No subarray found") // }else{ // print("Size of datastructure.array whose sum is 12 : $size") // } // case 3: println(howManySubarrayWithSumK(arr, 12)) }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/day7/FindSubarrayWithSumKKt.class", "javap": "Compiled from \"FindSubarrayWithSumK.kt\"\npublic final class day7.FindSubarrayWithSumKKt {\n public static final int fixedSizeSubArraySum(int[], int);\n Code:\n 0: aload_0\n ...
minielectron__data-structure-and-coding-problems__f2aaff0/src/day8/subarraySumAlgorithm.kt
package day8 // Problem : Given an datastructure.array of integers, you have find if there are two numbers whose sum is equal to k. // 2 Sum - k=2 class subarraySumAlgorithm { fun findTwoSum(a: IntArray, k: Int): Boolean { var end = a.size - 1 var start = 0 a.sort() while (start < a.size) { val sum = a[start] + a[end] when { sum > k -> { end-- } sum < k -> { start++ } else -> { return true } } } return false } fun findThreeSum(a: IntArray, k: Int): Boolean { var start = 0 val end = a.size - 1 while (start < end){ if (findTwoSum(a.copyOfRange(start+1, end), k -a[start])){ return true } start++ } return false } } fun main() { val twoSumAlgorithm = subarraySumAlgorithm() val a = intArrayOf(2, -1, 0, 3, 2, 1, -1, 2) a.sort() // println(twoSumAlgorithm.findTwoSum(a, 6)) println(twoSumAlgorithm.findThreeSum(a, 0)) println(twoSumAlgorithm.findThreeSum(a, 3)) println(twoSumAlgorithm.findThreeSum(a, 11)) }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/day8/subarraySumAlgorithm.class", "javap": "Compiled from \"subarraySumAlgorithm.kt\"\npublic final class day8.subarraySumAlgorithm {\n public day8.subarraySumAlgorithm();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
minielectron__data-structure-and-coding-problems__f2aaff0/src/day10/MinimumTimeDiff.kt
package day10 import kotlin.math.abs /* Given an datastructure.array of time datastructure.strings times, return the smallest difference between any two times in minutes. Example: Input: ["00:03", "23:59", "12:03"] Output: 4 Input: The closest 2 times are "00:03" and "23:59" (by wrap-around), and they differ by 4 minutes. Constraints: All datastructure.strings will be non-empty and in the format HH:mm */ fun main(){ var min = Integer.MAX_VALUE val input = listOf("00:03", "23:59", "12:03") var pair : Pair<Int, Int> = Pair(-1,-1) for( i in input.indices){ for (j in i+1 until input.size){ val d = getDifference(input[i], input[j]) if (min > d){ min = d pair = Pair(i, j) } } } println("diff = <${pair.first}, ${pair.second}>") } fun getDifference(first: String, second: String ) : Int { return abs(getMinutes(first) - getMinutes(second)) } fun getMinutes(time: String): Int { val t = time.split(":") val h : Int h = if (t[0] == "00") { 24 }else{ t[0].toInt() } val m = t[1].toInt() return abs(h * 60 + m) }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/day10/MinimumTimeDiffKt.class", "javap": "Compiled from \"MinimumTimeDiff.kt\"\npublic final class day10.MinimumTimeDiffKt {\n public static final void main();\n Code:\n 0: ldc #7 // int 214748364...
minielectron__data-structure-and-coding-problems__f2aaff0/src/datastructure/heap/StreamMax.kt
package datastructure.heap /** * <> Heap: Maximum Element in a Stream Implement a function named streamMax that processes a stream of integers and returns the maximum number encountered so far for each input number. This function should take in an array of integers and return a list of integers. Given an array of integers, your function should iterate over the array and for each number, it should find the maximum number in the array up until that point, including the current number. int[] nums = {1, 5, 2, 9, 3, 6, 8}; List<Integer> result = streamMax(nums); // Expected output: [1, 5, 5, 9, 9, 9, 9] // Explanation: The maximum number for the first number is 1, // for the first two numbers is 5, for the first three numbers is 5, and so on. * */ class StreamMax { fun findStreamMax(nums: IntArray): IntArray { val result = IntArray(nums.size) { Int.MIN_VALUE } val heap = Heap() nums.forEachIndexed { index, value -> heap.insert(value) result[index] = heap.getHeap()[0] } return result } } fun main() { val streamMax = StreamMax() // Test case 1 // Test case 1 val nums1 = intArrayOf(1, 5, 2, 9, 3, 6, 8) println("Test case 1:") println("Input: [1, 5, 2, 9, 3, 6, 8]") println("Expected output: [1, 5, 5, 9, 9, 9, 9]") val output = streamMax.findStreamMax(nums1) output.forEach { print("$it, ") } println() // Test case 2 // Test case 2 val nums2 = intArrayOf(10, 2, 5, 1, 0, 11, 6) println("Test case 2:") println("Input: [10, 2, 5, 1, 0, 11, 6]") println("Expected output: [10, 10, 10, 10, 10, 11, 11]") val output2 = streamMax.findStreamMax(nums2) output2.forEach { print("$it, ") } println() }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/datastructure/heap/StreamMaxKt.class", "javap": "Compiled from \"StreamMax.kt\"\npublic final class datastructure.heap.StreamMaxKt {\n public static final void main();\n Code:\n 0: new #8 // class...
minielectron__data-structure-and-coding-problems__f2aaff0/src/datastructure/heap/Heap.kt
package datastructure.heap class Heap { private val heap = arrayListOf<Int>() fun getHeap(): List<Int> { return heap.toList() } fun getLeftChild(index: Int): Int { return 2 * index + 1 } fun getRightChild(index: Int): Int { return 2 * index + 2 } private fun getParentIndex(index: Int): Int { return (index - 1) / 2 } fun insert(item: Int) { heap.add(item) heapifyUp() } private fun heapifyUp() { // For max heap var index = heap.size - 1 // Start at the last element while (hasParent(index) && parent(index) < heap[index]) { // While we have a parent and it's greater than the current node // Swap the current node with its parent swap(getParentIndex(index), index) // Move up the tree index = getParentIndex(index) } } private fun heapifyDown() { // for min heap var index = heap.size - 1 // Start at the last element while (hasParent(index) && parent(index) > heap[index]) { // While we have a parent and it's greater than the current node // Swap the current node with its parent swap(getParentIndex(index), index) // Move up the tree index = getParentIndex(index) } } fun remove() : Int? { if (heap.isEmpty()) return null if (heap.size == 1){ return heap.removeAt(0) } val maxValue = heap[0] heap[0] = heap.removeAt(heap.size -1) sinkDown(0) return maxValue } fun findKthSmallest(nums: IntArray, k: Int): Int? { val heap = Heap() if (nums.isEmpty()) return null if (k < 0 || k> nums.size) return null if (nums.size == 1) return heap.remove() for (i in nums.indices) { heap.insert(nums[i]) } val size = nums.size var actaulK = size - k var ans = -1 while (actaulK >= 0) { ans = heap.remove()!! actaulK-- } return ans } private fun sinkDown(index: Int) { var index = index var maxIndex = index while (true) { val leftIndex: Int = getLeftChild(index) val rightIndex: Int = getRightChild(index) if (leftIndex < heap.size && heap[leftIndex] > heap[maxIndex]) { maxIndex = leftIndex } if (rightIndex < heap.size && heap[rightIndex] > heap[maxIndex]) { maxIndex = rightIndex } index = if (maxIndex != index) { swap(index, maxIndex) maxIndex } else { return } } } private fun hasParent(index: Int) = getParentIndex(index) >= 0 private fun parent(index: Int) = heap[getParentIndex(index)] private fun swap(i: Int, j: Int) { val temp = heap[i] heap[i] = heap[j] heap[j] = temp } override fun toString(): String { return "$heap" } } fun main() { val heap = Heap() // Test case 1 // Test case 1 val nums1 = intArrayOf(7, 10, 4, 3, 20, 15) val k1 = 3 println("Test case 1:") println("Expected output: 7") System.out.println("Actual output: " + heap.findKthSmallest(nums1, k1)) println() // Test case 2 // Test case 2 val nums2 = intArrayOf(2, 1, 3, 5, 6, 4) val k2 = 2 println("Test case 2:") println("Expected output: 2") System.out.println("Actual output: " + heap.findKthSmallest(nums2, k2)) println() // Test case 3 // Test case 3 val nums3 = intArrayOf(9, 3, 2, 11, 7, 10, 4, 5) val k3 = 5 println("Test case 3:") println("Expected output: 7") System.out.println("Actual output: " + heap.findKthSmallest(nums3, k3)) println() }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/datastructure/heap/HeapKt.class", "javap": "Compiled from \"Heap.kt\"\npublic final class datastructure.heap.HeapKt {\n public static final void main();\n Code:\n 0: new #8 // class datastructure/...
minielectron__data-structure-and-coding-problems__f2aaff0/src/datastructure/graphs/Graphs.kt
package datastructure.graphs import java.util.LinkedList import java.util.PriorityQueue data class Edge(val source: Int, val destination: Int, val weight: Int) class Graphs(private val nodes: Int) { private val graph = Array(nodes) { ArrayList<Edge>() } // Fixed array size to 'nodes' fun createGraph() { graph[0].add(Edge(0, 2, 2)) graph[0].add(Edge(0, 3, 4)) graph[1].add(Edge(1, 0, 7)) graph[2].add(Edge(2, 1, 3)) graph[3].add(Edge(3, 4, 1)) } fun bfs() { if (graph.isEmpty()) { return } val queue = LinkedList<Int>() val visited = BooleanArray(nodes) // Initialize the queue with the first vertex (you can choose any starting vertex) queue.add(graph[0].first().source) // Starting vertex with source and destination as 0 while (queue.isNotEmpty()) { val curr = queue.poll() if (!visited[curr]) { visited[curr] = true println(curr) // Find neighbors of the current edge's destination val neighbours = findNeighbours(curr) // Enqueue unvisited neighbors for (neighbor in neighbours) { if (!visited[neighbor]) { queue.add(neighbor) } } } } } fun dfs(inputGraph: Array<ArrayList<Edge>>, curr: Int, visited: BooleanArray) { // O(V+E) // Step - 1 - Print the node print("$curr ") //Step 2- Mark visited true visited[curr] = true // Step 3 - Explore neighbour nodes val neighbours = findNeighbours(curr) for (n in neighbours) { if (!visited[n]) { dfs(inputGraph, n, visited) println() } } } fun size(): Int { return graph.size } private fun findNeighbours(vertex: Int): List<Int> { val neighbours = mutableListOf<Int>() // Implement your logic to find neighbors of 'vertex' here // You can iterate through 'graph' and identify edges connected to 'vertex' graph[vertex].forEach { neighbours.add(it.destination) } return neighbours } fun detectCycle(curr: Int, visited: BooleanArray, recurStack: BooleanArray): Boolean { // Works for directed nodes visited[curr] = true recurStack[curr] = true val neighbours = findNeighbours(curr) for (n in neighbours) { if (recurStack[n]) { return true // There is a cycle } else if (!visited[n]) { if (detectCycle(n, visited, recurStack)) { return true } } } recurStack[curr] = false return false } fun cycleDetectionInUndirectedGraph(curr: Int, visited: BooleanArray, parent: Int): Boolean { visited[curr] = true val neighbours = findNeighbours(curr) for (n in neighbours) { if (visited[n] && parent != n) { return true } else if (!visited[n]) { if (cycleDetectionInUndirectedGraph(n, visited, curr)) { return true } } } return false } fun printAllPaths(curr: Int, visited: BooleanArray, target: Int, path: String) { // O(V^V) // Base condition if (curr == target) { println(path) return } val neighbours = findNeighbours(curr) for (n in neighbours) { if (!visited[n]) { visited[curr] = true printAllPaths(n, visited, target, path.plus(n)) visited[curr] = false // Important } } } fun dijkstraAlgorithm(src: Int) { val pq = PriorityQueue<VertexPair>() val visited = BooleanArray(graph.size) { false } // Here we are tricking which will work in case starting node is zero but won't work for others. pq.add(VertexPair(src, 0)) val distance = IntArray(graph.size) for (i in distance.indices) { if (i != src) { distance[i] = Int.MAX_VALUE } } while (pq.isNotEmpty()) { val curr: VertexPair = pq.remove() if (!visited[curr.node]) { visited[curr.node] = true } for (i in graph[curr.node].indices) { val edge: Edge = graph[curr.node][i] val u = edge.source val v = edge.destination // Relaxation step if (distance[u] + edge.weight < distance[v]) { distance[v] = distance[u] + edge.weight pq.add(VertexPair(v, distance[v])) } } } for (d in distance) { print("$d ->") } } fun bellmanfordAlgo(src: Int) { val V = graph.size val dist = IntArray(V) for (i in graph.indices) { if (src != i) { dist[i] = Int.MAX_VALUE } } for (k in 0 until V - 1) { for (i in 0 until V) { for (j in graph[i].indices) { val edge = graph[i][j] val u = edge.source val v = edge.destination if (dist[u] != Int.MAX_VALUE && dist[u] + edge.weight < dist[v]) { dist[v] = dist[u] + edge.weight } } } } for (d in dist) { print("$d ->") } } fun primsMst(src: Int) { val pq = PriorityQueue<VertexPair>() pq.add(VertexPair(0, 0)) // Non mst val visited = BooleanArray(graph.size) { false } var cost = 0 while (pq.isNotEmpty()) { val curr = pq.poll() if (!visited[curr.node]) { visited[curr.node] = true cost += curr.distance for (i in graph[curr.node].indices) { val edge = graph[curr.node][i] if (!visited[edge.destination]) { pq.add(VertexPair(edge.destination, edge.weight)) } } } } println("\nTotal path cost = $cost") } fun topSort(): LinkedList<Int> { val visited = BooleanArray(6) { false } val stack = LinkedList<Int>() for (node in graph.indices) { if (!visited[node]) { topologicalSort(node, visited, stack) } } return stack } private fun topologicalSort(curr: Int, visited: BooleanArray, stack: LinkedList<Int>) { visited[curr] = true val neighbours = findNeighbours(curr) for (n in neighbours) { if (!visited[n]) { topologicalSort(n, visited, stack) } } stack.push(curr) // DFS + push to stack } /** * This algorithm is used to find the strongly connected components inside a graph. * A graph is called strongly connected if all the nodes can be reached from each of the nodes. * * There are three steps to find the SCC. * * 1. Get nodes in stack(Topological sort) * 2. Transpose the graph * 3. Do DFS according to stack nodes on the transpose graph. * */ fun kosarajuAlgorithm() { val visited = BooleanArray(graph.size) { false } // Step 1 val stack = topSort() // Step 2 -- Transpose the graph val transposeGraph = Array(graph.size) { ArrayList<Edge>() } for (i in graph.indices) { for (j in graph[i].indices) { val edge = graph[i][j] transposeGraph[edge.destination].add( Edge( source = edge.destination, destination = edge.source, weight = edge.weight ) ) } } println("Graph") graph.forEach { println(it) } println("Transpose") transposeGraph.forEach { println(it) } // Step 3 -- Do DFS on stack nodes println("Stack") println(stack) while (stack.isNotEmpty()) { val node = stack.pop() if (!visited[node]) { dfs(transposeGraph, node, visited) println() } } } } class VertexPair(val node: Int, val distance: Int) : Comparable<VertexPair> { override fun compareTo(other: VertexPair): Int { return distance - other.distance } override fun toString(): String { return "[$node, $distance]" } } fun main() { val graph = Graphs(5) graph.createGraph() // graph.bfs() // val visited = BooleanArray(graph.size()) { false } // visited.forEachIndexed { index, value -> // if (!value) { // graph.dfs(index, visited) // } // } // val visitedCycles = BooleanArray(graph.size()) { false } // val recurStack = BooleanArray(graph.size()) { false } // println(graph.detectCycle(0, visitedCycles, recurStack)) // val startNode = 0 // val pathVisited = BooleanArray(graph.size()) // println("\nAll paths are : ") // graph.printAllPaths(startNode, pathVisited, 4, "$startNode") // println("Topological sort ") // topSort(graph) // println("Cycle detection in undirected graph") // val visited = BooleanArray(4){false} // println(graph.cycleDetectionInUndirectedGraph(0, visited, -1)) // graph.bellmanfordAlgo(0) // graph.primsMst(0) graph.kosarajuAlgorithm() }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/datastructure/graphs/GraphsKt.class", "javap": "Compiled from \"Graphs.kt\"\npublic final class datastructure.graphs.GraphsKt {\n public static final void main();\n Code:\n 0: new #8 // class data...
minielectron__data-structure-and-coding-problems__f2aaff0/src/datastructure/graphs/RootenOranges.kt
package datastructure.graphs /** * You are given an m x n grid where each cell can have one of three values: ● 0 representing an empty cell, ● 1 representing a fresh orange, * or ● 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. * Return the minimum number of minutes that must elapse until no cell has a fresh orange. * If this is impossible, return -1. * * Example 1 Input: grid = [[2,1,1],[1,1,0],[0,1,1]] * Output: 4 * * Example 2 Input: grid = [[2,1,1],[0,1,1],[1,0,1]] * Output: -1 Explanation: * * The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally * */ import java.util.LinkedList import java.util.Queue fun orangesRotting(grid: Array<IntArray>): Int { val rows = grid.size val cols = grid[0].size // Define four possible directions (up, down, left, right) val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) // Initialize a queue to perform BFS val queue: Queue<kotlin.Pair<Int, Int>> = LinkedList() // Initialize variables to keep track of time and fresh oranges var minutes = 0 var freshOranges = 0 // Enqueue all rotten oranges and count fresh oranges // This step also ensure to handle multiple rotten oranges at same time. for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == 2) { queue.offer(Pair(i, j)) } else if (grid[i][j] == 1) { freshOranges++ } } } // Perform BFS while (queue.isNotEmpty()) { val size = queue.size for (i in 0 until size) { val (x, y) = queue.poll() for (direction in directions) { val newX = x + direction[0] val newY = y + direction[1] if (newX in 0 until rows && newY in 0 until cols && grid[newX][newY] == 1) { grid[newX][newY] = 2 freshOranges-- queue.offer(Pair(newX, newY)) } } } minutes++ } // If there are still fresh oranges left, it's impossible to rot them all return if (freshOranges == 0) minutes else -1 } fun main() { val grid1 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(1, 1, 0), intArrayOf(0, 1, 2) ) val grid2 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(0, 1, 1), intArrayOf(1, 0, 1) ) println(orangesRotting(grid1)) // Output: 4 println(orangesRotting(grid2)) // Output: -1 } fun printMatrix(matrix: Array<IntArray>){ for (i in matrix.indices) { for (j in matrix[i].indices) { print("${matrix[i][j]} \t") } println() } }
[ { "class_path": "minielectron__data-structure-and-coding-problems__f2aaff0/datastructure/graphs/RootenOrangesKt.class", "javap": "Compiled from \"RootenOranges.kt\"\npublic final class datastructure.graphs.RootenOrangesKt {\n public static final int orangesRotting(int[][]);\n Code:\n 0: aload_0\n ...
igorwojda__kotlin-coding-challenges__b09b738/src/test/kotlin/com/igorwojda/string/issubstring/Solution.kt
package com.igorwojda.string.issubstring // Time complexity: O(n*m) // Space complexity: O(1) // // Optimal solution using double pointer. private object Solution1 { private fun isSubstring(str: String, subStr: String): Boolean { if (subStr.isEmpty()) return true if (str.length < subStr.length) return false var pointer1 = 0 var pointer2 = 0 while (pointer1 <= str.lastIndex) { if (str[pointer1] == subStr[pointer2]) { pointer1++ pointer2++ if (pointer2 == subStr.length) { return true } } else { pointer1 = pointer1 - pointer2 + 1 pointer2 = 0 } } return false } } // Time complexity: O(n*m) // Space complexity: ??, but more than O(1) // Number of iterations (n) is bounded by the length of the first string // and String.drop requires copying the entire remaining string (on it's own it has O(m) complexity) // First of 5 chars, needs 5 iterations at most and 15 character copied (5+4+3+2+1=15). Second is copied less often. // // Recursive solution private object Solution2 { private fun isSubstring(str: String, subStr: String): Boolean { fun isExactMatch(str: String, subStr: String): Boolean { if (subStr.length > str.length) { return false } return when { str.isEmpty() && subStr.isEmpty() -> true str.isNotEmpty() && subStr.isEmpty() -> true else -> str[0] == subStr[0] && isExactMatch(str.drop(1), subStr.drop(1)) } } if (subStr.length > str.length) { return false } if (str.isEmpty() || subStr.isEmpty()) { return true } return isExactMatch(str, subStr) || isSubstring(str.drop(1), subStr) } } private object Solution3 { private fun isSubstring(str: String, subStr: String): Boolean { if (subStr.isEmpty()) return true return str .windowed(subStr.length) .any { it == subStr } } } // Time complexity: O(n*m) // Space complexity: O(1) // This recursive solution is faster than solution with String.drop because it uses double pointer // // Recursive solution private fun isSubstring(str: String, subStr: String): Boolean { if (subStr.isEmpty()) { return true } fun helper(first: String, second: String, firstPointer1: Int = 0, secondPointer2: Int = 0): Boolean { if (firstPointer1 > first.lastIndex) { return false } return if (first[firstPointer1] == second[secondPointer2]) { val localPointer1 = firstPointer1 + 1 val localPointer2 = secondPointer2 + 1 when { localPointer1 <= first.lastIndex && localPointer2 <= second.lastIndex -> { helper(first, second, localPointer1, localPointer2) } localPointer2 <= second.lastIndex && localPointer1 > first.lastIndex -> false else -> true } } else { val p1 = firstPointer1 - secondPointer2 + 1 if (p1 > first.lastIndex) { return false } else { helper(first, second, p1, 0) } } } return helper(str, subStr) }
[ { "class_path": "igorwojda__kotlin-coding-challenges__b09b738/com/igorwojda/string/issubstring/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class com.igorwojda.string.issubstring.SolutionKt {\n private static final boolean isSubstring(java.lang.String, java.lang.String);\n Co...
hectdel__aco-kotlin-2022__cff5677/src/Day03/Day03.kt
package Day03 import java.io.File fun main() { val chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun Char.toValue(): Int = chars.indexOf(this) + 1 check('p'.toValue() == 16) check('L'.toValue() == 38) fun part1(input: String): Int { var commonChars = mutableListOf<Char>() input.lines() .map { it.substring(0, it.length.div(2)) to it.substring(it.length.div(2), it.length) } .map { it.first.iterator().forEach { char -> if (it.second.contains(char)) { commonChars.add(char) return@map } } } return commonChars.map { it.toValue() }.sum() } fun containsChar(c: Char, line:String):Boolean { return line.contains(c) } fun calculateResult(n: Int, input: String) : Int{ val grouped = input .lines() .chunked(n) return grouped.sumOf { it.first() .toCharArray() .first { char -> IntRange(1, n - 1).all { n -> containsChar(char, it[n]) } } .toValue() } } fun part2(input: String): Int { return calculateResult(3, input) } val testInput = File("src/Day03/test_data.txt").readText() println(part1(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70 ) val input = File("src/Day03/data.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "hectdel__aco-kotlin-2022__cff5677/Day03/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03.Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\n ...
hectdel__aco-kotlin-2022__cff5677/src/Day02/Day02.kt
package Day02 import java.io.File fun main() { fun playResult(play: String): Int { val splitPlay = play.split(" ") val play = Play(splitPlay[0], splitPlay[1]); return play.selScore() + play.resScore() } fun playResultPart2(play: String): Int { val splitPlay = play.split(" ") val play = Play(splitPlay[0], splitPlay[1]); return play.selAndEndScore() } fun part1(input: String): Int { return input .lines() .fold(0) { acc, play -> acc + playResult(play) } } fun part2(input: String): Int { return input .lines() .fold(0) { acc, play -> acc + playResultPart2(play) } } // test if implementation meets criteria from the description, like: val testInput = File("src/Day02/Day02_test.txt").readText() check(part1(testInput) == 15) check(part2(testInput) == 12) val input = File("src/Day02/data.txt").readText() println(part1(input)) println(part2(input)) } class Play(val opponent: String, val you: String) { fun selScore(): Int { return when (you) { in "X" -> 1 in "Y" -> 2 in "Z" -> 3 else -> 0 } } fun resScore(): Int { return when (you) { in "X" -> when (opponent) { "A" -> 3 "B" -> 0 else -> 6 } in "Y" -> when (opponent) { "A" -> 6 "B" -> 3 else -> 0 } else -> when (opponent) { "A" -> 0 "B" -> 6 else -> 3 } } } fun recScore(op: String, you: String): Int { val play = Play(op, you); return return play.selScore() + play.resScore() } fun selAndEndScore(): Int { return when (opponent) { in "A" -> when (you) { "X" -> recScore("A", "Z") "Y" -> recScore("A", "X") else -> recScore("A", "Y") } in "B" -> when (you) { "X" -> recScore("B", "X") "Y" -> recScore("B", "Y") else -> recScore("B", "Z") } else -> when (you) { "X" -> recScore("C", "Y") "Y" -> recScore("C", "Z") else -> recScore("C", "X") } } } }
[ { "class_path": "hectdel__aco-kotlin-2022__cff5677/Day02/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02.Day02Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
burriad__functional-kotlin__d27e471/functional-kotlin-basics-solution/src/main/kotlin/ch/sbb/functionalkotlin/basics/Recursion.kt
package ch.sbb.functionalkotlin.basics // 2.1 Given the function prepend, write a recursive function concat that concatenates a list of chars to a string fun prepend(c: Char, s: String): String = "$c$s" fun concat(chars: List<Char>): String = if (chars.isEmpty()) "" else prepend(chars.first(), concat(chars.takeLast(chars.size - 1))) // 2.2 Create a recursive version of a function that computes the n-th number in the Fibonacci sequence // Hint: the Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, 21; hence the n-th number in the sequence is the sum of the (n-2)th and (n-1)th numbers fun fibRec(n: Int): Int = when (n) { 0 -> 0 1 -> 1 else -> fibRec(n - 1) + fibRec(n - 2) } // 2.3 (HARD) Create a tail-recursive version of the function in 2.2 fun fibCorec(n: Int): Int { tailrec fun _fib(n: Int, prev2: Int, prev1: Int): Int = when (n) { 0 -> prev2 1 -> prev1 else -> _fib(n - 1, prev1, prev2 + prev1) } return _fib(n, 0, 1) } // 2.4 (Extra) Write a binary search function which takes a sorted list of ints and checks whether an element is present fun binarySearch(value: Int, list: List<Int>): Boolean = when { list.isEmpty() -> false list[middle(list)] < value -> binarySearch(value, list.subList(0, middle(list))) list[middle(list)] > value -> binarySearch(value, list.subList(middle(list) + 1, list.size)) else -> true // list[middle(list)] == value } fun middle(list: List<Int>) = list.size / 2
[ { "class_path": "burriad__functional-kotlin__d27e471/ch/sbb/functionalkotlin/basics/RecursionKt.class", "javap": "Compiled from \"Recursion.kt\"\npublic final class ch.sbb.functionalkotlin.basics.RecursionKt {\n public static final java.lang.String prepend(char, java.lang.String);\n Code:\n 0: alo...
ArcaDone__DodgeTheEnemies__2413375/util/src/main/java/com/arcadan/util/math/QuadraticEquation.kt
package com.arcadan.util.math import java.lang.Math.* import kotlin.math.pow data class QuadraticEquation(val a: Double, val b: Double, val c: Double) { data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> "${i}i" else -> "$r + ${i}i" } } data class Solution(val x1: Any, val x2: Any) { override fun toString() = when(x1) { x2 -> "X1,2 = $x1" else -> "X1 = $x1, X2 = $x2" } } val quadraticRoots by lazy { val _2a = a + a val d = b * b - 4.0 * a * c // discriminant if (d < 0.0) { val r = -b / _2a val i = kotlin.math.sqrt(-d) / _2a Solution(Complex(r, i), Complex(r, -i)) } else { // avoid calculating -b +/- sqrt(d), to avoid any // subtractive cancellation when it is near zero. val r = if (b < 0.0) (-b + kotlin.math.sqrt(d)) / _2a else (-b - kotlin.math.sqrt(d)) / _2a Solution(r, c / (a * r)) } } fun obtainYForXValue(x: Double) : Double = ((x.pow(2) * a) + (x * b) + c) }
[ { "class_path": "ArcaDone__DodgeTheEnemies__2413375/com/arcadan/util/math/QuadraticEquation$Solution.class", "javap": "Compiled from \"QuadraticEquation.kt\"\npublic final class com.arcadan.util.math.QuadraticEquation$Solution {\n private final java.lang.Object x1;\n\n private final java.lang.Object x2;\n...
dmstocking__levenshtein__3060966/src/main/kotlin/com/github/dmstocking/levenshtein/Levenshtein.kt
package com.github.dmstocking.levenshtein import kotlin.math.min class Levenshtein(private var height: Int = 16, private var width: Int = 16) { private var distance = Array(height) { Array(width) { 0 } } init { for (i in 0 until width) { distance[i][0] = i } for (j in 0 until height) { distance[0][j] = j } } fun distance(a: String, b: String): Int { val rows = a.length val columns = b.length growToFit(rows, columns) for (j in 1..columns) { for (i in 1..rows) { val substitutionCost = if (a[i-1] == b[j-1]) 0 else 1 distance[i][j] = min( distance[i-1][j ] + 1, // delete distance[i ][j-1] + 1, // insert distance[i-1][j-1] + substitutionCost // substitution ) } } return distance[rows][columns] } private fun growToFit(rows: Int, columns: Int) { while (width < rows + 2 || height < columns + 2) { height *= 2 width *= 2 } distance = Array(height) { Array(width) { 0 } } for (i in 0 until width) { distance[i][0] = i } for (j in 0 until height) { distance[0][j] = j } } } fun min(vararg values: Int): Int { return values.reduce { current, next -> min(current, next) } }
[ { "class_path": "dmstocking__levenshtein__3060966/com/github/dmstocking/levenshtein/LevenshteinKt.class", "javap": "Compiled from \"Levenshtein.kt\"\npublic final class com.github.dmstocking.levenshtein.LevenshteinKt {\n public static final int min(int...);\n Code:\n 0: aload_0\n 1: ldc ...
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin2023/Day005.kt
package main.kotlin2023 class Day005 { fun part1(lines: String): Long { val parsedInput = parseInput(lines) val seeds = parsedInput.get(0).get(0) val seedMaps = parsedInput.drop(1) val locationValues = mutableSetOf<Long>() for (seed in seeds) { val foundCorrespondent = findCorrespondent(seed, seedMaps[0]) val foundCorrespondent2 = findCorrespondent(foundCorrespondent, seedMaps[1]) val foundCorrespondent3 = findCorrespondent(foundCorrespondent2, seedMaps[2]) val foundCorrespondent4 = findCorrespondent(foundCorrespondent3, seedMaps[3]) val foundCorrespondent5 = findCorrespondent(foundCorrespondent4, seedMaps[4]) val foundCorrespondent6 = findCorrespondent(foundCorrespondent5, seedMaps[5]) val foundCorrespondentFinal = findCorrespondent(foundCorrespondent6, seedMaps[6]) locationValues.add(foundCorrespondentFinal) } return locationValues.min() } fun part2(lines: String): Long { val parsedInput = parseInput(lines) val seedsRaw = parsedInput.get(0).get(0) // val seeds = mutableSetOf<Long>() // for (i in 0..seedsRaw.size - 2 step 2) { // seeds.addAll(seedsRaw[i]..seedsRaw[i] + seedsRaw[i + 1]) // } val seeds = sequence { for (i in 0..seedsRaw.size-2 step 2) { yieldAll(seedsRaw[i] .. seedsRaw[i]+seedsRaw[i+1]) } } val seedMaps = parsedInput.drop(1) val locationValues = mutableSetOf<Long>() for (seed in seeds) { val foundCorrespondent = findCorrespondent(seed, seedMaps[0]) val foundCorrespondent2 = findCorrespondent(foundCorrespondent, seedMaps[1]) val foundCorrespondent3 = findCorrespondent(foundCorrespondent2, seedMaps[2]) val foundCorrespondent4 = findCorrespondent(foundCorrespondent3, seedMaps[3]) val foundCorrespondent5 = findCorrespondent(foundCorrespondent4, seedMaps[4]) val foundCorrespondent6 = findCorrespondent(foundCorrespondent5, seedMaps[5]) val foundCorrespondentFinal = findCorrespondent(foundCorrespondent6, seedMaps[6]) locationValues.add(foundCorrespondentFinal) } return locationValues.min() } private fun findCorrespondent(source: Long, targets: List<List<Long>>): Long { for (target in targets) { if (source >= target[1] && source <= target[1] + target[2]) { return target[0] + source - target[1] } } return source } private fun parseInput(input: String) = input.split("\n\n") .map { eachLine -> eachLine.split("\n") .map { it.dropWhile { !it.isDigit() } } .map { it.split(' ') .filter { it.isNotEmpty() && it.all(Character::isDigit) } .map(String::toLong) } .filter { it.isNotEmpty() } } }
[ { "class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/main/kotlin2023/Day005$part2$seeds$1.class", "javap": "Compiled from \"Day005.kt\"\nfinal class main.kotlin2023.Day005$part2$seeds$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequen...
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin2023/Day004.kt
package main.kotlin2023 import kotlin.math.pow class Day004 { fun part1(lines: List<String>): Int { val objects = lines.map { line -> line.dropWhile { it != ':' } .split('|') .map { subString -> subString.split(' ') .filter { it.isNotEmpty() && it.all(Character::isDigit) } .map(String::toInt) } } val sumOf = objects.map { it[0].intersect(it[1]).size } .filter { !it.equals(0) } .sumOf { 2.0.pow(it - 1) }.toInt() return sumOf } fun part2(lines: List<String>): Int { data class Card(val winningNumbers: List<Int>, val ourNumbers: List<Int>) return lines.map { line -> val (_, winningNumbersText, ourNumbersText) = line.split(":", " | ") val winningNumbers = winningNumbersText.chunked(3).map { it.trim().toInt() } val ourNumbers = ourNumbersText.chunked(3).map { it.trim().toInt() } val count = winningNumbers.count { it in ourNumbers } Card(winningNumbers, ourNumbers)to count }.let { pairs -> val countByCard = MutableList(pairs.size) { 1 } pairs.mapIndexed { index, (_, count) -> (1..count).forEach { countByCard[index + it] += countByCard[index] } } countByCard } .onEach(::println) .sum() } }
[ { "class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/main/kotlin2023/Day004$part2$Card.class", "javap": "Compiled from \"Day004.kt\"\npublic final class main.kotlin2023.Day004$part2$Card {\n private final java.util.List<java.lang.Integer> winningNumbers;\n\n private final java.util.List<java.lang.Inte...
teodor-vasile__aoc-2022-kotlin__2fcfe95/src/main/kotlin2023/Day001.kt
package main.kotlin2023 class Day001 { fun part1(input: String): Int { val data = parseInput(input) return data.map { row -> row.find { it.isDigit() }.toString() + row.findLast { it.isDigit() }.toString() } .sumOf { it.toInt() } } fun part2(input: String): Int { val data = parseInput(input) val mapped = data .map { row -> row.replace("nine", "n9e", false) } .map { row -> row.replace("eight", "e8t", false) } .map { row -> row.replace("seven", "s7n", false) } .map { row -> row.replace("six", "s6x", false) } .map { row -> row.replace("five", "f5e", false) } .map { row -> row.replace("four", "f4r", false) } .map { row -> row.replace("three", "t3e", false) } .map { row -> row.replace("two", "t2o", false) } .map { row -> row.replace("one", "o1e", false) } .map { row -> row.find { it.isDigit() }.toString() + row.findLast { it.isDigit() }.toString() } .sumOf { it.toInt() } return mapped } private fun parseInput(input: String) = input.split("\n") }
[ { "class_path": "teodor-vasile__aoc-2022-kotlin__2fcfe95/main/kotlin2023/Day001.class", "javap": "Compiled from \"Day001.kt\"\npublic final class main.kotlin2023.Day001 {\n public main.kotlin2023.Day001();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object...
yt8492__indikate__4f86715/library/src/main/kotlin/com/yt8492/indikate/RoutingPath.kt
package com.yt8492.indikate class RoutingPath(val parts: List<RoutingPathSegment>) { fun evaluate(path: String): PathEvaluationResult { val pathParts = path.splitToSequence("/") .filter { it.isNotBlank() } .toList() if (pathParts.size != parts.size) { return PathEvaluationResult( false, PathEvaluationResult.QUALITY_FAILED, emptyMap() ) } var quality = PathEvaluationResult.QUALITY_CONSTANT val parameters = mutableMapOf<String, String>() pathParts.zip(parts).forEach { (pathPart, part) -> when (part) { is RoutingPathSegment.Constant -> { if (part.value != pathPart) { return PathEvaluationResult( false, PathEvaluationResult.QUALITY_FAILED, emptyMap() ) } } is RoutingPathSegment.Parameter -> { quality *= PathEvaluationResult.QUALITY_PARAMETER parameters[part.value] = pathPart } is RoutingPathSegment.WildCard -> { quality *= PathEvaluationResult.QUALITY_WILDCARD } } } return PathEvaluationResult( true, quality, parameters ) } companion object { private val ROOT: RoutingPath = RoutingPath(listOf()) fun parse(path: String): RoutingPath { if (path == "/") return ROOT val parts = path.splitToSequence("/") .filter { it.isNotBlank() } .map { when { it == "*" -> RoutingPathSegment.WildCard it.startsWith(":") -> RoutingPathSegment.Parameter(it.drop(1)) else -> RoutingPathSegment.Constant(it) } } .toList() return RoutingPath(parts) } } override fun toString(): String = parts.joinToString("/", "/") { it.value } } sealed class RoutingPathSegment { abstract val value: String data class Constant(override val value: String) : RoutingPathSegment() data class Parameter(override val value: String) : RoutingPathSegment() object WildCard : RoutingPathSegment() { override val value: String = "*" } } data class PathEvaluationResult( val succeeded: Boolean, val quality: Double, val parameters: Map<String, String> ) { companion object { const val QUALITY_CONSTANT = 1.0 const val QUALITY_PARAMETER = 0.8 const val QUALITY_WILDCARD = 0.5 const val QUALITY_FAILED = 0.0 } }
[ { "class_path": "yt8492__indikate__4f86715/com/yt8492/indikate/RoutingPath.class", "javap": "Compiled from \"RoutingPath.kt\"\npublic final class com.yt8492.indikate.RoutingPath {\n public static final com.yt8492.indikate.RoutingPath$Companion Companion;\n\n private final java.util.List<com.yt8492.indikat...
bladefistx2__learn-kotlin__a834944/src/academy/learnprogramming/challenges/KotlinOOBicycles.kt
package academy.learnprogramming.challenges fun main(args: Array<String>) { val mtb = KotlinMountainBike(33, 1000, 25, 7) mtb.printDescription() val bike = KotlinBicycle(1, 1) bike.printDescription() val bike2 = KotlinMountainBike("green",1, 2, 1) bike2.printDescription() println("===") println(KotlinMountainBike.availableColors) println("===") KotlinMountainBike.availableColors.forEach(::println) } open class KotlinBicycle(var cadence: Int, var speed: Int, var gear: Int = 1, val type: String = "") { fun applyBrake(decrement: Int) { speed -= decrement } fun speedUp(increment: Int) { speed += increment } open fun printDescription() = println(""" The $type bike is in gear $gear with a cadence of $cadence travelling at the speed of $speed. """.trimIndent()) } class KotlinMountainBike(var seatHeight: Int, cadence: Int, speed: Int, gear: Int = 1): KotlinBicycle(cadence, speed, gear, "mountain") { constructor(color: String, seatHeight: Int, cadence: Int, speed: Int, gear: Int = 1): this(seatHeight, cadence, speed, gear) { println("mtb color is $color") } override fun printDescription(){ super.printDescription() println("The seat hight is $seatHeight mm.") } companion object { val availableColors: List<String> = listOf("blue", "red", "green", "black") } } class KotlinRoadBike(val tireWidth: Int, cadence: Int, speed: Int, gear: Int): KotlinBicycle(cadence, speed, gear, "road") { override fun printDescription(){ super.printDescription() println("The tire width is $tireWidth mm.") } }
[ { "class_path": "bladefistx2__learn-kotlin__a834944/academy/learnprogramming/challenges/KotlinOOBicyclesKt.class", "javap": "Compiled from \"KotlinOOBicycles.kt\"\npublic final class academy.learnprogramming.challenges.KotlinOOBicyclesKt {\n public static final void main(java.lang.String[]);\n Code:\n ...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day07/Day07.kt
package day07 import java.io.File fun main() { val data = parse("src/main/kotlin/day07/Day07-Sample.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 07 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Long> { var node = "/" val dirs = mutableMapOf(node to 0L) File(path).forEachLine { line -> val tokens = line.split(" ") if (tokens[0] == "$" && tokens[1] == "cd") { val name = tokens[2] node = when (name) { "/" -> "/" ".." -> node.substringBeforeLast('/') else -> "$node/$name" } } else { tokens[0].toLongOrNull()?.let { size -> var current = node while (current.isNotBlank()) { dirs.merge(current, size, Long::plus) current = current.substringBeforeLast('/') } } } } return dirs.map { it.value } } private fun part1(data: List<Long>): Long { return data.filter { it <= 100000L }.sum() } private fun part2(data: List<Long>): Long { val required = 30_000_000 - (70_000_000 - data.first()) return data.sorted().first { it >= required } }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day07/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class day07.Day07Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day07/Day07-Sample.txt\n 2: invo...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day09/Day09.kt
package day09 import java.io.File import kotlin.math.absoluteValue import kotlin.math.sign fun main() { val data = parse("src/main/kotlin/day09/Day09.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 09 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Pair<String, Int>> = File(path).readLines() .map { it.split(" ") } .map { (move, step) -> move to step.toInt() } private data class Knot( var x: Int, var y: Int, ) private fun MutableList<Knot>.move(direction: String) { when (direction) { "U" -> this[0].y += 1 "D" -> this[0].y -= 1 "R" -> this[0].x += 1 "L" -> this[0].x -= 1 } for ((head, tail) in this.zipWithNext()) { val dx = head.x - tail.x val dy = head.y - tail.y if (dx.absoluteValue < 2 && dy.absoluteValue < 2) { return } tail.x += dx.sign tail.y += dy.sign } } private fun solve(data: List<Pair<String, Int>>, count: Int): Int { val rope = generateSequence { Knot(0, 0) } .take(count) .toMutableList() val visited = mutableSetOf(Knot(0, 0)) for ((direction, steps) in data) { repeat(steps) { rope.move(direction) visited += rope.last().copy() } } return visited.size } private fun part1(data: List<Pair<String, Int>>): Int = solve(data, count = 2) private fun part2(data: List<Pair<String, Int>>): Int = solve(data, count = 10)
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day09/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class day09.Day09Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day09/Day09.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day08/Day08.kt
package day08 import java.io.File fun main() { val data = parse("src/main/kotlin/day08/Day08.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 08 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<List<Int>> = File(path).useLines { lines -> lines.map { it.map(Char::digitToInt) }.toList() } private fun part1(data: List<List<Int>>): Int { var counter = 0 for (y in data.indices) { for (x in data[0].indices) { val current = data[y][x] if ((x - 1 downTo 0).all { i -> data[y][i] < current }) { counter += 1 continue } if ((x + 1..data[0].lastIndex).all { i -> data[y][i] < current }) { counter += 1 continue } if ((y - 1 downTo 0).all { i -> data[i][x] < current }) { counter += 1 continue } if ((y + 1..data.lastIndex).all { i -> data[i][x] < current }) { counter += 1 continue } } } return counter } private fun part2(data: List<List<Int>>): Int { val scores = mutableListOf<Int>() for (y in data.indices) { for (x in data[0].indices) { val current = data[y][x] val distances = Array(4) { 0 } for (i in (x - 1) downTo 0) { distances[0] += 1 if (data[y][i] >= current) { break } } for (i in (x + 1)..data[0].lastIndex) { distances[1] += 1 if (data[y][i] >= current) { break } } for (i in (y - 1) downTo 0) { distances[2] += 1 if (data[i][x] >= current) { break } } for (i in (y + 1)..data.lastIndex) { distances[3] += 1 if (data[i][x] >= current) { break } } scores.add(distances.reduce(Int::times)) } } return scores.max() }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day08/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class day08.Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day08/Day08.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day23/Day23.kt
package day23 import java.io.File fun main() { val data = parse("src/main/kotlin/day23/Day23.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 23 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } typealias Point = Pair<Int, Int> @Suppress("SameParameterValue") private fun parse(path: String): Set<Point> { val elves = mutableSetOf<Pair<Int, Int>>() val lines = File(path).readLines() for ((y, row) in lines.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { elves += x to y } } } return elves } private fun Point.neighbors(): List<Point> { val (x, y) = this return listOf( x - 1 to y - 1, x + 0 to y - 1, x + 1 to y - 1, x - 1 to y + 0, x + 1 to y + 0, x - 1 to y + 1, x + 0 to y + 1, x + 1 to y + 1, ) } private val directions = listOf( (+0 to -1) to listOf(-1 to -1, +0 to -1, +1 to -1), // North (+0 to +1) to listOf(-1 to +1, +0 to +1, +1 to +1), // South (-1 to +0) to listOf(-1 to -1, -1 to +0, -1 to +1), // West (+1 to +0) to listOf(+1 to -1, +1 to +0, +1 to +1), // East ) private data class State( val elves: Set<Point>, val firstDirection: Int = 0, ) private fun State.next(): State { val movements = mutableMapOf<Point, List<Point>>() for ((x, y) in elves) { if ((x to y).neighbors().all { it !in elves }) { continue } search@for (i in 0..3) { val (proposal, offsets) = directions[(firstDirection + i) % 4] if (offsets.all { (dx, dy) -> (x + dx) to (y + dy) !in elves }) { val (px, py) = proposal val (nx, ny) = (x + px) to (y + py) movements.merge(nx to ny, listOf(x to y)) { a, b -> a + b } break@search } } } val newElves = elves.toMutableSet() for ((position, candidates) in movements) { if (candidates.size == 1) { newElves -= candidates.first() newElves += position } } val newFirstDirection = (firstDirection + 1) % 4 return State(newElves, newFirstDirection) } private fun part1(data: Set<Point>): Int = generateSequence(State(data), State::next) .drop(10) .first() .let { (elves, _) -> val minX = elves.minOf { (x, _) -> x } val maxX = elves.maxOf { (x, _) -> x } val minY = elves.minOf { (_, y) -> y } val maxY = elves.maxOf { (_, y) -> y } (minY..maxY).sumOf { y -> (minX..maxX).sumOf { x -> (if (x to y !in elves) 1 else 0).toInt() } } } private fun part2(data: Set<Point>): Int = generateSequence(State(data), State::next) .zipWithNext() .withIndex() .dropWhile { (_, states) -> states.let { (s0, s1) -> s0.elves != s1.elves } } .first() .let { (idx, _) -> idx + 1 }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day23/Day23Kt.class", "javap": "Compiled from \"Day23.kt\"\npublic final class day23.Day23Kt {\n private static final java.util.List<kotlin.Pair<kotlin.Pair<java.lang.Integer, java.lang.Integer>, java.util.List<kotlin.Pair<java.lang.Integer, java.lan...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day24/Day24.kt
package day24 import java.io.File fun main() { val data = parse("src/main/kotlin/day24/Day24.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 24 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Point( val x: Int, val y: Int, ) private data class Blizzard( val origin: Point, val offset: Point, ) private data class World( val source: Point, val target: Point, val blizzards: Set<Blizzard>, ) @Suppress("SameParameterValue") private fun parse(path: String): World { val lines = File(path).readLines() val source = Point(lines.first().indexOf('.'), 0) val target = Point(lines.last().indexOf('.'), lines.lastIndex) val blizzards = mutableSetOf<Blizzard>() for ((y, row) in lines.withIndex()) { for ((x, col) in row.withIndex()) { when (col) { '>' -> blizzards += Blizzard(Point(x, y), Point(+1, +0)) '<' -> blizzards += Blizzard(Point(x, y), Point(-1, +0)) '^' -> blizzards += Blizzard(Point(x, y), Point(+0, -1)) 'v' -> blizzards += Blizzard(Point(x, y), Point(+0, +1)) } } } return World(source, target, blizzards) } private val World.minX get() = source.x private val World.maxX get() = target.x private val World.minY get() = source.y + 1 private val World.maxY get() = target.y - 1 private fun World.next(): World { val newBlizzards = mutableSetOf<Blizzard>() for ((origin, offset) in blizzards) { var nx = origin.x + offset.x var ny = origin.y + offset.y if (nx < minX) nx = maxX if (nx > maxX) nx = minX if (ny < minY) ny = maxY if (ny > maxY) ny = minY newBlizzards += Blizzard(Point(nx, ny), offset) } return copy(blizzards = newBlizzards) } private fun Point.neighbors(): List<Point> = listOf( Point(x + 0, y + 1), Point(x + 0, y - 1), Point(x + 1, y + 0), Point(x - 1, y + 0), ) private fun World.withinBounds(point: Point): Boolean = (point.x in minX..maxX) && (point.y in minY..maxY) private fun World.safe(point: Point): Boolean = blizzards.find { it.origin == point } == null private fun solve(world: World, source: Point, target: Point, stepCount: Int = 0): Pair<Int, World> { val worlds = mutableMapOf(stepCount to world) val queue = ArrayDeque<Pair<Int, Point>>().apply { add(stepCount to source) } val visited = mutableSetOf<Pair<Int, Point>>() while (queue.isNotEmpty()) { val attempt = queue.removeFirst() if (attempt in visited) { continue } val (steps, position) = attempt val nextWorld = worlds.computeIfAbsent(steps + 1) { worlds.getValue(steps).next() } val neighbors = position.neighbors() if (target in neighbors) { return steps + 1 to nextWorld } for (neighbor in position.neighbors()) { if (nextWorld.withinBounds(neighbor) && nextWorld.safe(neighbor)) { queue += steps + 1 to neighbor } } visited += attempt if (nextWorld.safe(position)) { queue += steps + 1 to position } } error("Could not find the path.") } private fun part1(data: World): Int = solve(data, data.source, data.target).let { (steps, _) -> steps } private fun part2(w0: World): Int { val (s1, w1) = solve(w0, w0.source, w0.target) val (s2, w2) = solve(w1, w0.target, w0.source, s1) val (s3, _) = solve(w2, w0.source, w0.target, s2) return s3 }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day24/Day24Kt.class", "javap": "Compiled from \"Day24.kt\"\npublic final class day24.Day24Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day24/Day24.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day12/Day12.kt
package day12 import java.io.File fun main() { val data = parse("src/main/kotlin/day12/Day12.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 12 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Heightmap( val nodes: String, val width: Int, val height: Int, ) @Suppress("SameParameterValue") private fun parse(path: String): Heightmap { val data = File(path).readLines() val width = data[0].length val height = data.size return Heightmap(data.joinToString(separator = ""), width, height) } private fun Char.toElevation(): Char = when (this) { 'S' -> 'a' 'E' -> 'z' else -> this } private fun Char.reaches(other: Char): Boolean = (other.toElevation() - this.toElevation()) <= 1 private fun Heightmap.neighborsOf(index: Int): List<Int> { val x = index % width val y = index / width val current = nodes[index] val result = mutableListOf<Int>() if (x > 0 && current.reaches(nodes[index - 1])) { result.add(index - 1) } if (y > 0 && current.reaches(nodes[index - width])) { result.add(index - width) } if (x < width - 1 && current.reaches(nodes[index + 1])) { result.add(index + 1) } if (y < height - 1 && current.reaches(nodes[index + width])) { result.add(index + width) } return result } private fun Heightmap.solve(source: Int): Int? { val queue = ArrayDeque<Int>() val distances = Array(nodes.length) { Int.MAX_VALUE } queue.add(source) distances[source] = 0 while (queue.isNotEmpty()) { val vertex = queue.removeFirst() for (neighbor in neighborsOf(vertex)) { if (nodes[neighbor] == 'E') { return distances[vertex] + 1 } if (distances[neighbor] > distances[vertex] + 1) { distances[neighbor] = distances[vertex] + 1 queue.add(neighbor) } } } return null } private fun part1(graph: Heightmap): Int { val source = graph.nodes.indexOfFirst { it == 'S' } return graph.solve(source) ?: error("Path not found.") } private fun part2(graph: Heightmap): Int { val distances = mutableListOf<Int>() for ((source, c) in graph.nodes.withIndex()) { if (c == 'a' || c == 'S') { distances.add(graph.solve(source) ?: continue) } } return distances.min() }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day12/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class day12.Day12Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day12/Day12.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day15/Day15.kt
package day15 import java.io.File import kotlin.math.abs fun main() { val data = parse("src/main/kotlin/day15/Day15.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 15 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Sensor( val sx: Int, val sy: Int, val bx: Int, val by: Int, ) @Suppress("SameParameterValue") private fun parse(path: String): List<Sensor> { val pattern = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") return File(path).readLines().map { line -> val (sx, sy, bx, by) = pattern.matchEntire(line)!!.groupValues .drop(1) .map { it.toInt() } Sensor(sx, sy, bx, by) } } private data class Range( val from: Int, val to: Int, ) private fun findCoverage(data: List<Sensor>, y: Int): List<Range> { val ranges = mutableListOf<Range>() for ((sx, sy, bx, by) in data) { val distance = abs(sx - bx) + abs(sy - by) val dx = distance - abs(sy - y) if (dx >= 0) { ranges += Range(sx - dx, sx + dx) } } ranges.sortWith(compareBy(Range::from, Range::to)) val mergedRanges = mutableListOf<Range>() var merged = ranges[0] for (i in 1..ranges.lastIndex) { val range = ranges[i] if (merged.to >= range.to) { continue } if (merged.to >= range.from) { merged = Range(merged.from, range.to) continue } mergedRanges += merged merged = range } mergedRanges += merged return mergedRanges } private fun part1(data: List<Sensor>, target: Int = 2_000_000): Int { val covered = findCoverage(data, target) .sumOf { (from, to) -> abs(to) + abs(from) + 1 } val beacons = data.mapTo(HashSet()) { it.by } .count { it == target } return covered - beacons } private fun part2(data: List<Sensor>, size: Int = 4_000_000): Long { for (y in 0..size) { val ranges = findCoverage(data, y) if (ranges.size > 1) { val x = ranges[0].to + 1 return x.toLong() * 4_000_000L + y.toLong() } } error("Beacon not found!") }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day15/Day15Kt.class", "javap": "Compiled from \"Day15.kt\"\npublic final class day15.Day15Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day15/Day15.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day14/Day14.kt
package day14 import java.io.File import kotlin.math.min import kotlin.math.max fun main() { val data = parse("src/main/kotlin/day14/Day14.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 14 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Segment( val points: List<Pair<Int, Int>>, ) private fun String.toSegment(): Segment = split(" -> ") .map { it.split(",").let { (a, b) -> a.toInt() to b.toInt() } } .let { points -> Segment(points) } @Suppress("SameParameterValue") private fun parse(path: String): Set<Pair<Int, Int>> = File(path).readLines().map { it.toSegment() }.toObstacles() private fun List<Segment>.toObstacles(): Set<Pair<Int, Int>> { val obstacles = mutableSetOf<Pair<Int, Int>>() for ((points) in this) { for ((a, b) in points.zipWithNext()) { val (ax, ay) = a val (bx, by) = b if (ax == bx) { for (dy in min(ay, by)..max(ay, by)) { obstacles += ax to dy } } else { for (dx in min(ax, bx)..max(ax, bx)) { obstacles += dx to ay } } } } return obstacles } private fun part1(data: Set<Pair<Int, Int>>): Int { val obstacles = data.toMutableSet() val maxy = obstacles.maxBy { (_, y) -> y }.second var sandCount = 0 outer@while (true) { var sx = 500 var sy = 0 inner@while (sx to sy !in obstacles) { sy += 1 if (sx to sy in obstacles) { if ((sx - 1) to sy !in obstacles) { sx -= 1 } else if ((sx + 1) to sy !in obstacles) { sx += 1 } else { sy -= 1 break@inner } } if (sy >= maxy) { break@outer } } obstacles += sx to sy sandCount += 1 } return sandCount } private fun part2(data: Set<Pair<Int, Int>>): Int { val obstacles = data.toMutableSet() val maxy = obstacles.maxBy { (_, y) -> y }.second var sandCount = 0 outer@while (true) { var sx = 500 var sy = 0 inner@while (sx to sy !in obstacles) { sy += 1 if (sx to sy in obstacles) { if ((sx - 1) to sy !in obstacles) { sx -= 1 } else if ((sx + 1) to sy !in obstacles) { sx += 1 } else { sy -= 1 break@inner } } if (sy == maxy + 2) { sy -= 1 break@inner } } obstacles += sx to sy sandCount += 1 if (sx == 500 && sy == 0) { break@outer } } return sandCount }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day14/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class day14.Day14Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day14/Day14.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day13/Day13.kt
package day13 import java.io.File fun main() { val data = parse("src/main/kotlin/day13/Day13.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 13 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private sealed class Packet : Comparable<Packet> { data class Integer(val value: Int) : Packet() { override fun toString() = value.toString() override operator fun compareTo(other: Packet): Int = when (other) { is Integer -> value.compareTo(other.value) is List -> compareContents(listOf(this), other.values) } } data class List(val values: kotlin.collections.List<Packet>) : Packet() { override fun toString() = values.toString() override operator fun compareTo(other: Packet): Int = when (other) { is Integer -> compareContents(values, listOf(other)) is List -> compareContents(values, other.values) } } companion object { fun of(n: Int) = Integer(n) fun of(vararg elements: Packet) = List(listOf(*elements)) } } private fun compareContents(lhs: List<Packet>, rhs: List<Packet>): Int { for ((a, b) in lhs.zip(rhs)) { val result = a.compareTo(b) if (result != 0) { return result } } return lhs.size.compareTo(rhs.size) } @Suppress("SameParameterValue") private fun parse(path: String): List<Packet> = File(path).readLines() .filterNot { it.isBlank() } .map { it.toPacket() } private fun String.toPacket(): Packet = ParserState(source = this).packet() private data class ParserState( val source: String, var current: Int = 0, ) private fun ParserState.peek(): Char = source[current] private fun ParserState.next(): Char = source[current++] /* * packet ::= list | integer */ private fun ParserState.packet(): Packet { return if (peek() == '[') { list() } else { integer() } } /* * list ::= '[' (packet ',')* packet? ']' */ private fun ParserState.list(): Packet.List { val values = mutableListOf<Packet>() next() // skip '[' while (peek() != ']') { values.add(packet()) if (peek() == ',') { next() } } next() // skip ']' return Packet.List(values) } /* * integer ::= [0-9]+ */ private fun ParserState.integer(): Packet.Integer { var result = 0 while (peek().isDigit()) { result = result * 10 + next().digitToInt() } return Packet.Integer(result) } private fun part1(data: List<Packet>): Int { val indices = mutableListOf<Int>() for ((i, packet) in data.chunked(2).withIndex()) { val (lhs, rhs) = packet if (lhs < rhs) { indices.add(i + 1) } } return indices.sum() } private fun part2(data: List<Packet>): Int { val divider2 = Packet.of(Packet.of(2)) val divider6 = Packet.of(Packet.of(6)) val sorted = (data + listOf(divider2, divider6)).sorted() return (sorted.indexOf(divider2) + 1) * (sorted.indexOf(divider6) + 1) }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day13/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class day13.Day13Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day13/Day13.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day22/Day22.kt
package day22 import java.io.File fun main() { val data = parse("src/main/kotlin/day22/Day22.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 22 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Point( val x: Int, val y: Int, ) private sealed interface Step { data class Move(val count: Int) : Step object TurnRight : Step object TurnLeft : Step } private data class Board( val walls: Set<Point>, val steps: List<Step>, ) private fun String.toSteps(): List<Step> { val steps = mutableListOf<Step>() var count = 0 for (c in this) { if (c.isDigit()) { count = count * 10 + c.digitToInt() } else { steps += Step.Move(count) steps += when (c) { 'R' -> Step.TurnRight 'L' -> Step.TurnLeft else -> error("Unknown turn: $c") } count = 0 } } steps += Step.Move(count) return steps } private fun List<String>.toWalls(): Set<Point> { val walls = mutableSetOf<Point>() for ((y, row) in this.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { walls += Point(x, y) } } } return walls } @Suppress("SameParameterValue") private fun parse(path: String): Board = File(path).readLines().let { lines -> val walls = lines.dropLast(2).toWalls() val steps = lines.last().toSteps() Board(walls, steps) } private sealed interface Facing { fun turnLeft(): Facing fun turnRight(): Facing object E : Facing { override fun turnLeft(): Facing = N override fun turnRight(): Facing = S override fun toString() = "E" } object S : Facing { override fun turnLeft(): Facing = E override fun turnRight(): Facing = W override fun toString() = "S" } object W : Facing { override fun turnLeft(): Facing = S override fun turnRight(): Facing = N override fun toString() = "W" } object N : Facing { override fun turnLeft(): Facing = W override fun turnRight(): Facing = E override fun toString() = "N" } } private data class Transition( val sourceId: String, val targetId: String, val sourceFacing: Facing, val targetFacing: Facing, ) private const val PLANE_SIZE = 50 private data class Plane( val topLeft: Point, val transitionToE: Transition, val transitionToS: Transition, val transitionToW: Transition, val transitionToN: Transition, ) private fun Plane.selectTransition(facing: Facing): Transition = when (facing) { is Facing.E -> transitionToE is Facing.S -> transitionToS is Facing.W -> transitionToW is Facing.N -> transitionToN } private val planes = mapOf( // == Part 1 ============================================================== "A1" to Plane( topLeft = Point(50, 0), transitionToE = Transition(sourceId = "A1", targetId = "A2", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A1", targetId = "A3", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A1", targetId = "A2", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A1", targetId = "A5", Facing.N, Facing.N), ), "A2" to Plane( topLeft = Point(100, 0), transitionToE = Transition(sourceId = "A2", targetId = "A1", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A2", targetId = "A2", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A2", targetId = "A1", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A2", targetId = "A2", Facing.N, Facing.N), ), "A3" to Plane( topLeft = Point(50, 50), transitionToE = Transition(sourceId = "A3", targetId = "A3", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A3", targetId = "A5", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A3", targetId = "A3", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A3", targetId = "A1", Facing.N, Facing.N), ), "A4" to Plane( topLeft = Point(0, 100), transitionToE = Transition(sourceId = "A4", targetId = "A5", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A4", targetId = "A6", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A4", targetId = "A5", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A4", targetId = "A6", Facing.N, Facing.N), ), "A5" to Plane( topLeft = Point(50, 100), transitionToE = Transition(sourceId = "A5", targetId = "A4", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A5", targetId = "A1", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A5", targetId = "A4", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A5", targetId = "A3", Facing.N, Facing.N), ), "A6" to Plane( topLeft = Point(0, 150), transitionToE = Transition(sourceId = "A6", targetId = "A6", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A6", targetId = "A4", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A6", targetId = "A6", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A6", targetId = "A4", Facing.N, Facing.N), ), // == Part 2 ============================================================== "B1" to Plane( topLeft = Point(50, 0), transitionToE = Transition(sourceId = "B1", targetId = "B2", Facing.E, Facing.E), transitionToS = Transition(sourceId = "B1", targetId = "B3", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B1", targetId = "B4", Facing.W, Facing.E), transitionToN = Transition(sourceId = "B1", targetId = "B6", Facing.N, Facing.E), ), "B2" to Plane( topLeft = Point(100, 0), transitionToE = Transition(sourceId = "B2", targetId = "B5", Facing.E, Facing.W), transitionToS = Transition(sourceId = "B2", targetId = "B3", Facing.S, Facing.W), transitionToW = Transition(sourceId = "B2", targetId = "B1", Facing.W, Facing.W), transitionToN = Transition(sourceId = "B2", targetId = "B6", Facing.N, Facing.N), ), "B3" to Plane( topLeft = Point(50, 50), transitionToE = Transition(sourceId = "B3", targetId = "B2", Facing.E, Facing.N), transitionToS = Transition(sourceId = "B3", targetId = "B5", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B3", targetId = "B4", Facing.W, Facing.S), transitionToN = Transition(sourceId = "B3", targetId = "B1", Facing.N, Facing.N), ), "B4" to Plane( topLeft = Point(0, 100), transitionToE = Transition(sourceId = "B4", targetId = "B5", Facing.E, Facing.E), transitionToS = Transition(sourceId = "B4", targetId = "B6", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B4", targetId = "B1", Facing.W, Facing.E), transitionToN = Transition(sourceId = "B4", targetId = "B3", Facing.N, Facing.E), ), "B5" to Plane( topLeft = Point(50, 100), transitionToE = Transition(sourceId = "B5", targetId = "B2", Facing.E, Facing.W), transitionToS = Transition(sourceId = "B5", targetId = "B6", Facing.S, Facing.W), transitionToW = Transition(sourceId = "B5", targetId = "B4", Facing.W, Facing.W), transitionToN = Transition(sourceId = "B5", targetId = "B3", Facing.N, Facing.N), ), "B6" to Plane( topLeft = Point(0, 150), transitionToE = Transition(sourceId = "B6", targetId = "B5", Facing.E, Facing.N), transitionToS = Transition(sourceId = "B6", targetId = "B2", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B6", targetId = "B1", Facing.W, Facing.S), transitionToN = Transition(sourceId = "B6", targetId = "B4", Facing.N, Facing.N), ), ) private val Plane.minX: Int get() = topLeft.x private val Plane.maxX: Int get() = topLeft.x + PLANE_SIZE - 1 private val Plane.minY: Int get() = topLeft.y private val Plane.maxY: Int get() = topLeft.y + PLANE_SIZE - 1 private operator fun Plane.contains(point: Point): Boolean = (point.x in minX..maxX) && (point.y in minY..maxY) private fun Point.toLocal(plane: Plane): Point = Point(x - plane.topLeft.x, y - plane.topLeft.y) private fun Point.toGlobal(plane: Plane): Point = Point(x + plane.topLeft.x, y + plane.topLeft.y) private fun Point.flip(): Point = Point(y, x) private val Transition.source: Plane get() = planes[sourceId] ?: error("Plane '$sourceId' doesn't exist.") private val Transition.target: Plane get() = planes[targetId] ?: error("Plane '$targetId' doesn't exist.") private fun Transition.findPosition(start: Point): Point = when (sourceFacing to targetFacing) { Facing.E to Facing.E -> Point(target.minX, start.toLocal(source).toGlobal(target).y) Facing.W to Facing.W -> Point(target.maxX, start.toLocal(source).toGlobal(target).y) Facing.S to Facing.S -> Point(start.toLocal(source).toGlobal(target).x, target.minY) Facing.N to Facing.N -> Point(start.toLocal(source).toGlobal(target).x, target.maxY) Facing.N to Facing.E -> Point(target.minX, start.toLocal(source).flip().toGlobal(target).y) Facing.S to Facing.W -> Point(target.maxX, start.toLocal(source).flip().toGlobal(target).y) Facing.W to Facing.E -> Point(target.minX, target.maxY - start.toLocal(source).y) Facing.E to Facing.W -> Point(target.maxX, target.maxY - start.toLocal(source).y) Facing.W to Facing.S -> Point(start.toLocal(source).flip().toGlobal(target).x, target.minY) Facing.E to Facing.N -> Point(start.toLocal(source).flip().toGlobal(target).x, target.maxY) else -> error("Transition from $sourceFacing to $targetFacing isn't defined.") } private fun Facing.toOffset(): Point = when (this) { is Facing.E -> Point(+1, +0) is Facing.S -> Point(+0, +1) is Facing.W -> Point(-1, +0) is Facing.N -> Point(+0, -1) } private fun Facing.toValue(): Int = when (this) { is Facing.E -> 0 is Facing.S -> 1 is Facing.W -> 2 is Facing.N -> 3 } private fun solve(data: Board, start: String): Int { val (walls, steps) = data var plane = planes[start] ?: error("Plane '$start' doesn't exist.") var facing: Facing = Facing.E var position = plane.topLeft for (step in steps) { when (step) { is Step.TurnLeft -> facing = facing.turnLeft() is Step.TurnRight -> facing = facing.turnRight() is Step.Move -> { for (i in 1..step.count) { val (dx, dy) = facing.toOffset() var newFacing = facing var newPosition = Point(position.x + dx, position.y + dy) var newPlane = plane if (newPosition !in plane) { val transition = plane.selectTransition(facing) newFacing = transition.targetFacing newPosition = transition.findPosition(position) newPlane = transition.target } if (newPosition in walls) { break } facing = newFacing position = newPosition plane = newPlane } } } } return (1000 * (position.y + 1)) + (4 * (position.x + 1)) + facing.toValue() } private fun part1(data: Board): Int = solve(data, start = "A1") private fun part2(data: Board): Int = solve(data, start = "B1")
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day22/Day22Kt.class", "javap": "Compiled from \"Day22.kt\"\npublic final class day22.Day22Kt {\n private static final int PLANE_SIZE;\n\n private static final java.util.Map<java.lang.String, day22.Plane> planes;\n\n public static final void main();...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day04/Day04.kt
package day04 import java.io.File fun main() { val data = parse("src/main/kotlin/day04/Day04.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 04 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Range( val start: Int, val end: Int ) private fun String.toRange(): Range = this.split("-") .map(String::toInt) .let { (start, end) -> Range(start, end) } @Suppress("SameParameterValue") private fun parse(path: String): List<Pair<Range, Range>> = File(path).useLines { lines -> lines .map { it.split(",").map(String::toRange) } .map { (lhs, rhs) -> lhs to rhs } .toList() } private fun Range.contains(other: Range): Boolean = start <= other.start && other.end <= end private fun Range.overlaps(other: Range): Boolean = contains(other) || (other.start <= start && start <= other.end) || (other.start <= end && end <= other.end) private fun part1(data: List<Pair<Range, Range>>): Int = data.count { (a, b) -> a.contains(b) || b.contains(a) } private fun part2(data: List<Pair<Range, Range>>): Int = data.count { (a, b) -> a.overlaps(b) || b.overlaps(a) }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day04/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day04/Day04.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day02/Day02.kt
package day02 import java.io.File fun main() { val data = parse("src/main/kotlin/day02/Day02.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 02 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Rule( val points: Int, val beats: String, val loses: String, ) private val rules = mapOf( "A" to Rule(points = 1, beats = "C", loses = "B"), // Rock "B" to Rule(points = 2, beats = "A", loses = "C"), // Paper "C" to Rule(points = 3, beats = "B", loses = "A"), // Scissors ) private fun assignPoints(elf: String, you: String): Int = when { rules[you]?.beats == elf -> 6 rules[elf]?.beats == you -> 0 else -> 3 } private fun playRound(elf: String, you: String): Int = rules[you]!!.points + assignPoints(elf, you) @Suppress("SameParameterValue") private fun parse(path: String): List<Pair<String, String>> = File(path).useLines { lines -> lines.map { it.split(" ").let { (a, b) -> a to b } }.toList() } private fun part1(data: List<Pair<String, String>>): Int = data.sumOf { (elf, you) -> playRound(elf, when (you) { "X" -> "A" "Y" -> "B" "Z" -> "C" else -> throw IllegalArgumentException() }) } private fun part2(data: List<Pair<String, String>>): Int = data.sumOf { (elf, you) -> playRound(elf, when (you) { "X" -> rules[elf]!!.beats "Y" -> elf "Z" -> rules[elf]!!.loses else -> throw IllegalArgumentException() }) }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day02/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n private static final java.util.Map<java.lang.String, day02.Rule> rules;\n\n public static final void main();\n Code:\n 0: ldc #8 ...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day05/Day05.kt
package day05 import java.io.File fun main() { val data = parse("src/main/kotlin/day05/Day05.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 05 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Move( val count: Int, val from: Int, val to: Int, ) private data class Instructions( val stacks: List<List<Char>>, val moves: List<Move>, ) @Suppress("SameParameterValue") private fun parse(path: String): Instructions = File(path).readLines().let { lines -> val crates = lines .filter { it.contains('[') } .map { line -> line.chunked(4).map { it[1] } } val stackCount = crates[0].size val stacks = (0 until stackCount).map { i -> crates.asReversed() .map { it[i] } .filter { it.isLetter() } } val moves = lines .filter { it.startsWith("move") } .map { line -> val (count, from, to) = line .split("""\D+""".toRegex()) .drop(1) .map(String::toInt) Move(count, from - 1, to - 1) } Instructions(stacks, moves) } private fun solve(instructions: Instructions, reverse: Boolean): String { val (_stacks, moves) = instructions val stacks = _stacks.map { it.toMutableList() } for ((count, source, target) in moves) { val crates = stacks[source].takeLast(count) stacks[target].addAll(if (reverse) crates.asReversed() else crates) repeat(count) { stacks[source].removeLast() } } return stacks .map(List<Char>::last) .joinToString(separator = "") } private fun part1(instructions: Instructions): String = solve(instructions, reverse = true) private fun part2(instructions: Instructions): String = solve(instructions, reverse = false)
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day05/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class day05.Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day05/Day05.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day18/Day18.kt
package day18 import java.io.File fun main() { val data = parse("src/main/kotlin/day18/Day18.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 18 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Point( val x: Int, val y: Int, val z: Int, ) @Suppress("SameParameterValue") private fun parse(path: String): Set<Point> = File(path).readLines().mapTo(HashSet()) { line -> line.split(",") .map { it.toInt() } .let { (x, y, z) -> Point(x, y, z) } } private fun Point.neighbors(): Set<Point> { return setOf( Point(x + 1, y + 0, z + 0), Point(x - 1, y + 0, z + 0), Point(x + 0, y + 1, z + 0), Point(x + 0, y - 1, z + 0), Point(x + 0, y + 0, z + 1), Point(x + 0, y + 0, z - 1), ) } private fun part1(data: Set<Point>): Int = data.flatMap { it.neighbors() } .count { it !in data } private fun part2(data: Set<Point>): Int { val xRange = (data.minOf { it.x } - 1)..(data.maxOf { it.x } + 1) val yRange = (data.minOf { it.y } - 1)..(data.maxOf { it.y } + 1) val zRange = (data.minOf { it.z } - 1)..(data.maxOf { it.z } + 1) val start = Point( xRange.first, yRange.first, zRange.first, ) val queue = ArrayDeque<Point>().apply { add(start) } val visited = mutableSetOf<Point>() var area = 0 while (queue.isNotEmpty()) { val point = queue.removeFirst() if (point in visited) { continue } visited += point for (neighbor in point.neighbors()) { val (x, y, z) = neighbor if (x in xRange && y in yRange && z in zRange) { if (neighbor in data) { area += 1 } else if (neighbor !in visited) { queue += neighbor } } } } return area }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day18/Day18Kt.class", "javap": "Compiled from \"Day18.kt\"\npublic final class day18.Day18Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day18/Day18.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day20/Day20.kt
package day20 import java.io.File fun main() { val data = parse("src/main/kotlin/day20/Day20.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 20 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Int> = File(path).readLines().map(String::toInt) private fun solve(data: List<Int>, times: Int = 1, key: Long = 1L): Long { val numbers = data.map { it * key } val mixed = (0..data.lastIndex).toMutableList() repeat(times) { for ((i, number) in numbers.withIndex()) { val oldMixedIndex = mixed.indexOf(i) mixed.removeAt(oldMixedIndex) val newMixedIndex = (oldMixedIndex + number).mod(mixed.size) mixed.add(newMixedIndex, i) } } val zeroIndex = mixed.indexOf(data.indexOf(0)) return listOf(1000, 2000, 3000).sumOf { offset -> numbers[mixed[(zeroIndex + offset) % mixed.size]] } } private fun part1(data: List<Int>): Long = solve(data) private fun part2(data: List<Int>): Long = solve(data, times = 10, key = 811589153L)
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day20/Day20Kt.class", "javap": "Compiled from \"Day20.kt\"\npublic final class day20.Day20Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day20/Day20.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day16/Day16.kt
package day16 import java.io.File fun main() { val data = parse("src/main/kotlin/day16/Day16.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 16 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Cave( val rates: Map<String, Int>, val edges: Map<String, List<String>>, val costs: Map<Pair<String, String>, Int>, val useful: Set<String>, ) @Suppress("SameParameterValue") private fun parse(path: String): Cave { val rates = mutableMapOf<String, Int>() val edges = mutableMapOf<String, List<String>>() val useful = mutableSetOf<String>() val pattern = Regex("""Valve (\w\w) has flow rate=(\d+); tunnels? leads? to valves? (.*)""") File(path).forEachLine { line -> val (name, rate, tunnels) = (pattern.matchEntire(line) ?: error("Couldn't parse: $line")).destructured rates[name] = rate.toInt() edges[name] = tunnels.split(", ") if (rate.toInt() != 0) { useful += name } } val costs = floydWarshall(edges) return Cave(rates, edges, costs, useful) } private fun floydWarshall(edges: Map<String, List<String>>): Map<Pair<String, String>, Int> { val nodes = edges.keys val costs = mutableMapOf<Pair<String, String>, Int>() for (source in nodes) { for (target in nodes) { costs[source to target] = nodes.size + 1 } } for ((source, neighbors) in edges) { for (target in neighbors) { costs[source to target] = 1 } } for (source in nodes) { costs[source to source] = 0 } for (via in nodes) { for (source in nodes) { for (target in nodes) { if (costs[source to target]!! > costs[source to via]!! + costs[via to target]!!) { costs[source to target] = costs[source to via]!! + costs[via to target]!! } } } } return costs } private fun Cave.dfs( source: String, minutesLeft: Int, candidates: Set<String> = useful, rate: Int = 0, pressure: Int = 0, elephantAllowed: Boolean = false, ): Int { var maxPressure = pressure + rate * minutesLeft // This solution is really slow and ugly, but I don't care ¯\_(ツ)_/¯ if (elephantAllowed) { maxPressure += dfs(source = "AA", minutesLeft = 26, candidates = candidates, elephantAllowed = false) } for (target in candidates) { val cost = costs.getValue(source to target) + 1 if (minutesLeft - cost <= 0) { continue } val newPressure = dfs( source = target, minutesLeft = minutesLeft - cost, candidates = candidates - target, rate = rate + rates.getValue(target), pressure = pressure + rate * cost, elephantAllowed = elephantAllowed ) if (newPressure > maxPressure) { maxPressure = newPressure } } return maxPressure } private fun part1(cave: Cave): Int = cave.dfs(source = "AA", minutesLeft = 30) private fun part2(cave: Cave): Int = cave.dfs(source = "AA", minutesLeft = 26, elephantAllowed = true)
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day16/Day16Kt.class", "javap": "Compiled from \"Day16.kt\"\npublic final class day16.Day16Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day16/Day16.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day11/Day11.kt
package day11 import java.io.File fun main() { val data = parse("src/main/kotlin/day11/Day11.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 11 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Monkey( val initialItems: List<Long>, val operation: (Long) -> Long, val condition: Long, val consequent: Int, val alternate: Int, ) private fun List<String>.toMonkey(): Monkey { val lines = filter { it.startsWith(" ") } val initialItems = lines[0] .substringAfterLast(": ") .split(", ") .map(String::toLong) val (op, rhs) = lines[1] .split(" ") .takeLast(2) val operator = when (op) { "*" -> { a: Long, b: Long -> a * b } "+" -> { a: Long, b: Long -> a + b } else -> error("Invalid operator: '$op'") } val operation = if (rhs == "old") { n: Long -> operator(n, n) } else { n: Long -> operator(n, rhs.toLong()) } val condition = lines[2] .substringAfterLast(" ") .toLong() val consequent = lines[3] .substringAfterLast(" ") .toInt() val alternate = lines[4] .substringAfterLast(" ") .toInt() return Monkey( initialItems, operation, condition, consequent, alternate ) } @Suppress("SameParameterValue") private fun parse(path: String): List<Monkey> = File(path) .readLines() .chunked(7) .map { it.toMonkey() } private fun List<Monkey>.solve(rounds: Int, transform: (Long) -> Long): Long { val items = map { it.initialItems.toMutableList() } val interactions = Array(size) { 0L } repeat(rounds) { for ((i, monkey) in withIndex()) { for (item in items[i]) { val worry = transform(monkey.operation(item)) val target = if (worry % monkey.condition == 0L) { monkey.consequent } else { monkey.alternate } items[target].add(worry) } interactions[i] += items[i].size.toLong() items[i].clear() } } return interactions .sortedArrayDescending() .take(2) .reduce(Long::times) } private fun part1(monkeys: List<Monkey>): Long { return monkeys.solve(rounds = 20) { it / 3L } } private fun part2(monkeys: List<Monkey>): Long { val test = monkeys .map(Monkey::condition) .reduce(Long::times) return monkeys.solve(rounds = 10_000) { it % test } }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day11/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day11/Day11.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day10/Day10.kt
package day10 import java.io.File fun main() { val data = parse("src/main/kotlin/day10/Day10.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 10 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer:\n$answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<String> = File(path).readLines() private fun List<String>.execute(onCycle: (x: Int, cycle: Int) -> Unit) { var x = 1 var cycle = 0 for (instruction in this) { val tokens = instruction.split(" ") when (tokens[0]) { "noop" -> onCycle(x, ++cycle) "addx" -> { onCycle(x, ++cycle) onCycle(x, ++cycle) x += tokens[1].toInt() } } } } private fun part1(program: List<String>): Int { var result = 0 program.execute { x, cycle -> if ((cycle - 20) % 40 == 0) { result += x * cycle; } } return result } private fun part2(program: List<String>): String { val (w, h) = 40 to 6 val crt = Array(h) { Array(w) { '.' } } program.execute { x, cycle -> val col = (cycle - 1) % w if (x - 1 <= col && col <= x + 1) { val row = (cycle - 1) / w crt[row][col] = '#' } } return crt.asIterable() .joinToString(separator = "\n") { line -> line.joinToString(separator = "") } }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day10/Day10Kt.class", "javap": "Compiled from \"Day10.kt\"\npublic final class day10.Day10Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day10/Day10.txt\n 2: invokestati...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day17/Day17.kt
package day17 import java.io.File import kotlin.math.max fun main() { val data = parse("src/main/kotlin/day17/Day17.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 17 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } @Suppress("SameParameterValue") private fun parse(path: String): List<Int> = File(path).readText().trim() .map { if (it == '>') +1 else -1 } private val shapes = listOf( setOf(0 to 0, 1 to 0, 2 to 0, 3 to 0), setOf(1 to 0, 0 to 1, 1 to 1, 2 to 1, 1 to 2), setOf(0 to 0, 1 to 0, 2 to 0, 2 to 1, 2 to 2), setOf(0 to 0, 0 to 1, 0 to 2, 0 to 3), setOf(0 to 0, 1 to 0, 0 to 1, 1 to 1), ) private data class State( val shifts: List<Int>, val obstacles: MutableSet<Pair<Int, Int>> = mutableSetOf(), var shapeIndex: Int = 0, var shiftIndex: Int = 0, var height: Int = 0, ) private data class Step( val ceiling: List<Int>, val shapeIndex: Int, val shiftIndex: Int, ) private fun State.step() { var shape = shapes[shapeIndex++ % shapes.size] .map { (x, y) -> (2 + x) to (height + 3 + y) } .toSet() while (true) { val shift = shifts[shiftIndex++ % shifts.size] val shiftedShapeX = shape .map { (x, y) -> (x + shift) to y } .toSet() if (shiftedShapeX.all { (x, _) -> x in 0..6 }) { if ((shiftedShapeX intersect obstacles).isEmpty()) { shape = shiftedShapeX } } val shiftedShapeY = shape .map { (x, y) -> x to (y - 1) } .toSet() if (shiftedShapeY.all { (_, y) -> y >= 0 }) { if ((shiftedShapeY intersect obstacles).isEmpty()) { shape = shiftedShapeY continue } } break } obstacles += shape height = max(height, shape.maxOf { (_, y) -> y } + 1) } private fun solve(shifts: List<Int>, count: Long): Long { val state = State(shifts) val history = mutableMapOf<Step, Pair<Int, Int>>() while (true) { state.step() val highest = state.obstacles.maxOf { (_, y) -> y } val ceiling = state.obstacles .groupBy { (x, _) -> x }.entries .sortedBy { (x, _) -> x } .map { (_, points) -> points.maxOf { (_, y) -> y } } .let { ys -> ys.map { y -> highest - y } } val step = Step( ceiling = ceiling, shapeIndex = state.shapeIndex % shapes.size, shiftIndex = state.shiftIndex % shifts.size, ) if (step !in history) { history[step] = state.shapeIndex to state.height continue } val (shapeCount, height) = history.getValue(step) val shapesPerCycle = state.shapeIndex - shapeCount val cycleCount = (count - shapeCount) / shapesPerCycle val cycleHeight = state.height - height val shapesRemain = (count - shapeCount) - (shapesPerCycle * cycleCount) repeat(shapesRemain.toInt()) { state.step() } return state.height + (cycleHeight * (cycleCount - 1)) } } private fun part1(shifts: List<Int>): Long = solve(shifts, count = 2022L) private fun part2(shifts: List<Int>): Long = solve(shifts, count = 1_000_000_000_000L)
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day17/Day17Kt.class", "javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n private static final java.util.List<java.util.Set<kotlin.Pair<java.lang.Integer, java.lang.Integer>>> shapes;\n\n public static final void main();\n ...
daniilsjb__advent-of-code-2022__6f0d373/src/main/kotlin/day21/Day21.kt
package day21 import java.io.File fun main() { val data = parse("src/main/kotlin/day21/Day21.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 21 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private sealed interface Monkey { data class Yelling( val number: Long, ) : Monkey data class Operation( val lhs: String, val rhs: String, val op: String, ) : Monkey } @Suppress("SameParameterValue") private fun parse(path: String): Map<String, Monkey> { val data = mutableMapOf<String, Monkey>() File(path).forEachLine { line -> val (name, job) = line.split(": ") val monkey = job.toLongOrNull()?.let { Monkey.Yelling(it) } ?: run { val (lhs, op, rhs) = job.split(" ") Monkey.Operation(lhs, rhs, op) } data[name] = monkey } return data } private fun Monkey.evaluate(ctx: Map<String, Monkey>): Long = when (this) { is Monkey.Yelling -> number is Monkey.Operation -> { val lhsNumber = ctx.getValue(lhs).evaluate(ctx) val rhsNumber = ctx.getValue(rhs).evaluate(ctx) when (op) { "+" -> lhsNumber + rhsNumber "-" -> lhsNumber - rhsNumber "*" -> lhsNumber * rhsNumber "/" -> lhsNumber / rhsNumber else -> error("Unknown operation: $op") } } } private fun Monkey.evaluateOrNull(ctx: Map<String, Monkey>): Long? { return when (this) { is Monkey.Yelling -> number is Monkey.Operation -> { if (lhs == "humn" || rhs == "humn") { return null } val lhsNumber = ctx.getValue(lhs).evaluateOrNull(ctx) ?: return null val rhsNumber = ctx.getValue(rhs).evaluateOrNull(ctx) ?: return null when (op) { "+" -> lhsNumber + rhsNumber "-" -> lhsNumber - rhsNumber "*" -> lhsNumber * rhsNumber "/" -> lhsNumber / rhsNumber else -> error("Unknown operation: $op") } } } } private fun Monkey.coerce(ctx: Map<String, Monkey>, expected: Long): Long { return when (this) { is Monkey.Yelling -> expected is Monkey.Operation -> { ctx.getValue(rhs).evaluateOrNull(ctx)?.let { value -> val next = ctx.getValue(lhs) return when (op) { "+" -> next.coerce(ctx, expected - value) "-" -> next.coerce(ctx, expected + value) "*" -> next.coerce(ctx, expected / value) "/" -> next.coerce(ctx, expected * value) else -> error("Unknown operation: $op") } } ctx.getValue(lhs).evaluateOrNull(ctx)?.let { value -> val next = ctx.getValue(rhs) return when (op) { "+" -> next.coerce(ctx, expected - value) "-" -> next.coerce(ctx, value - expected) "*" -> next.coerce(ctx, expected / value) "/" -> next.coerce(ctx, value / expected) else -> error("Unknown operation: $op") } } error("Cannot evaluate either branch.") } } } private fun part1(data: Map<String, Monkey>): Long = data.getValue("root").evaluate(data) private fun part2(data: Map<String, Monkey>): Long { val (lhs, rhs, _) = data["root"] as Monkey.Operation data.getValue(lhs).evaluateOrNull(data)?.let { expected -> return data.getValue(rhs).coerce(data, expected) } data.getValue(rhs).evaluateOrNull(data)?.let { expected -> return data.getValue(lhs).coerce(data, expected) } error("Cannot evaluate either branch.") }
[ { "class_path": "daniilsjb__advent-of-code-2022__6f0d373/day21/Day21Kt.class", "javap": "Compiled from \"Day21.kt\"\npublic final class day21.Day21Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/kotlin/day21/Day21.txt\n 2: invokestati...
rupeshsasne__algorithms-sedgewick-wayne__e5a9b1f/src/main/kotlin/coursera/algorithms1/week1/assignments/interview/UnionFindWithSpecificCanonicalElement.kt
package coursera.algorithms1.week1.assignments.interview class UnionFindWithSpecificCanonicalElement(n: Int) { private val ids = IntArray(n) { it } private val largestValueAt = IntArray(n) { it } private val size = IntArray(n) { 1 } private fun root(p: Int): Int { var trav = p while (ids[trav] != trav) { ids[trav] = ids[ids[trav]] trav = ids[trav] } return trav } fun find(i: Int): Int = largestValueAt[root(i)] fun connected(p: Int, q: Int): Boolean = root(p) == root(q) fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) if (pRoot == qRoot) return val newRoot: Int val oldRoot: Int if (size[pRoot] > size[qRoot]) { ids[qRoot] = pRoot size[pRoot] += size[qRoot] newRoot = pRoot oldRoot = qRoot } else { ids[pRoot] = qRoot size[qRoot] += size[pRoot] newRoot = qRoot oldRoot = pRoot } if (largestValueAt[newRoot] < largestValueAt[oldRoot]) largestValueAt[newRoot] = largestValueAt[oldRoot] } }
[ { "class_path": "rupeshsasne__algorithms-sedgewick-wayne__e5a9b1f/coursera/algorithms1/week1/assignments/interview/UnionFindWithSpecificCanonicalElement.class", "javap": "Compiled from \"UnionFindWithSpecificCanonicalElement.kt\"\npublic final class coursera.algorithms1.week1.assignments.interview.UnionFind...
rupeshsasne__algorithms-sedgewick-wayne__e5a9b1f/src/main/kotlin/coursera/algorithms1/week3/classroom/MergeSort.kt
package coursera.algorithms1.week3.classroom inline fun <reified T> mergeWithSmallerAux(arr: Array<T>, lo: Int, mid: Int, hi: Int, comparator: Comparator<T>) { val aux = Array(((hi - lo) / 2)) { arr[lo + it] } var i = lo var j = mid + 1 var k = lo while (i <= mid && j <= hi) { if (comparator.compare(aux[i], arr[j]) > 0) arr[k++] = arr[j++] else arr[k++] = aux[i++] } while (i <= mid) arr[k++] = aux[i++] while (j <= hi) arr[k++] = arr[j++] } fun <T> merge(arr: Array<T>, aux: Array<T>, lo: Int, mid: Int, hi: Int, comparator: Comparator<T>) { for (i in lo..hi) { aux[i] = arr[i] } var i = lo var j = mid + 1 for (k in lo..hi) { when { i > mid -> arr[k] = aux[j++] j > hi -> arr[k] = aux[i++] // keeps the sort stable. comparator.compare(aux[j], aux[i]) < 0 -> arr[k] = aux[j++] else -> arr[k] = aux[i++] } } } fun <T> mergeSort(arr: Array<T>, aux: Array<T>, lo: Int, hi: Int, comparator: Comparator<T>) { if (hi <= lo) return val mid = lo + (hi - lo) / 2 mergeSort(arr, aux, lo, mid, comparator) mergeSort(arr, aux, mid + 1, hi, comparator) merge(arr, aux, lo, mid, hi, comparator) } inline fun <reified T> mergeSort(arr: Array<T>, comparator: Comparator<T>) { val aux = Array(arr.size) { arr[it] } mergeSort(arr, aux, 0, arr.lastIndex, comparator) } inline fun <reified T> mergeSortIterative(arr: Array<T>, comparator: Comparator<T>) { val aux = Array(arr.size) { arr[it] } var sz = 1 while (sz < arr.size) { var lo = 0 while (lo < arr.size - sz) { merge(arr, aux, lo, lo + sz - 1, (lo + sz + sz - 1).coerceAtMost(arr.lastIndex), comparator) lo += sz + sz } sz += sz } } fun main() { val arr = arrayOf(4, 5, 1, 2, 8, 9, 0, 10) mergeSortIterative(arr) { a, b -> a - b } println(arr.joinToString()) }
[ { "class_path": "rupeshsasne__algorithms-sedgewick-wayne__e5a9b1f/coursera/algorithms1/week3/classroom/MergeSortKt.class", "javap": "Compiled from \"MergeSort.kt\"\npublic final class coursera.algorithms1.week3.classroom.MergeSortKt {\n public static final <T> void mergeWithSmallerAux(T[], int, int, int, j...
t-34400__PoseTrackerVRC__89daad8/app/src/main/java/com/example/posetrackervrc/data/Vector3D.kt
package com.example.posetrackervrc.data import kotlin.math.sqrt data class Vector3D(val x: Float, val y: Float, val z: Float) { companion object { val zero = Vector3D(0.0f, 0.0f, 0.0f) val right = Vector3D(1.0f, 0.0f, 0.0f) val up = Vector3D(0.0f, 1.0f, 0.0f) val forward = Vector3D(0.0f, 0.0f, 1.0f) fun getRotationAxis(from: Vector3D, to: Vector3D): Vector3D { val crossProduct = from.cross(to) return crossProduct.normalized } } val sqrMagnitude: Float get() = x * x + y * y + z * z val magnitude: Float get() = sqrt(sqrMagnitude) val normalized: Vector3D get() { val magnitude = magnitude return if (magnitude != 0.0f) { Vector3D(x / magnitude, y / magnitude, z / magnitude) } else { zero } } operator fun plus(vector: Vector3D): Vector3D { return Vector3D(x + vector.x, y + vector.y, z + vector.z) } operator fun minus(vector: Vector3D): Vector3D { return Vector3D(x - vector.x, y - vector.y, z - vector.z) } operator fun times(multiplier: Float): Vector3D { return Vector3D(x * multiplier, y * multiplier, z * multiplier) } operator fun times(multiplier: Int): Vector3D { return Vector3D(x * multiplier, y * multiplier, z * multiplier) } operator fun div(divisor: Float): Vector3D { return Vector3D(x / divisor, y / divisor, z / divisor) } operator fun div(divisor: Int): Vector3D { return Vector3D(x / divisor, y / divisor, z / divisor) } operator fun unaryMinus(): Vector3D { return Vector3D(-x, -y, -z) } fun dot(vector: Vector3D): Float { return x * vector.x + y * vector.y + z * vector.z } fun cross(vector: Vector3D): Vector3D { return Vector3D( x = y * vector.z - z * vector.y, y = z * vector.x - x * vector.z, z = x * vector.y - y * vector.x ) } fun project(vector: Vector3D): Vector3D { val normalized = normalized return vector - normalized.dot(vector) * normalized } } operator fun Float.times(vector: Vector3D): Vector3D { return vector * this }
[ { "class_path": "t-34400__PoseTrackerVRC__89daad8/com/example/posetrackervrc/data/Vector3D.class", "javap": "Compiled from \"Vector3D.kt\"\npublic final class com.example.posetrackervrc.data.Vector3D {\n public static final com.example.posetrackervrc.data.Vector3D$Companion Companion;\n\n private final fl...
alexeymatveevp__adventofcode__d140ee8/src/main/java/com/luckystar/advent2020/Advent4.kt
package com.luckystar.advent2020 fun main() { val file = object {}.javaClass.getResource("/2020/input_4.txt").readText() val passports = file.split("\r\n\r\n") val data = passports.map { p -> val split = p .split("\r\n") .reduce { acc, s -> "$acc $s" } .split(" ") val parts = split .map { part -> val pair = part.split(":") Pair(pair[0], pair[1]) } .associateBy({ pair -> pair.first }, { pair -> pair.second }) Passport(parts["byr"]?.toInt(), parts["iyr"]?.toInt(), parts["eyr"]?.toInt(), parts["hgt"], parts["hcl"], parts["ecl"], parts["pid"], parts["cid"]) } // part 1 println(data.filter { passport -> passport.byr != null && passport.iyr != null && passport.eyr != null && passport.hgt != null && passport.hcl != null && passport.ecl != null && passport.pid != null }.count()) // part 2 val hgtRegex = """(\d+)(cm|in)""".toRegex() val hclRegex = """#[0-9a-f]{6}""".toRegex() val eclRegex = """^(amb|blu|brn|gry|grn|hzl|oth)$""".toRegex() val pidRegex = """^(\d){9}$""".toRegex() fun validate(passport: Passport): Boolean { if (passport.byr != null && passport.iyr != null && passport.eyr != null && passport.hgt != null && passport.hcl != null && passport.ecl != null && passport.pid != null) { if (passport.byr !in 1920..2002) { return false } if (passport.iyr !in 2010..2020) { return false } if (passport.eyr !in 2020..2030) { return false } val hgtMatch = hgtRegex.find(passport.hgt) ?: return false val ( value, type ) = hgtMatch.destructured val hgtValue = value.toInt() if (type == "cm" && (hgtValue !in 150..193) || type == "in" && (hgtValue !in 59..76)) { return false } if (hclRegex.find(passport.hcl) == null) { return false } if (eclRegex.find(passport.ecl) == null) { return false } if (pidRegex.find(passport.pid) == null) { return false } return true } else { return false } } println(data.filter(::validate).count()) } data class Passport( val byr: Int?, val iyr: Int?, val eyr: Int?, val hgt: String?, val hcl: String?, val ecl: String?, val pid: String?, val cid: String? )
[ { "class_path": "alexeymatveevp__adventofcode__d140ee8/com/luckystar/advent2020/Advent4Kt.class", "javap": "Compiled from \"Advent4.kt\"\npublic final class com.luckystar.advent2020.Advent4Kt {\n public static final void main();\n Code:\n 0: new #8 // class com/luckystar...
alexeymatveevp__adventofcode__d140ee8/src/main/java/com/luckystar/advent2020/Advent7.kt
package com.luckystar.advent2020 fun main() { val file = object {}.javaClass.getResource("/2020/input_7.txt").readText() var rules = file.split("\r\n") rules = rules.filter { rule -> !rule.contains("no other bags") } val regex = """^(\w+ \w+) bags contain (.*)\.$""".toRegex() val rightRegex = """^(\d) (\w+ \w+) bags?$""".toRegex() val flatRules = rules.map { rule -> val (left, right) = regex.find(rule)!!.destructured right.split(", ").map { g -> val (num, bag) = rightRegex.find(g)!!.destructured Triple(left, num.toInt(), bag) } }.flatten() // part 1 val mapRight = flatRules.groupBy { r -> r.third } var deps = mapRight.getValue("shiny gold"); val uniqueBags = mutableSetOf<String>() while (deps.isNotEmpty()) { val lefts = deps.map { d -> d.first } uniqueBags.addAll(lefts) deps = lefts.map { l -> mapRight.get(l) }.filterNotNull().flatten() } println(uniqueBags.size) // part 2 val mapLeft = flatRules.groupBy { r -> r.first } var deps2 = mapLeft.getValue("shiny gold").map { t -> Triple(t.first, t.second, t.third) }; var numberOfBags = 0 while (deps2.isNotEmpty()) { numberOfBags += deps2 .map { q -> val first = mapLeft.get(q.third) Pair(first, q.second) } .filter { p -> p.first == null } .map { p -> p.second } .sum() deps2 = deps2 .map { q -> Pair(mapLeft.get(q.third), q.second) } .filter { p -> p.first != null } .flatMap { p -> numberOfBags += p.second p.first!!.map { t -> Triple(t.first, t.second * p.second, t.third) } } } println(numberOfBags) } data class Quadruple<T1, T2, T3, T4>(val first: T1, val second: T2, val third: T3, val fourth: T4)
[ { "class_path": "alexeymatveevp__adventofcode__d140ee8/com/luckystar/advent2020/Advent7Kt$main$file$1.class", "javap": "Compiled from \"Advent7.kt\"\npublic final class com.luckystar.advent2020.Advent7Kt$main$file$1 {\n com.luckystar.advent2020.Advent7Kt$main$file$1();\n Code:\n 0: aload_0\n ...
pjozsef__WeightedRandom__7337618/src/main/kotlin/com/github/pjozsef/WeightedRandom.kt
package com.github.pjozsef import java.util.Random class WeightedCoin(val trueProbability: Double, val random: Random = Random()) { init { require(trueProbability in 0.0..1.0) { "trueProbability must be between 0.0 and 1.0, but was: $trueProbability" } } fun flip(): Boolean { return random.nextDouble() <= trueProbability } } class WeightedDie<T>(probabilities: Map<T, Number>, val random: Random = Random()) { constructor(values: List<T>, probabilities: List<Number>, random: Random = Random()) : this(values.zip(probabilities), random) constructor(probabilities: List<Pair<T, Number>>, random: Random = Random()) : this(probabilities.toMap(), random) private val n = probabilities.size private val alias = IntArray(n) private val prob = DoubleArray(n) private val values: List<T> init { val sumOfProbabilities = probabilities.values.map { it.toDouble() }.sum() val probList = probabilities.mapValues { it.value.toDouble() / sumOfProbabilities }.toList() require(probList.map { it.second }.none { it < 0.0 }) { "Probabilities must not be negative" } values = probList.unzip().first val small = mutableListOf<Int>() val large = mutableListOf<Int>() val scaledProbs = probList.zip(0 until n) { (_, percent), index -> index to percent }.map { it.first to it.second * n }.onEach { (i, value) -> if (value < 1.0) small.add(i) else large.add(i) }.map { it.second }.toTypedArray() while (small.isNotEmpty() && large.isNotEmpty()) { val l = small.removeAt(0) val g = large.removeAt(0) prob[l] = scaledProbs[l] alias[l] = g val pgtemp = scaledProbs[g] + scaledProbs[l] - 1 scaledProbs[g] = pgtemp if (pgtemp < 1) small.add(g) else large.add(g) } while (large.isNotEmpty()) { val g = large.removeAt(0) prob[g] = 1.0 } while (small.isNotEmpty()) { val l = small.removeAt(0) prob[l] = 1.0 } } fun roll(): T = random.nextInt(n).let { i -> if (flipCoin(prob[i], random)) values[i] else values[alias[i]] } } fun flipCoin(trueProbability: Double, random: Random = Random()): Boolean { return WeightedCoin(trueProbability, random).flip() } fun intWeightedDice(probabilities: List<Double>, random: Random = Random()) = WeightedDie(probabilities.indices.toList().zip(probabilities).toMap(), random)
[ { "class_path": "pjozsef__WeightedRandom__7337618/com/github/pjozsef/WeightedRandomKt.class", "javap": "Compiled from \"WeightedRandom.kt\"\npublic final class com.github.pjozsef.WeightedRandomKt {\n public static final boolean flipCoin(double, java.util.Random);\n Code:\n 0: aload_2\n 1: ld...
chjaeggi__aoc2020__3ab7867/src/main/kotlin/chjaeggi/Day9.kt
package chjaeggi class Day9(private val input: List<Long>, private val preAmble: Int) { fun solvePart1(): Long { input.forEachIndexed { index, _ -> if (index < (preAmble)) { return@forEachIndexed } else if (index + 1 >= input.size) { return@forEachIndexed } else { val expected = input[index + 1] val subList = input.subList(index - (preAmble - 1), index + 1) if (!subList.hasSumInTwo(expected)) { return expected } } } return -1 } fun solvePart2(): Long { return input.hasSumInRange(solvePart1()) } } fun List<Long>.hasSumInTwo(expectedSum: Long): Boolean { for (first in this.indices) { for (second in this.indices) { if (second == first) { continue } if ((this[first] + this[second]) == expectedSum) { return true } } } return false } fun List<Long>.hasSumInRange(expectedSum: Long): Long { var first = 0 var second = 0 var result = 0L fun reset() { first++ second = first result = 0L } while (first < this.size) { if (second >= this.size) { reset() continue } result += this[second] if (result == expectedSum) { return (this.subList(first, second).minOrNull() ?: -1) + (this.subList(first, second).maxOrNull() ?: -1) } if (result > expectedSum) { reset() continue } second++ } return -1 }
[ { "class_path": "chjaeggi__aoc2020__3ab7867/chjaeggi/Day9Kt.class", "javap": "Compiled from \"Day9.kt\"\npublic final class chjaeggi.Day9Kt {\n public static final boolean hasSumInTwo(java.util.List<java.lang.Long>, long);\n Code:\n 0: aload_0\n 1: ldc #10 // String...
chjaeggi__aoc2020__3ab7867/src/main/kotlin/chjaeggi/Day7.kt
package chjaeggi class Day7(private val input: List<String>) { private val parentsPerBag: MutableMap<String, List<String>> = mutableMapOf() private val childrenPerBag: MutableMap<String, MutableMap<String, Int>> = mutableMapOf() init { input.forEach { val splitted = it.split("contain") val key = splitted[0].replace(" bags", "").dropLast(1) Regex("[a-z]+ [a-z]+,|[a-z]+ [a-z]+.").findAll(splitted[1]) .forEach { val value = it.value.dropLast(1) if (parentsPerBag.containsKey(value)) { parentsPerBag[value] = parentsPerBag[value]!! + key } else { parentsPerBag[value] = listOf(key) } } Regex("[0-9]+ [a-z]+ [a-z]+,|[0-9]+ [a-z]+ [a-z]+.|no other ").findAll(splitted[1]) .forEach { val valueString = it.value.dropLast(1) if (valueString.contains("no other")) { return@forEach } val amount = valueString.substringBefore(" ").toInt() val value = valueString.dropWhile { !it.isLetter() } if (!childrenPerBag.containsKey(key)) { childrenPerBag[key] = mutableMapOf() } childrenPerBag[key]!![value] = amount } } } fun solvePart1(): Int { return parentsPerBag["shiny gold"]?.flatMap { getParents(it) }?.toSet()?.count() ?: -1 } fun solvePart2(): Int { return getCosts("shiny gold", 1) } private fun getParents(bag: String): List<String> { return when (parentsPerBag.containsKey(bag)) { false -> listOf(bag) true -> listOf(bag) + parentsPerBag[bag]!!.flatMap { getParents(it) } } } private fun getCosts(bag: String, amount: Int): Int { return amount * getSameLevelChildrenCost(bag) + (getNextLevelChildren(bag)?.map { amount * getCosts(it.key, it.value) }?.sum() ?: 0) } private fun getNextLevelChildren(bag: String): Map<String, Int>? { return childrenPerBag[bag] } private fun getSameLevelChildrenCost(bag: String): Int { return childrenPerBag[bag]?.values?.sum() ?: 0 } }
[ { "class_path": "chjaeggi__aoc2020__3ab7867/chjaeggi/Day7.class", "javap": "Compiled from \"Day7.kt\"\npublic final class chjaeggi.Day7 {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.Map<java.lang.String, java.util.List<java.lang.String>> parentsPerBag;\n\n private ...
konfork__konfork__b75e6b9/konfork-predicates/src/commonMain/kotlin/io/github/konfork/predicates/CheckDigits.kt
package io.github.konfork.predicates fun isMod10(evenWeight: Int, oddWeight: Int): (String) -> Boolean { val weightSequence = alternatingSequence(evenWeight, oddWeight) return { isMod10(it, weightSequence, Int::times) } } fun isEan(length: Int): (String) -> Boolean { val mod10Fn = isMod10(1, 3) return { it.length == length && mod10Fn(it) } } fun isLuhn(s: String): Boolean = isAllDigits(s) && validateMod10Checksum(s, alternatingSequence(1, 2)) { l, r -> (l * r).let { (it / 10) + (it % 10) } } private fun isAllDigits(s: String): Boolean = s.all(Char::isDigit) private val MOD11_DIGITS = Regex("[0-9]+[xX]?") fun isMod11(weightSequence: Sequence<Int>): (String) -> Boolean = { it.matches(MOD11_DIGITS) && validateMod11Checksum(it.map(Char::toMod11Int), weightSequence) } fun isMod11(startWeight: Int, endWeight: Int): (String) -> Boolean = isMod11(repeatingCounterSequence(startWeight, endWeight)) private val isMod11Isbn10 = isMod11(9, 1) fun isIsbn10(s: String): Boolean = s.replace(Regex("[ -]"), "") .let { it.length == 10 && isMod11Isbn10(it) } private val isEan13 = isEan(13) fun isIsbn13(s: String): Boolean = isEan13(s.replace(Regex("[ -]"), "")) fun isIsbn(s: String): Boolean = isIsbn10(s) || isIsbn13(s) private fun isMod10(s: String, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Boolean = isAllDigits(s) && validateMod10Checksum(s, weightSequence, map) private fun validateMod10Checksum(s: String, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Boolean = weightedSum(s.map(Char::digitToInt).reversed(), weightSequence, map) .let { it % 10 == 0 } private fun alternatingSequence(even: Int, odd: Int): Sequence<Int> = generateIndexedSequence { it % 2 == 0 } .map { if (it) even else odd } private fun <T : Any> generateIndexedSequence(generator: (Int) -> T): Sequence<T> = generateSequence(0) { index -> index + 1 } .map(generator) private fun repeatingCounterSequence(start: Int, end: Int): Sequence<Int> = if (start <= end) { generateIndexedSequence { index -> start + index % (end - start + 1) } } else { generateIndexedSequence { index -> start - index % (start - end + 1) } } private fun validateMod11Checksum(s: List<Int>, weightSequence: Sequence<Int>): Boolean = weightedSum(s.dropLast(1).reversed(), weightSequence, Int::times) .let { it % 11 == s.last() } private fun weightedSum(list: List<Int>, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Int = list.asSequence() .zip(weightSequence, map) .sum() private fun Char.toMod11Int(): Int = when (this) { 'x' -> 10 'X' -> 10 else -> this.digitToInt() }
[ { "class_path": "konfork__konfork__b75e6b9/io/github/konfork/predicates/CheckDigitsKt.class", "javap": "Compiled from \"CheckDigits.kt\"\npublic final class io.github.konfork.predicates.CheckDigitsKt {\n private static final kotlin.text.Regex MOD11_DIGITS;\n\n private static final kotlin.jvm.functions.Fun...
exponentialGroth__Calculator__49a34a8/app/src/main/java/com/exponential_groth/calculator/result/Util.kt
package com.exponential_groth.calculator.result import kotlin.math.abs import kotlin.math.max import kotlin.math.sign import kotlin.math.sqrt private val Double.mantissa get() = toBits() and 0x000fffffffffffffL/* or 0x0010000000000000L*/ private val Double.exponent get() = (toBits() and 0x7ff0000000000000 ushr 52) - 1023 fun reduceFraction(numerator: Long, denominator: Long): Pair<Long, Long> { val sign = if ((numerator > 0) xor (denominator > 0)) -1 else 1 val gcd = gcd(abs(numerator), abs(denominator)) return Pair( sign * abs(numerator) / gcd, abs(denominator) / gcd ) } private fun gcd(a: Long, b: Long): Long { // binary gcd algorithm is faster than the euclidean one require(a > 0 && b > 0) if (a == 0L) return b if (b == 0L) return a val shift = (a or b).countTrailingZeroBits() var u = a var v = b u = u shr u.countTrailingZeroBits() do { v = v shr v.countTrailingZeroBits() v -= u val m = v shr 63 u += v and m v = (v + m) xor m } while (v != 0L) return u shl shift } fun fractionToDecimal(numerator: Long, denominator: Long): String { val nume = abs(numerator) val deno = abs(denominator) val sign = if ((numerator < 0) xor (denominator < 0)) "-" else "" if (deno == 0L) { return "" } else if (nume == 0L) { return "0" } else if (nume % deno == 0L) { return "$sign${nume / deno}" } val map = HashMap<Long, Int>() val rst = StringBuffer("$sign${nume/deno}.") var end = nume % deno * 10 var i = 0 while (end != 0L) { if (map.containsKey(end)) { rst.insert(rst.indexOf(".") + map[end]!! + 1, "\\overline{") rst.append("}") return rst.toString() } rst.append(end / deno) map[end] = i++ end = end % deno * 10 } return rst.toString() } fun Double.toFraction(): Pair<Long, Long>? { val sign = this.sign.toInt() val exponent = this.exponent var mantissa = this.mantissa shl 12 /* val maxExponent = 31 // it would work as long as exponent < 52 but that can take long if (exponent > maxExponent && this <= Long.MAX_VALUE) return toLong() to 1L else if (exponent > maxExponent) return null else if (exponent == -1023L) // Subnormal numbers are not supported return null*/ if (abs(exponent) >= 32) return null asRepeatingDecimalToFraction()?.let { return it } if (mantissa.countTrailingZeroBits() < 12 + 5) return null // should have at least 5 zeros to make sure that it is not repeating with a bigger repeating length var numerator = 1L var denominator = 1L var leadingZeros = mantissa.countLeadingZeroBits() while (leadingZeros != 64) { numerator = (numerator shl (leadingZeros+1)) + 1 denominator = denominator shl (leadingZeros+1) mantissa = mantissa shl (leadingZeros + 1) leadingZeros = mantissa.countLeadingZeroBits() } if (exponent >= 0) numerator = numerator shl exponent.toInt() else denominator = denominator shl -exponent.toInt() return reduceFraction(sign * numerator, denominator) } private fun Double.asRepeatingDecimalToFraction(): Pair<Long, Long>? { val exp = exponent.toInt() val numOfDigitsToCheck = 52 - max(exp, 0) - 2 // don't check last two digits and the ones that account for the integer part val digitsToCheck = (mantissa and (0L.inv() shl 2)) shl (62 - numOfDigitsToCheck) // remove the bits mentioned above and trim start if ((digitsToCheck ushr (64 - numOfDigitsToCheck)).countTrailingZeroBits() > numOfDigitsToCheck / 2) return null var currentlyCheckedRepetendLength = numOfDigitsToCheck / 2 var minRepeatingPartLength = numOfDigitsToCheck var smallestRepetendLength: Int? = null val alreadyChecked = mutableListOf<Int>() while (currentlyCheckedRepetendLength > 0) { var isRecurringWithCurrentLength = true for (i in (64 - numOfDigitsToCheck + currentlyCheckedRepetendLength) until (64 - (numOfDigitsToCheck - minRepeatingPartLength))) { if ((digitsToCheck and (1L shl (i - currentlyCheckedRepetendLength)) == 0L) != (digitsToCheck and (1L shl i) == 0L)) { isRecurringWithCurrentLength = false break } } if (!isRecurringWithCurrentLength && smallestRepetendLength != null) { if (currentlyCheckedRepetendLength == 1) break alreadyChecked.add(currentlyCheckedRepetendLength) do { currentlyCheckedRepetendLength = smallestRepetendLength / smallestDivisor(smallestRepetendLength, smallestRepetendLength / currentlyCheckedRepetendLength) } while (currentlyCheckedRepetendLength > 1 && alreadyChecked.any { it % currentlyCheckedRepetendLength == 0 }) if (currentlyCheckedRepetendLength == 1) break } else if (!isRecurringWithCurrentLength) { currentlyCheckedRepetendLength-- if (currentlyCheckedRepetendLength != 0) minRepeatingPartLength-- } else { smallestRepetendLength = currentlyCheckedRepetendLength if (currentlyCheckedRepetendLength == 1) break currentlyCheckedRepetendLength /= smallestPrimeFactor(currentlyCheckedRepetendLength) alreadyChecked.clear() } } if (smallestRepetendLength == null) return null val repetend = ((((1L shl smallestRepetendLength) - 1) shl (minRepeatingPartLength - smallestRepetendLength)) and (digitsToCheck ushr (64-numOfDigitsToCheck))) ushr (minRepeatingPartLength - smallestRepetendLength) var shiftRepetitionStart = 0 val allDigits = mantissa for (i in (2 + minRepeatingPartLength) until (52 - max(exp, 0))) { if ((allDigits and (1L shl (i - smallestRepetendLength)) == 0L) != (allDigits and (1L shl i) == 0L)) break shiftRepetitionStart++ } // I.APPP... = (IAP - IA) / ((2^n - 1) * 2^k) with n = repetendLength, k = digits between . and first P val p = repetend.rotateRight(shiftRepetitionStart, smallestRepetendLength) val ia = (mantissa or 0x0010000000000000L) ushr (2 + minRepeatingPartLength + shiftRepetitionStart) val numerator = ((ia shl smallestRepetendLength) or p) - ia // Do I need to check for overflow here and the line below? val denominator = ((1L shl smallestRepetendLength) - 1) shl (50 - minRepeatingPartLength - shiftRepetitionStart - exp) return reduceFraction(sign.toInt() * numerator, denominator) } /**returns the smallest divisor of [n] that is bigger than [k]*/ private fun smallestDivisor(n: Int, k: Int): Int { for (i in k+1 until n) { if (n % i == 0) return i } return n } private fun smallestPrimeFactor(n: Int): Int { // fast enough, because n is never bigger than 50 if (n % 2 == 0) return 2 var i = 3 while (i <= sqrt(n.toDouble())) { if (n % i == 0) return i i += 2 } return n } fun primeFactors(num: Long): Map<Long, Int> { var n = num val factors = mutableMapOf<Long, Int>() var i = 2L while (i * i <= n) { while (n % i == 0L) { val occurrences = factors[i]?:0 factors[i] = occurrences + 1 n /= i } i++ } if (n > 1) { val occurrences = factors[i]?:0 factors[n] = occurrences + 1 } return factors.toMap() } private fun Long.rotateRight(n: Int, size: Int) = (((1L shl n) - 1) shl (size - n)) and (this shl (size - n)) or (this ushr n)
[ { "class_path": "exponentialGroth__Calculator__49a34a8/com/exponential_groth/calculator/result/UtilKt.class", "javap": "Compiled from \"Util.kt\"\npublic final class com.exponential_groth.calculator.result.UtilKt {\n private static final long getMantissa(double);\n Code:\n 0: dload_0\n 1: in...
Neonader__Advent-of-Code-2022__4d0cb6f/src/main/kotlin/day09/DayNine.kt
package day09 import java.io.File data class Knot(var x: Int, var y: Int) val fileList = File("puzzle_input/day09.txt").readLines() fun moveHead(head: Knot, direction: Char) = when (direction) { 'U' -> Knot(head.x, head.y + 1) 'L' -> Knot(head.x - 1, head.y) 'R' -> Knot(head.x + 1, head.y) 'D' -> Knot(head.x, head.y - 1) else -> Knot(0, 0) } fun moveTail(head: Knot, tail: Knot) = when { head.x > tail.x + 1 && head.y > tail.y + 1 -> Knot(head.x - 1, head.y - 1) head.x < tail.x - 1 && head.y > tail.y + 1 -> Knot(head.x + 1, head.y - 1) head.x > tail.x + 1 && head.y < tail.y - 1 -> Knot(head.x - 1, head.y + 1) head.x < tail.x - 1 && head.y < tail.y - 1 -> Knot(head.x + 1, head.y + 1) head.x > tail.x + 1 -> Knot(head.x - 1, head.y) head.x < tail.x - 1 -> Knot(head.x + 1, head.y) head.y > tail.y + 1 -> Knot(head.x, head.y - 1) head.y < tail.y - 1 -> Knot(head.x, head.y + 1) else -> tail } fun a(): Int { val visited = mutableSetOf(Knot(0, 0)) var head = Knot(0, 0) var tail = Knot(0, 0) for (line in fileList) { val direction = line[0] val steps = line.slice(2 until line.length).toInt() repeat(steps) { head = moveHead(head, direction) tail = moveTail(head, tail) visited += tail } } return visited.size } fun b(): Int { val visited = mutableSetOf(Knot(0, 0)) val rope = Array(10) { Knot(0,0) } for (line in fileList) { val direction = line[0] val steps = line.slice(2 until line.length).toInt() repeat(steps) { rope[0] = moveHead(rope[0], direction) for (i in rope.indices.filter { it > 0 }) rope[i] = moveTail(rope[i - 1], rope[i]) visited += rope[9] } } return visited.size }
[ { "class_path": "Neonader__Advent-of-Code-2022__4d0cb6f/day09/DayNineKt.class", "javap": "Compiled from \"DayNine.kt\"\npublic final class day09.DayNineKt {\n private static final java.util.List<java.lang.String> fileList;\n\n public static final java.util.List<java.lang.String> getFileList();\n Code:\...