kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day11/Solution.kt
package day11 import java.io.File import java.lang.Exception data class Monkey( val id: Int, val items: List<Long>, val operation: (Long) -> Long, val nextMonkey: (Long) -> Int, val monkeyActivity: Int = 0 ) { fun doATurn(monkeys: List<Monkey>, reduceLevel: Int = 1, verbose: Boolean = false): List<Monkey> { if (items.isEmpty()) return monkeys val updatedMonkeys = items.fold(monkeys) { acc, item -> if (verbose) println("Monkey $id inspects an item with a worry level of $item.") val newLevel = operation(item) if (verbose) println("\tWorry level is now $newLevel.") val dividedLevel = newLevel/reduceLevel.toLong() if (verbose) println("\tMonkey gets bored with item. Worry level is divided by 3 to $dividedLevel.") val receiverMonkeyId = nextMonkey(dividedLevel) if (verbose) println("\tItem with worry level $dividedLevel is thrown to monkey $receiverMonkeyId.") val receiverMonkey = acc.first { it.id == receiverMonkeyId } acc.filter { it.id != receiverMonkeyId } + receiverMonkey.copy( items = receiverMonkey.items + dividedLevel ) } return updatedMonkeys.filter { it.id != id } + this.copy(items = emptyList(), monkeyActivity = monkeyActivity + items.size) } } fun parseNextMonkey(input: String): (Long) -> Int { val divisor = Regex("Test: divisible by ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifTrue = Regex("If true: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() val ifFalse = Regex("If false: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt() return { it -> if (it%divisor.toLong() == 0.toLong()) ifTrue else ifFalse} } fun parseOperation(rawOperation: String): (Long) -> Long { Regex("new = ([0-9a-z]+) ([*+-]) ([0-9a-z]+)") .find(rawOperation)!! .groupValues .let { groups -> val first = groups[1] val op = groups[2] val second = groups[3] return if(first == "old" && second == "old") { when(op) { "+" -> { it -> it + it } "*" -> { it -> it * it } else -> throw Exception("Operation not supported") } } else { when(op) { "+" -> { it -> it + second.toLong() } "*" -> { it -> it * second.toLong() } else -> throw Exception("Operation not supported") } } } } fun parseInputFile() = File("src/main/kotlin/day11/input.txt") .readText() .split(Regex("\r\n\r\n")) .fold(emptyList<Monkey>()) { acc, rawMonkey -> val monkeyId = Regex("Monkey ([0-9]+)").find(rawMonkey)!!.groupValues[1].toInt() val items = Regex("[0-9]+").findAll( Regex("Starting items: ([0-9]+,? ?)+").find(rawMonkey)!!.value ).toList().map { it.value.toLong() } val operation = parseOperation( Regex("Operation: new = [a-z0-9]+ [*+-] [a-z0-9]+").find(rawMonkey)!!.value ) val nextMonkey = parseNextMonkey(rawMonkey) acc + Monkey( monkeyId, items, operation, nextMonkey ) } fun findMonkeyBusinessAfterNthRound(round: Int, worryLevel: Int): Int { val monkeys = parseInputFile() val ids = (monkeys.indices) val finalMonkeys = (0 until round).fold(monkeys) { m, _ -> ids.fold(m) { acc, id -> val monkey = acc.first { it.id == id } monkey.doATurn(acc, worryLevel) } } val monkeyActivity = finalMonkeys.map { it.monkeyActivity }.sortedDescending() return monkeyActivity[0] * monkeyActivity[1] } fun main() { println("The level of monkey business after 20 rounds is ${findMonkeyBusinessAfterNthRound(20, 3)}") }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day11/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day11.SolutionKt {\n public static final kotlin.jvm.functions.Function1<java.lang.Long, java.lang.Integer> parseNextMonkey(java.lang.String);\n Code:\n 0:...
TestaDiRapa__advent-of-code-2022__b5b7ebf/src/main/kotlin/day10/Solution.kt
package day10 import java.io.File data class RegisterHistory( val history: Map<Int, Int> = mapOf(0 to 1) ) { fun addNoOp(): RegisterHistory { val lastClock = history.keys.last() val lastRegister = history.values.last() return this.copy(history = history + (lastClock+1 to lastRegister)) } fun addAddxOp(amount: Int): RegisterHistory { val lastClock = history.keys.last() val lastRegister = history.values.last() return this.copy(history = history + (lastClock + 2 to lastRegister + amount)) } fun getRegisterValueAtClock(clock: Int) = history.keys.last { it < clock }.let { history[it] } ?: 0 } data class CrtRender( val crt: List<Char> = emptyList() ) { fun renderSprite(spriteCenter: Int): CrtRender = if (crt.size < 240) { val adjustedSprite = spriteCenter + (crt.size/40) * 40 if (crt.size >= adjustedSprite-1 && crt.size <= adjustedSprite+1) this.copy(crt = crt + listOf('#')) else this.copy(crt = crt + listOf('.')) } else this fun printRendered() { crt.chunked(40).onEach { println(String(it.toCharArray())) } } } fun parseInputFile() = File("src/main/kotlin/day10/input.txt") .readLines() .fold(RegisterHistory()) { acc, cmd -> if(cmd == "noop") acc.addNoOp() else { val (_, amount) = cmd.split(" ") acc.addAddxOp(amount.toInt()) } } fun findSignalLevelAtClocks() = parseInputFile() .let { registerHistory -> List(6){ it*40+20 }.fold(0) { sum, it -> sum + registerHistory.getRegisterValueAtClock(it)*it } } fun renderCrt() = parseInputFile() .let { (1 .. 240).fold(CrtRender()) { crt, clock -> crt.renderSprite(it.getRegisterValueAtClock(clock)) }.printRendered() } fun main() { println("The sum of the signal strengths during the 20th, 60th, 100th, 140th, 180th, and 220th cycles is: ${findSignalLevelAtClocks()}") println("The final CRT render is:") renderCrt() }
[ { "class_path": "TestaDiRapa__advent-of-code-2022__b5b7ebf/day10/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day10.SolutionKt {\n public static final day10.RegisterHistory parseInputFile();\n Code:\n 0: new #9 // class java/io/File\n ...
fwcd__advent-of-code-2021__9327e74/day17/src/main/kotlin/dev/fwcd/adventofcode2021/Day17.kt
package dev.fwcd.adventofcode2021 import kotlin.math.sign data class Vec(val x: Int, val y: Int) { operator fun plus(rhs: Vec) = Vec(x + rhs.x, y + rhs.y) } data class Rect(val min: Vec, val max: Vec) { operator fun contains(pos: Vec): Boolean = pos.x >= min.x && pos.x <= max.x && pos.y >= min.y && pos.y <= max.y } data class SimulationResults(val hitTarget: Boolean, val maxY: Int) fun simulate(startVelocity: Vec, target: Rect): SimulationResults { var pos = Vec(0, 0) var velocity = startVelocity var maxY = 0 while (pos.x <= target.max.x && pos.y >= target.min.y) { if (pos in target) { return SimulationResults(hitTarget = true, maxY) } pos += velocity maxY = Math.max(pos.y, maxY) velocity = Vec(velocity.x - velocity.x.sign, velocity.y - 1) } return SimulationResults(hitTarget = false, maxY) } fun main() { val input = object {}.javaClass.getResource("/input.txt").readText() val pattern = """target area: x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""".toRegex() val (x1, x2, y1, y2) = pattern.find(input)!!.groupValues.drop(1).map { it.toInt() } val target = Rect(Vec(x1, y1), Vec(x2, y2)) val radius = Math.max( Math.max(Math.abs(x1), Math.abs(x2)), Math.max(Math.abs(y1), Math.abs(y2)) ) var maxY = 0 var hitCount = 0 for (dy in -radius..radius) { for (dx in -radius..radius) { val results = simulate(Vec(dx, dy), target) if (results.hitTarget) { maxY = Math.max(maxY, results.maxY) hitCount++ } } } println("Part 1: $maxY") println("Part 2: $hitCount") }
[ { "class_path": "fwcd__advent-of-code-2021__9327e74/dev/fwcd/adventofcode2021/Day17Kt$main$input$1.class", "javap": "Compiled from \"Day17.kt\"\npublic final class dev.fwcd.adventofcode2021.Day17Kt$main$input$1 {\n dev.fwcd.adventofcode2021.Day17Kt$main$input$1();\n Code:\n 0: aload_0\n 1: i...
whaley__advent-of-code__16ce3c9/2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day07.kt
package com.morninghacks.aoc2017 import java.lang.invoke.MethodHandles private data class NodeFromLine(val id: String, val weight: Int, val childIds: List<String>) private data class Node(val id: String, val weight: Int, var children: List<Node> = listOf(), val parent: Node? = null) { fun treeWeight() : Int = weight + children.sumBy(Node::treeWeight) override fun toString(): String { return "Node(id='$id', weight=$weight, children=$children)" } } fun solve(source: String): Pair<String,Pair<String,Int>> { //need two maps - id -> Node for all nodes val allNodes: List<NodeFromLine> = source.lines() .filter(String::isNotBlank) .map(::nodeFromLine) val nodesById: Map<String,NodeFromLine> = allNodes.associateBy(NodeFromLine::id) val parentsAndChildren: Map<String,List<NodeFromLine?>> = createParentChildRelationships(nodesById) val allChildren = parentsAndChildren.values.flatten().filterNotNull() val rootId: String = parentsAndChildren.keys.minus(allChildren.map(NodeFromLine::id)).first() //createTree val rootNodeFrom = nodesById.getValue(rootId) val rootNode = createTree(rootNodeFrom, nodesById) val unbalanced = findUnbalanceNode(rootNode) val unbalancedParent = unbalanced.parent val otherWeight = unbalancedParent!!.children.minus(unbalanced).first().treeWeight() val difference = otherWeight - unbalanced.treeWeight() return Pair(rootNode.id,Pair(unbalanced.id, Math.abs(unbalanced.weight + difference))) } private tailrec fun findUnbalanceNode(node: Node): Node { val nodesByWeight = node.children.groupBy(Node::treeWeight) if (nodesByWeight.size == 1) { return node } else { for (childNodes: List<Node> in nodesByWeight.values) { if (childNodes.size == 1) { return findUnbalanceNode(childNodes[0]) } } } throw IllegalStateException() } private fun createTree(rootNfl: NodeFromLine, nodesById: Map<String,NodeFromLine>) : Node { fun createSubTree(nfl: NodeFromLine, parent: Node): Node { val node = Node(nfl.id, nfl.weight, parent = parent) node.children = nfl.childIds.map { childId -> createSubTree(nodesById.getValue(childId), node) } return node } val rootNode = Node(rootNfl.id, rootNfl.weight, parent = null) rootNode.children = rootNfl.childIds.map { childId -> createSubTree(nodesById.getValue(childId),rootNode) } return rootNode } private fun createParentChildRelationships(nodesById: Map<String,NodeFromLine>) : Map<String,List<NodeFromLine?>> { return nodesById.filter { (id,node) -> node.childIds.isNotEmpty() } .mapValues { (id,node) -> node.childIds.map(nodesById::get) } } private fun nodeFromLine(line: String) : NodeFromLine { //Sample Line: ugml (68) -> gyxo, ebii, jptl val id = line.subSequence(0,line.indexOf('(')).trim().toString() val weight = line.subSequence(line.indexOf('(') + 1, line.indexOf(')')).toString().toInt() val childIds : List<String> = if (line.contains('>')) { val childIdSection = line.subSequence(line.indexOf('>') + 1,line.length) childIdSection.split(",").map { s -> s.trim() }.toList() } else { listOf() } return NodeFromLine(id,weight,childIds) } fun main(args: Array<String>) { val input = MethodHandles.lookup().lookupClass().getResourceAsStream("/Day07Input.txt").bufferedReader().readText() println(solve(input)) }
[ { "class_path": "whaley__advent-of-code__16ce3c9/com/morninghacks/aoc2017/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class com.morninghacks.aoc2017.Day07Kt {\n public static final kotlin.Pair<java.lang.String, kotlin.Pair<java.lang.String, java.lang.Integer>> solve(java.lang.String)...
whaley__advent-of-code__16ce3c9/2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day03.kt
package com.morninghacks.aoc2017 import kotlin.math.roundToInt import kotlin.math.sqrt // let x be the target number // let y next highest perfect square derived from multiplying odd numbers after and including x // // let max distance = (square root of y) - 1 // let f(x) = max - ((y - x) % max) <--- this fails for numbers like 10, 27, or 33 // if f(x) >= min then f(x) max - f(x) fun manhattan(x: Int): Int { val y = nextOddPerfectSquareInclusive(x) val max = sqrt(y.toDouble()).roundToInt() - 1 val min = max / 2 val f = if (max == 0) 0 else max - ((y - x) % max) //for 33, f is 2, needs to be 4 return if (f < min) max - f else f } fun nextOddPerfectSquareInclusive(x: Int): Int { for (i in 1..x step 2) { val iSquared = Math.pow(i.toDouble(), 2.toDouble()).roundToInt() val nextSquared = Math.pow((i + 2).toDouble(), 2.toDouble()).roundToInt() if (x == iSquared) return x else if (x > iSquared && x < nextSquared) return nextSquared else continue } throw IllegalStateException() } fun main(args: Array<String>) { println(manhattan(325489)) println(createGridUntil(325489).values.max() ?: 0) } data class Point(val x: Int, val y: Int) fun createGridUntil(target: Int) : Map<Point,Int>{ val initial = Point(0, 0) val knownPointsAndScores = hashMapOf(initial to 1) var direction = Direction.RIGHT var currentPoint = initial var steps = 1 var stepsRemainingBeforeTurn = steps while ((knownPointsAndScores[currentPoint] ?: 0) < target) { if (stepsRemainingBeforeTurn == 0 && (direction == Direction.UP || direction == Direction.DOWN)) { direction = direction.nextDirection() steps++ stepsRemainingBeforeTurn = steps - 1 } else if (stepsRemainingBeforeTurn == 0) { direction = direction.nextDirection() stepsRemainingBeforeTurn = steps - 1 } else { stepsRemainingBeforeTurn-- } currentPoint = direction.nextPoint(currentPoint) val score: Int = knownPointsAndScores.keys.intersect(adjacentPoints(currentPoint)).sumBy { knownPointsAndScores[it] ?: 0 } knownPointsAndScores[currentPoint] = score } return knownPointsAndScores } enum class Direction { UP { override fun nextDirection(): Direction = LEFT override fun nextPoint(point: Point) = Point(point.x, point.y + 1) }, DOWN { override fun nextDirection(): Direction = RIGHT override fun nextPoint(point: Point) = Point(point.x, point.y - 1) }, LEFT { override fun nextDirection(): Direction = DOWN override fun nextPoint(point: Point) = Point(point.x - 1, point.y) }, RIGHT { override fun nextDirection(): Direction = UP override fun nextPoint(point: Point) = Point(point.x + 1, point.y) }; abstract fun nextDirection(): Direction abstract fun nextPoint(point: Point): Point } fun adjacentPoints(point: Point): Set<Point> { val adjacentPoints = hashSetOf<Point>() for (x in -1..1) { for (y in -1..1) { adjacentPoints.add(Point(point.x + x, point.y + y)) } } return adjacentPoints }
[ { "class_path": "whaley__advent-of-code__16ce3c9/com/morninghacks/aoc2017/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class com.morninghacks.aoc2017.Day03Kt {\n public static final int manhattan(int);\n Code:\n 0: iload_0\n 1: invokestatic #9 // Metho...
whaley__advent-of-code__16ce3c9/2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day02.kt
package com.morninghacks.aoc2017 import kotlin.math.abs /* Part One: The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences. For example, given the following spreadsheet: 5 1 9 5 7 5 3 2 4 6 8 The first row's largest and smallest values are 9 and 1, and their difference is 8. The second row's largest and smallest values are 7 and 3, and their difference is 4. The third row's difference is 6. In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. ======================================================================================================================== Part Two: It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. For example, given the following spreadsheet: 5 9 2 8 9 4 7 3 3 8 6 5 In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4. In the second row, the two numbers are 9 and 3; the result is 3. In the third row, the result is 2. In this example, the sum of the results would be 4 + 3 + 2 = 9. */ fun checksum(spreadsheet: String, lineSummer: (List<Int>) -> Int = ::minAndMax): Int { val lines = spreadsheet.split("\n") val rows: List<List<Int>> = lines.map { line -> line.split(Regex("""\s""")).map { num -> Integer.valueOf(num) } } return rows.fold(0, { sum: Int, list -> sum + lineSummer(list)}) } fun minAndMax(list: List<Int>): Int { return abs((list.max() ?: 0) - (list.min() ?: 0)) } fun evenlyDivides(list: List<Int>): Int { val pair : Pair<Int,Int>? = allPairs(list).find { it -> it.first % it.second == 0 || it.second % it.first == 0 } return when { pair == null -> 0 pair.first > pair.second -> pair.first / pair.second else -> pair.second / pair.first } } fun <T> allPairs(list: List<T>): List<Pair<T, T>> { val pairs = arrayListOf<Pair<T, T>>() for ((index, left) in list.withIndex()) { if (index != list.size - 1) { list.subList(index + 1, list.size).mapTo(pairs) { left to it } } } return pairs } fun main(args: Array<String>) { val input = """5806 6444 1281 38 267 1835 223 4912 5995 230 4395 2986 6048 4719 216 1201 74 127 226 84 174 280 94 159 198 305 124 106 205 99 177 294 1332 52 54 655 56 170 843 707 1273 1163 89 23 43 1300 1383 1229 5653 236 1944 3807 5356 246 222 1999 4872 206 5265 5397 5220 5538 286 917 3512 3132 2826 3664 2814 549 3408 3384 142 120 160 114 1395 2074 1816 2357 100 2000 112 103 2122 113 92 522 1650 929 1281 2286 2259 1068 1089 651 646 490 297 60 424 234 48 491 245 523 229 189 174 627 441 598 2321 555 2413 2378 157 27 194 2512 117 140 2287 277 2635 1374 1496 1698 101 1177 104 89 542 2033 1724 1197 474 1041 1803 770 87 1869 1183 553 1393 92 105 1395 1000 85 391 1360 1529 1367 1063 688 642 102 999 638 4627 223 188 5529 2406 4980 2384 2024 4610 279 249 2331 4660 4350 3264 242 769 779 502 75 1105 53 55 931 1056 1195 65 292 1234 1164 678 1032 2554 75 4406 484 2285 226 5666 245 4972 3739 5185 1543 230 236 3621 5387 826 4028 4274 163 5303 4610 145 5779 157 4994 5053 186 5060 3082 2186 4882 588 345 67 286 743 54 802 776 29 44 107 63 303 372 41 810 128 2088 3422 111 3312 740 3024 1946 920 131 112 477 3386 2392 1108 2741""" println(checksum(input, ::minAndMax)) println(checksum(input, ::evenlyDivides)) }
[ { "class_path": "whaley__advent-of-code__16ce3c9/com/morninghacks/aoc2017/Day02Kt$checksum$1.class", "javap": "Compiled from \"Day02.kt\"\nfinal class com.morninghacks.aoc2017.Day02Kt$checksum$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.util.List<? exte...
whaley__advent-of-code__16ce3c9/2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day08.kt
package com.morninghacks.aoc2017 import java.lang.invoke.MethodHandles /* You receive a signal directly from the CPU. Because of your recent assistance with jump instructions, it would like you to compute the result of a series of unusual register instructions. Each instruction consists of several parts: the register to modify, whether to increase or decrease that register's value, the amount by which to increase or decrease it, and a condition. If the condition fails, skip the instruction without modifying the register. The registers all start at 0. The instructions look like this: b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10 These instructions would be processed as follows: Because a starts at 0, it is not greater than 1, and so b is not modified. a is increased by 1 (to 1) because b is less than 5 (it is 0). c is decreased by -10 (to 10) because a is now greater than or equal to 1 (it is 1). c is increased by -20 (to -10) because c is equal to 10. After this process, the largest value in any register is 1. You might also encounter <= (less than or equal to) or != (not equal to). However, the CPU doesn't have the bandwidth to tell you what all the registers are named, and leaves that to you to determine. What is the largest value in any register after completing the instructions in your puzzle input? */ sealed class ComparisonOperator { abstract fun apply(lhs: Int, rhs: Int): Boolean } object LessThan : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs < rhs } object LessThanOrEqualTo : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs <= rhs } object GreaterThan : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs > rhs } object GreaterThanOrEqualTo : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs >= rhs } object EqualTo : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs == rhs } object NotEqualTo : ComparisonOperator() { override fun apply(lhs: Int, rhs: Int) = lhs != rhs } data class Instruction(val registerName: String, val incValue: Int, val condition: Condition) data class Condition(val registerName: String, val comparisonOperator: ComparisonOperator, val value: Int) data class Results(val registers: Map<String, Int>, val highestSeenValue: Int) fun runInstructions(input: String): Results { return runInstructions(parseInput(input)) } fun runInstructions(instructions: List<Instruction>): Results { var highestSeenValue: Int = Int.MIN_VALUE val registers = mutableMapOf<String, Int>() for (instruction in instructions) { val cond = instruction.condition registers.putIfAbsent(instruction.registerName, 0) registers.putIfAbsent(cond.registerName, 0) if (cond.comparisonOperator.apply(registers.getOrDefault(cond.registerName, 0), cond.value)) { registers.merge(instruction.registerName, instruction.incValue, fun(orig, incBy): Int { //This is mildly disgusting, but gets the answer quickly val res = orig + incBy if (res > highestSeenValue) { highestSeenValue = res } return res }) } } return Results(registers, highestSeenValue) } fun parseInput(input: String): List<Instruction> { return input.lines() .filter(String::isNotBlank) .map(::lineToInstruction) } fun lineToInstruction(line: String): Instruction { val parts: List<String> = line.trim().split("""\s""".toRegex()) val registerName: String = parts[0] val incBy: Int = if (parts[1] == "inc") parts[2].toInt() else parts[2].toInt() * -1 val conditionRegisterName: String = parts[4] val conditionValue: Int = parts[6].toInt() val operator: ComparisonOperator = when (parts[5]) { "==" -> EqualTo "!=" -> NotEqualTo ">" -> GreaterThan ">=" -> GreaterThanOrEqualTo "<" -> LessThan "<=" -> LessThanOrEqualTo else -> throw IllegalArgumentException() } return Instruction(registerName, incBy, Condition(conditionRegisterName, operator, conditionValue)) } fun main(args: Array<String>) { val input = MethodHandles.lookup().lookupClass().getResourceAsStream("/Day08Input.txt").bufferedReader().readText() val results = runInstructions(input) println("Part One Answer: ${results.registers.values.max()}") println("Part Two Answer: ${results.highestSeenValue}") }
[ { "class_path": "whaley__advent-of-code__16ce3c9/com/morninghacks/aoc2017/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class com.morninghacks.aoc2017.Day08Kt {\n public static final com.morninghacks.aoc2017.Results runInstructions(java.lang.String);\n Code:\n 0: aload_0\n ...
arnavb__competitive-programming-kotlin__5b805ce/src/codeforces/problem1B/Main.kt
package codeforces.problem1B fun convertToExcelFormat(coord: String, alphabet: CharArray): String { val row = coord.substring(1, coord.indexOf('C')) var column = coord.substring(coord.indexOf('C') + 1).toInt() // Convert column number to letters val resultingColumn = StringBuilder() while (column > 26) { var remainder = column % 26 if (remainder == 0) { // 0 is represented by Z with one less letter remainder = 26 } resultingColumn.append(alphabet[remainder]) column -= remainder column /= 26 } resultingColumn.append(alphabet[column]) return "${resultingColumn.reverse()}$row" } fun convertToNumericalFormat(coord: String, alphabet: CharArray): String { val firstDigitPos = coord.indexOfFirst { it.isDigit() } val row = coord.substring(firstDigitPos) val column = coord.substring(0, firstDigitPos) var convertedColumn = 0 var powerOf26 = 1 for (i in column.length - 1 downTo 0) { convertedColumn += powerOf26 * alphabet.binarySearch(column[i]) powerOf26 *= 26 } return "R${row}C$convertedColumn" } fun main() { val numLines = readLine()!!.toInt() val alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() val outputs = mutableListOf<String>() for (i in 0 until numLines) { val currentLine = readLine()!! val positionOfC = currentLine.indexOf('C') if (positionOfC > 0 && currentLine[positionOfC - 1].isDigit()) { // Input is in Row Column format outputs.add(convertToExcelFormat(currentLine, alphabet)) } else { // Input is in Letter Row format outputs.add(convertToNumericalFormat(currentLine, alphabet)) } } println(outputs.joinToString("\n")) }
[ { "class_path": "arnavb__competitive-programming-kotlin__5b805ce/codeforces/problem1B/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class codeforces.problem1B.MainKt {\n public static final java.lang.String convertToExcelFormat(java.lang.String, char[]);\n Code:\n 0: aload_0\n ...
uberto__fotf__0e02c3a/bowlingkata/src/main/kotlin/com/ubertob/fotf/bowlingkata/BowlingGameFP.kt
package com.ubertob.fotf.bowlingkata enum class Pins(val number: Int) { zero(0), one(1), two(2), three(3), four(4), five(5), six(6), seven(7), eight(8), nine(9), ten(10) } data class BowlingGameFP(val rolls: List<Pins>, val scoreFn: (List<Pins>) -> Int) { val score by lazy { scoreFn(rolls) } fun roll(pins: Pins): BowlingGameFP = copy(rolls = rolls + pins) companion object { fun newBowlingGame() = BowlingGameFP(emptyList(), Companion::calcBowlingScoreRec) fun calcBowlingScore(rolls: List<Pins>): Int { fun getRoll(roll: Int): Int = rolls.getOrElse(roll) { Pins.zero }.number fun isStrike(frameIndex: Int): Boolean = getRoll(frameIndex) == 10 fun sumOfBallsInFrame(frameIndex: Int): Int = getRoll(frameIndex) + getRoll(frameIndex + 1) fun spareBonus(frameIndex: Int): Int = getRoll(frameIndex + 2) fun strikeBonus(frameIndex: Int): Int = getRoll(frameIndex + 1) + getRoll(frameIndex + 2) fun isSpare(frameIndex: Int): Boolean = getRoll(frameIndex) + getRoll(frameIndex + 1) == 10 var score = 0 var frameIndex = 0 for (frame in 0..9) { if (isStrike(frameIndex)) { score += 10 + strikeBonus(frameIndex) frameIndex++ } else if (isSpare(frameIndex)) { score += 10 + spareBonus(frameIndex) frameIndex += 2 } else { score += sumOfBallsInFrame(frameIndex) frameIndex += 2 } } return score } fun calcBowlingScoreRec(rolls: List<Pins>): Int { val lastFrame = 10 val noOfPins = 10 fun List<Int>.isStrike(): Boolean = first() == noOfPins fun List<Int>.isSpare(): Boolean = take(2).sum() == noOfPins fun calcFrameScore(frame: Int, rolls: List<Int>): Int = when { frame == lastFrame || rolls.size < 3 -> rolls.sum() rolls.isStrike() -> rolls.take(3).sum() + calcFrameScore(frame + 1, rolls.drop(1)) rolls.isSpare() -> rolls.take(3).sum() + calcFrameScore(frame + 1, rolls.drop(2)) else -> rolls.take(2).sum() + calcFrameScore(frame + 1, rolls.drop(2)) } return calcFrameScore(1, rolls.map(Pins::number)) } } } fun scoreAndLog( fnLog: (Int) -> Unit, fnScore: (List<Int>) -> Int ): (List<Int>) -> Int = { rolls -> fnScore(rolls).also(fnLog) }
[ { "class_path": "uberto__fotf__0e02c3a/com/ubertob/fotf/bowlingkata/BowlingGameFPKt.class", "javap": "Compiled from \"BowlingGameFP.kt\"\npublic final class com.ubertob.fotf.bowlingkata.BowlingGameFPKt {\n public static final kotlin.jvm.functions.Function1<java.util.List<java.lang.Integer>, java.lang.Integ...
mhlavac__advent-of-code-2022__240dbd3/src/Day2/Day2.kt
package Day2 import java.io.File fun main() { val lines = File("src", "Day2/input.txt").readLines() var totalScore = 0 lines.forEach { val (theirs, mine) = it.split(" ") val score = score(map(theirs), map(mine)) totalScore += score println("$theirs $mine: $score") } println("Total Score: $totalScore") } fun score(theirs: String, mine:String): Int { var score = 0 when (mine) { "Rock" -> score += 1 // Rock is 1 point "Paper" -> score += 2 // Paper is 2 points "Scissors" -> score += 3 // Scissors are 3 points } if (theirs == mine) { return score + 3 // Draw is 3 points } if ( (theirs == "Rock" && mine == "Paper") || // A Rock is wrapped in a Y Paper (theirs == "Paper" && mine == "Scissors") || // B Paper is cut by Z scissors (theirs == "Scissors" && mine == "Rock") // C Scissors is blunted by X Rock ) { return score + 6; // Win is 6 points } return score } fun map(move: String): String { when (move) { "A", "X" -> return "Rock" "B", "Y" -> return "Paper" "C", "Z" -> return "Scissors" } return "" }
[ { "class_path": "mhlavac__advent-of-code-2022__240dbd3/Day2/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class Day2.Day2Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
reactivedevelopment__aoc-2022-8__cf3ac59/src/main/kotlin/com/adventofcode/Forest.kt
package com.adventofcode import com.adventofcode.Forest.addTrees import com.adventofcode.Forest.crosswalks class Crosswalk( private val tree: Int, private val left: List<Int>, private val right: List<Int>, private val top: List<Int>, private val bottom: List<Int> ) { fun scenicScore(): Int { val leftScore = countVisibleTreesOn(left) val rightScore = countVisibleTreesOn(right) val topScore = countVisibleTreesOn(top) val bottomScore = countVisibleTreesOn(bottom) return leftScore * rightScore * topScore * bottomScore } private fun countVisibleTreesOn(side: List<Int>): Int { return when (val visibleTrees = side.takeWhile { it < tree }.size) { side.size -> visibleTrees else -> visibleTrees + 1 } } } object Forest { private val forest = mutableListOf<List<Int>>() private val columns get() = forest.first().size private val rows get() = forest.size private fun tree(row: Int, column: Int): Int { return forest[row][column] } private fun column(n: Int): List<Int> { return (0 until rows).map { tree(it, n) } } private fun row(n: Int): List<Int> { return forest[n] } private fun crosswalk(row: Int, column: Int): Crosswalk { val me = tree(row, column) val leftAndRight = row(row) val left = leftAndRight.slice(0 until column).asReversed() val right = leftAndRight.slice(column + 1 until columns) val topAndBottom = column(column) val top = topAndBottom.slice(0 until row).asReversed() val bottom = topAndBottom.slice(row + 1 until rows) return Crosswalk(me, left, right, top, bottom) } fun addTrees(encodedRow: String) { val row = encodedRow.map { it.toString().toInt() } forest.add(row) } fun crosswalks() = sequence { for (r in 0 until rows) { for (c in 0 until columns) { yield(crosswalk(r, c)) } } } } fun solution(): Int { return crosswalks().maxOf(Crosswalk::scenicScore) } fun main() { ::main.javaClass .getResourceAsStream("/input")!! .bufferedReader() .forEachLine(::addTrees) println(solution()) }
[ { "class_path": "reactivedevelopment__aoc-2022-8__cf3ac59/com/adventofcode/Forest.class", "javap": "Compiled from \"Forest.kt\"\npublic final class com.adventofcode.Forest {\n public static final com.adventofcode.Forest INSTANCE;\n\n private static final java.util.List<java.util.List<java.lang.Integer>> f...
Nublo__KotlinByHaskell__ab51d42/lib/src/main/java/anatoldevelopers/by/functional/Extensions.kt
package anatoldevelopers.by.functional val <T> List<T>.head: T get() = when (this.isEmpty()) { true -> throw NoSuchElementException("List is empty.") false -> this[0] } val <T> List<T>.tail: List<T> get() = drop(1) val List<Int>.sum: Int get() = sum(this) fun sum(xs: List<Int>): Int { tailrec fun sumInner(xs: List<Int>, acum: Int): Int = when (xs.size) { 0 -> acum else -> sumInner(xs.tail, xs.head + acum) } return sumInner(xs, 0) } fun sum2(xs: List<Int>) = reduce(0, xs) { acum, current -> acum + current } fun <T, R> List<T>.map(f: (T) -> R): List<R> = when (this.size) { 0 -> listOf() else -> f(head) + tail.map(f) } fun <T, R> List<T>.map2(f: (T) -> R): List<R> = reduce(listOf(), this) { xs, s -> xs + f(s) } fun <T> List<T>.filter(f: (T) -> Boolean): List<T> = when (this.size) { 0 -> listOf() else -> if (f(head)) head + tail.filter(f) else tail.filter(f) } fun <T> List<T>.filter2(f: (T) -> Boolean): List<T> = reduce(listOf(), this) { ys, s -> if (f(s)) return@reduce ys + s else ys } fun <T, R> reduce(s: T, xs: List<R>, f: (T, R) -> T): T = when (xs.size) { 0 -> s else -> reduce(f(s, xs.head), xs.tail, f) } operator fun <T> List<T>.plus(x: T): List<T> = ArrayList(this).also { it.add(x) } operator fun <T> List<T>.plus(xs: List<T>): List<T> = when (xs.size) { 0 -> ArrayList(this) else -> (this + xs.head) + xs.tail } operator fun <T> T.plus(xs: List<T>): List<T> = listOf(this) + xs fun <T, R> zip(xs: List<T>, ys: List<R>): List<Pair<T, R>> = when (xs.isEmpty() || ys.isEmpty()) { true -> listOf() false -> Pair(xs.head, ys.head) + zip(xs.tail, ys.tail) } fun <T, R, C> zipWith(xs: List<T>, ys: List<R>, f: (T, R) -> C): List<C> = zip(xs, ys).map { f(it.first, it.second) } fun maxSum(xs: List<Int>) = zipWith(xs, xs.tail) { a, b -> a + b }.max() fun <T> reverse(xs: List<T>) = reduce(listOf<T>(), xs) { ys, s -> s + ys } fun sumWithEvenIndexes(xs: List<Int>) = zip(xs, generateSequence(0) { it + 1 }.take(xs.size).toList()) .filter { it.second % 2 == 0 } .map { it.first } .sum fun <T> reduceSame(xs: List<T>) = reduce(listOf<T>(), xs) { list, elem -> list + elem }
[ { "class_path": "Nublo__KotlinByHaskell__ab51d42/anatoldevelopers/by/functional/ExtensionsKt.class", "javap": "Compiled from \"Extensions.kt\"\npublic final class anatoldevelopers.by.functional.ExtensionsKt {\n public static final <T> T getHead(java.util.List<? extends T>);\n Code:\n 0: aload_0\n ...
JetBrains-Research__bumblebee__aff0459/ast-transformations-core/src/test/kotlin/org/jetbrains/research/ml/ast/util/FileTestUtil.kt
package org.jetbrains.research.ml.ast.util import java.io.File enum class Extension(val value: String) { Py(".py"), Xml(".xml") } enum class Type { Input, Output } class TestFileFormat(private val prefix: String, private val extension: Extension, val type: Type) { data class TestFile(val file: File, val type: Type, val number: Number) fun check(file: File): TestFile? { val number = "(?<=${prefix}_)\\d+(?=(_.*)?${extension.value})".toRegex().find(file.name)?.value?.toInt() return number?.let { TestFile(file, type, number) } } fun match(testFile: TestFile): Boolean { return testFile.type == type } } object FileTestUtil { val File.content: String get() = this.readText().removeSuffix("\n") /** * We assume the format of the test files will be: * * inPrefix_i_anySuffix.inExtension * outPrefix_i_anySuffix.outExtension, * * where: * inPrefix and outPrefix are set in [inFormat] and [outFormat] together with extensions, * i is a number; two corresponding input and output files should have the same number, * suffixes can by any symbols not necessary the same for the corresponding files. */ fun getInAndOutFilesMap( folder: String, inFormat: TestFileFormat = TestFileFormat("in", Extension.Py, Type.Input), outFormat: TestFileFormat? = null ): Map<File, File?> { val (files, folders) = File(folder).listFiles().orEmpty().partition { it.isFile } // Process files in the given folder val inAndOutFilesGrouped = files.mapNotNull { inFormat.check(it) ?: outFormat?.check(it) }.groupBy { it.number } val inAndOutFilesMap = inAndOutFilesGrouped.map { (number, fileInfoList) -> val (f1, f2) = if (outFormat == null) { require(fileInfoList.size == 1) { "There are less or more than 1 test files with number $number" } Pair(fileInfoList.first(), null) } else { require(fileInfoList.size == 2) { "There are less or more than 2 test files with number $number" } fileInfoList.sortedBy { it.type }.zipWithNext().first() } require(inFormat.match(f1)) { "The input file does not match the input format" } outFormat?.let { require(f2 != null && outFormat.match(f2)) { "The output file does not match the output format" } } f1.file to f2?.file }.sortedBy { it.first.name }.toMap() outFormat?.let { require(inAndOutFilesMap.values.mapNotNull { it }.size == inAndOutFilesMap.values.size) { "Output tests" } } // Process all other nested files return folders.sortedBy { it.name }.map { getInAndOutFilesMap(it.absolutePath, inFormat, outFormat) } .fold(inAndOutFilesMap, { a, e -> a.plus(e) }) } }
[ { "class_path": "JetBrains-Research__bumblebee__aff0459/org/jetbrains/research/ml/ast/util/FileTestUtil$getInAndOutFilesMap$lambda$9$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class org.jetbrains.research.ml.ast.util.FileTestUtil$getInAndOutFilesMap$lambda$9$$inline...
Juuxel__Advent2019__3e9d218/src/main/kotlin/juuxel/advent/Day2.kt
package juuxel.advent import java.nio.file.Files import java.nio.file.Paths fun main() { val input = Files.readAllLines(Paths.get("day2.txt")).joinToString(separator = "") val mem = input.split(',').map { it.toInt() }.toIntArray() part1(mem.copyOf()) part2(mem) // Part 2 is mem-safe } private fun part1(mem: IntArray) { println( "Part 1: " + run(mem, noun = 12, verb = 2) ) } private fun part2(mem: IntArray) { for (noun in mem.indices) { for (verb in mem.indices) { val result = run(mem.copyOf(), noun, verb) if (result == 19690720) { println("Part 2: ${100 * noun + verb}") break } } } } private fun run(mem: IntArray, noun: Int, verb: Int): Int { val reader = MemReader(mem) mem[1] = noun mem[2] = verb while (true) { reader.nextOpcode().run(mem) ?: return mem[0] } } private class MemReader(private val mem: IntArray) { private var pos: Int = 0 fun nextOpcode(): Intcode { val result = when (val opcode = mem[pos]) { 1 -> Intcode.Add(mem[pos + 1], mem[pos + 2], mem[pos + 3]) 2 -> Intcode.Multiply(mem[pos + 1], mem[pos + 2], mem[pos + 3]) 99 -> Intcode.Halt else -> Intcode.Unknown(opcode) } pos += 4 return result } } private sealed class Intcode { data class Add(val a: Int, val b: Int, val out: Int) : Intcode() data class Multiply(val a: Int, val b: Int, val out: Int) : Intcode() object Halt : Intcode() data class Unknown(val opcode: Int) : Intcode() fun run(mem: IntArray): Unit? = when (this) { is Add -> mem[out] = mem[a] + mem[b] is Multiply -> mem[out] = mem[a] * mem[b] else -> null } }
[ { "class_path": "Juuxel__Advent2019__3e9d218/juuxel/advent/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class juuxel.advent.Day2Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String day2.txt\n 2: iconst_0\n 3: anewarray ...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day10.kt
package days import java.io.File fun String.parse() = when(this) { "noop" -> sequence{ yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x } } else -> this.replace("addx ", "").toInt().let { sequence{ yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x } yield { (cycle, x): Pair<Int, Int> -> cycle + 1 to x + it } } } } fun day10part1() = File("input/10.txt").readLines() .flatMap { it.parse() } .scan(1 to 1) { acc, f -> f(acc) } .filter { (cycle, _) -> cycle in 20..220 step 40 } .sumOf { (cycle, x) -> cycle * x } fun day10part2() = File("input/10.txt").readLines() .flatMap { it.parse() }.asSequence() .scan(0 to 1) { acc, f -> f(acc) } .map { (cycle, x) -> cycle.mod(40) to x } .map { (pointer, x ) -> if (x in (pointer - 1 .. pointer + 1)) '#' else '.' } .chunked(40) .map { it.joinToString(" ") } .joinToString("\n")
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day10Kt$parse$2$1.class", "javap": "Compiled from \"day10.kt\"\nfinal class days.Day10Kt$parse$2$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceScope<? super kotlin.jvm.fun...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day05.kt
package days import java.nio.file.Files import java.nio.file.Paths import java.util.* fun parseCrates(crates: String) = crates.split("\n").dropLast(1) .map { it.windowed(3,4) } .map { it.map { s -> s.trim(' ', '[', ']') } } .foldRight(mapOf<Int, Stack<String>>()) { line, cratesAcc -> line.foldIndexed(cratesAcc) { index, acc, crate -> if (crate.isNotBlank()) acc.toMutableMap().let { map -> map.getOrDefault(index + 1, Stack()) .also { it.push(crate) } .also { map[index + 1] = it } map.toMap() } else acc } } fun parseMoves(moves: String) = moves.split("\n") .map { it.replace("move ", "").replace(" from ", " ").replace(" to ", " ") } .map { it.split(" ").map(String::toInt) } fun Map<Int, Stack<String>>.move(quantity: Int, from: Int, to: Int) = this.toMutableMap().let { stacks -> repeat(quantity) { stacks[to]!!.push(stacks[from]!!.pop()) } stacks.toMap() } fun Map<Int, Stack<String>>.peekString() = this.entries.sortedBy { it.key }.joinToString("") { it.value.peek() } fun day5part1() = Files.readString(Paths.get("input/05.txt")).split("\n\n") .let { parseCrates(it[0]) to parseMoves(it[1]) } .let { (crates, moves) -> moves.fold(crates) { acc, move -> acc.move(move[0], move[1], move[2]) } } .peekString() fun Map<Int, Stack<String>>.move2(quantity: Int, from: Int, to: Int) = this.toMutableMap().let { (1..quantity) .fold(listOf<String>()) { acc, _ -> (acc + it[from]!!.pop()) } .reversed().forEach { crate -> it[to]!!.push(crate) } it.toMap() } fun day5part2() = Files.readString(Paths.get("input/05.txt")).split("\n\n") .let { parseCrates(it[0]) to parseMoves(it[1]) } .let { (crates, moves) -> moves.fold(crates) { acc, move -> acc.move2(move[0], move[1], move[2]) } } .peekString()
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day05Kt$peekString$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class days.Day05Kt$peekString$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public days.Day05Kt$peekString$$inlined$sortedBy$1();\n Code...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day07.kt
package days import java.nio.file.Files import java.nio.file.Paths fun createMapOfSizes(shellOuput: String): Map<List<String>, Int> = shellOuput .replaceFirst("\$ ", "") .split("\n\$ ") .map { when { it.startsWith("cd") -> "cd" to listOf(it.replaceFirst("cd ", "")) else -> "ls" to it.replaceFirst("ls\n", "").split("\n") } } .let { it.scan(listOf<String>()) { acc, (command, dirOrStdout) -> when(command) { "cd" -> when { dirOrStdout.first() == ".." -> acc.dropLast(1) else -> acc + dirOrStdout.first() } else -> acc } }.zip(it) } .filter { (_, command) -> command.first != "cd" } .map { (path, command) -> path to command.second } .reversed() .fold(mutableMapOf()) { map, (path, ls) -> map[path] = ls.sumOf { when { it.startsWith("dir ") -> map[path + it.replace("dir ", "")]!! else -> it.split(" ")[0].toInt() } } map } fun day7part1() = createMapOfSizes(Files.readString(Paths.get("input/07.txt"))) .values .filter { it <= 100000 } .sum() fun day7part2() = createMapOfSizes(Files.readString(Paths.get("input/07.txt"))) .let { it[listOf("/")]!! to it.values } .let { (used, values) -> values.sorted().first { 70000000 - 30000000 - used + it > 0 } }
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day07Kt.class", "javap": "Compiled from \"day07.kt\"\npublic final class days.Day07Kt {\n public static final java.util.Map<java.util.List<java.lang.String>, java.lang.Integer> createMapOfSizes(java.lang.String);\n Code:\n 0: aload_0\n 1: ld...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day02.kt
package days import java.nio.file.Files import java.nio.file.Paths import kotlin.streams.asSequence sealed interface Option object Rock : Option object Paper : Option object Scissors : Option fun String.parseOption() = when (this) { "A", "X" -> Rock "B", "Y" -> Paper "C", "Z" -> Scissors else -> throw IllegalArgumentException(this) } fun Pair<Option, Option>.matchPoints() = when(this) { Pair(Scissors, Rock), Pair(Rock, Paper), Pair(Paper, Scissors) -> 6 else -> when (this.first) { this.second -> 3 else -> 0 } } fun Option.selectionPoints() = when(this) { Rock -> 1 Paper -> 2 Scissors -> 3 } fun day2Part1() = Files.lines(Paths.get("input/02.txt")).asSequence() .map { it.split(" ") } .map { it[0].parseOption() to it[1].parseOption() } .map { it.matchPoints() + it.second.selectionPoints() } .sum() sealed interface Result object Win: Result object Draw: Result object Lose: Result fun String.parseResult() = when (this) { "X" -> Lose "Y" -> Draw "Z" -> Win else -> throw IllegalArgumentException(this) } fun neededFor(result: Result, option: Option) = when (result) { Lose -> when (option) { Rock -> Scissors Paper -> Rock Scissors -> Paper } Draw -> option Win -> when (option) { Rock -> Paper Paper -> Scissors Scissors -> Rock } } fun day2part2() = Files.lines(Paths.get("input/02.txt")).asSequence() .map { it.split(" ") } .map { it[0].parseOption() to it[1].parseResult() } .map { (option, result) -> option to neededFor(result, option) } .map { it.matchPoints() + it.second.selectionPoints() } .sum()
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day02Kt.class", "javap": "Compiled from \"day02.kt\"\npublic final class days.Day02Kt {\n public static final days.Option parseOption(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 // String <this>\n 3: ...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day09.kt
package days import java.io.File import kotlin.math.abs import kotlin.math.max fun Pair<Int, Int>.moveHead(cmd: Char) = when (cmd) { 'U' -> this.first to this.second + 1 'R' -> this.first + 1 to this.second 'D' -> this.first to this.second - 1 'L' -> this.first - 1 to this.second else -> throw IllegalArgumentException() } fun Pair<Int, Int>.moveTail(head: Pair<Int, Int>) = when { this.isTouching(head) -> this this.second == head.second -> when { head.first < this.first -> this.first - 1 to this.second else -> this.first + 1 to this.second } this.first == head.first -> when { head.second < this.second -> this.first to this.second - 1 else -> this.first to this.second + 1 } else -> when { head.second < this.second -> when { head.first < this.first -> this.first - 1 to this.second - 1 else -> this.first + 1 to this.second - 1 } else -> when { head.first < this.first -> this.first - 1 to this.second + 1 else -> this.first + 1 to this.second + 1 } } } fun Pair<Int, Int>.isTouching(point: Pair<Int, Int>) = max(abs(point.first - this.first), abs(point.second - this.second)) <= 1 fun tailPositions(commands: List<String>, knotsSize: Int) = commands .map { it.split(" ") } .map { it[0].repeat(it[1].toInt()) } .flatMap { it.toList() } .scan(List(knotsSize) { 0 to 0 }) { knots, cmd -> knots.drop(1).fold(listOf(knots.first().moveHead(cmd))) { acc, knot -> acc + knot.moveTail(acc.last()) } } .map { it.last() } .toSet() .size fun day9part1() = tailPositions(File("input/09.txt").readLines(), 2) fun day9part2() = tailPositions(File("input/09.txt").readLines(), 10)
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day09Kt.class", "javap": "Compiled from \"day09.kt\"\npublic final class days.Day09Kt {\n public static final kotlin.Pair<java.lang.Integer, java.lang.Integer> moveHead(kotlin.Pair<java.lang.Integer, java.lang.Integer>, char);\n Code:\n 0: aload_0...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day08.kt
package days import java.io.File fun <T> List<List<T>>.transpose(): List<List<T>> = when { this.first().isEmpty() -> listOf() else -> listOf(this.map { it.first() }) + this.map { it.drop(1) }.transpose() } fun day8part1() = File("input/08.txt").readLines() .mapIndexed { i, e1 -> e1.mapIndexed { j, e2 -> (i to j) to e2.digitToInt() }} .let { it to it.reversed().map { c -> c.reversed() } } .let { (mat, matRev) -> mat + matRev + mat.transpose() + matRev.transpose() } .map { it.fold(setOf<Pair<Pair<Int, Int>, Int>>()) { acc, c -> if (acc.isNotEmpty() && acc.maxOf { ac -> ac.second } >= c.second) acc else acc.plus(c) } } .flatten().toSet() .count() fun <T> List<T>.takeWhileInclusive(pred: (T) -> Boolean): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = pred(it) result } } fun day8part2() = File("input/08.txt").readLines() .mapIndexed { i, e1 -> e1.mapIndexed { j, e2 -> (i to j) to e2.digitToInt() } } .let { it to it.reversed().map { c -> c.reversed() } } .let { (mat, matRev) -> mat + matRev + mat.transpose() + matRev.transpose() } .fold(mutableMapOf<Pair<Pair<Int, Int>, Int>, List<List<Pair<Pair<Int, Int>, Int>>>>()) { acc, p -> p.forEachIndexed { index, pair -> if (acc.containsKey(pair)) acc[pair] = acc[pair]!!.plus(listOf(p.subList(index + 1, p.size))) else acc[pair] = listOf(p.subList(index + 1, p.size)) } acc }.entries .map { it.key.second to it.value.map { lp -> lp.map { p -> p.second } } } .map { (element, neighbours) -> neighbours.map { it.takeWhileInclusive { tree -> tree < element }.count() } } .maxOf { it.reduce { acc, i -> acc * i } }
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day08Kt.class", "javap": "Compiled from \"day08.kt\"\npublic final class days.Day08Kt {\n public static final <T> java.util.List<java.util.List<T>> transpose(java.util.List<? extends java.util.List<? extends T>>);\n Code:\n 0: aload_0\n 1: l...
josergdev__aoc-2022__ea17b3f/src/main/kotlin/days/day11.kt
package days import java.io.File fun String.parseMonkeys() = this .split("\n\n") .map { it.split("\n").map { l -> l.trim() } } .map { Pair( it[0].replace("Monkey ", "").replace(":", "").toLong(), Triple( it[1].replace("Starting items: ", "").split(",").map { item -> item.trim().toLong() }, it[2].replace("Operation: new = ", "").parseOp(), Triple( it[3].replace("Test: divisible by ", "").toLong(), it[4].replace("If true: throw to monkey ", "").toLong(), it[5].replace("If false: throw to monkey ", "").toLong()))) } .map { (monkey, monkeyData) -> (monkey to (monkeyData.first to 0L)) to (monkey to (monkeyData.second to monkeyData.third)) } .let { it.associate { p -> p.first } to it.associate { p -> p.second } } fun String.parseOp() = when { this == "old * old" -> { old: Long -> old * old } this.contains("old +") -> this.replace("old + ", "").toLong().let { { old: Long -> old + it } } else -> this.replace("old * ", "").toLong().let { { old: Long -> old * it } } } fun executeRound( monkeyItems: Map<Long, Pair<List<Long>, Long>>, monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>, worryReduction: (Long) -> Long ) = monkeyItems.keys.fold(monkeyItems) { map, monkey -> monkeyInspect(map, monkeyBehaviour, worryReduction, monkey) } fun monkeyInspect( monkeyItems: Map<Long, Pair<List<Long>, Long>>, monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>, worryReduction: (Long) -> Long, monkey: Long ) = monkeyItems[monkey]!!.first.fold(monkeyItems) { map , item -> inspectItem(map, monkeyBehaviour, worryReduction, monkey, item) } fun inspectItem( monkeyItems: Map<Long, Pair<List<Long>, Long>>, monkeyBehaviour: Map<Long, Pair<(Long) -> Long, Triple<Long, Long, Long>>>, worryReduction: (Long) -> Long, monkey: Long, item: Long ) = monkeyItems.toMutableMap().let { it[monkey] = it[monkey]!!.first.drop(1) to it[monkey]!!.second + 1 val newItem = monkeyBehaviour[monkey]!!.first(item) val newItemReduced = worryReduction(newItem) val newMonkey = if ((newItemReduced % monkeyBehaviour[monkey]!!.second.first) == 0L) monkeyBehaviour[monkey]!!.second.second else monkeyBehaviour[monkey]!!.second.third it[newMonkey] = it[newMonkey]!!.first.plus(newItemReduced) to it[newMonkey]!!.second it.toMap() } fun monkeyBusiness(monkeyItems: Map<Long, Pair<List<Long>, Long>>) = monkeyItems .entries.map { it.value.second } .sortedDescending() .take(2) .reduce { acc, act -> acc * act } fun day11part1() = File("input/11.txt").readText() .parseMonkeys() .let { (monkeyItems, monkeyBehaviour) -> (1 .. 20).fold(monkeyItems) { map, _ -> executeRound(map, monkeyBehaviour) { level -> level.div(3)} } } .let { monkeyBusiness(it) } fun day11part2() = File("input/11.txt").readText() .parseMonkeys() .let { (monkeyItems, monkeyBehaviour) -> (1 .. 10000).fold(monkeyItems) { map, _ -> executeRound(map, monkeyBehaviour, monkeyBehaviour.values.map { mbv -> mbv.second.first }.reduce(Long::times).let { { level: Long -> level.mod(it) } } ) } } .let { monkeyBusiness(it) }
[ { "class_path": "josergdev__aoc-2022__ea17b3f/days/Day11Kt.class", "javap": "Compiled from \"day11.kt\"\npublic final class days.Day11Kt {\n public static final kotlin.Pair<java.util.Map<java.lang.Long, kotlin.Pair<java.util.List<java.lang.Long>, java.lang.Long>>, java.util.Map<java.lang.Long, kotlin.Pair<...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/OasisReport.kt
package com.oocode fun oasisReportFrom(input: String): OasisReport = OasisReport(input .split("\n") .map { line -> OasisHistory(line.split(" ").map { it.toInt() }) }) data class OasisReport(private val histories: List<OasisHistory>) { fun extrapolatedValuesSum(): Int { return histories.map { it.extrapolatedValue() }.sum() } } data class OasisHistory(private val history: List<Int>) { fun extrapolatedValue(): Int = extrapolated() .map { it.first() } .foldRight(0, { i, accumulator -> i - accumulator }) private fun extrapolated(): List<OasisHistory> = listOf(this) + if (history.all { it == 0 }) { emptyList() } else { OasisHistory(nextHistoryRow(history)).extrapolated() } private fun first() = history[0] } fun nextHistoryRow(input: List<Int>) = input.mapIndexed { index, i -> i - input[Math.max(0, index - 1)] }.drop(1)
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/OasisReportKt.class", "javap": "Compiled from \"OasisReport.kt\"\npublic final class com.oocode.OasisReportKt {\n public static final com.oocode.OasisReport oasisReportFrom(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/Almanac.kt
package com.oocode fun almanacFrom(input: String): Almanac { val lines = input.split("\n") val seedNumbers = lines[0].split(" ").drop(1).map { it.toLong() } val seeds = seedNumbers.chunked(2).map { val startNumber = it[0] val rangeSize = it[1] InputRange(startNumber, (startNumber + rangeSize) - 1) } val converters = mutableListOf<Converter>() var currentMappings = mutableListOf<Mapping>() lines.drop(1).forEach { line -> if (line.isEmpty()) { if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) currentMappings = mutableListOf() } else { val numbers = numbersFrom(line) if (numbers.isNotEmpty()) { currentMappings.add(Mapping(numbers[0], numbers[1], numbers[2])) } } } if (currentMappings.isNotEmpty()) converters.add(Converter(currentMappings)) return Almanac(seeds, ConverterChain(converters)) } data class InputRange(val startNumber: Long, val endNumber: Long) private fun numbersFrom(line: String) = Regex("(\\d+)") .findAll(line) .map { it.value.toLong() } .toList() class Almanac(private val seeds: List<InputRange>, private val converterChain: ConverterChain) { fun lowestLocationNumber() = seeds.flatMap { converterChain.convert(it) }.map { it.startNumber }.min() } data class Mapping( private val destinationRangeStart: Long, private val sourceRangeStart: Long, private val rangeLength: Long, ) { val sourceRange = LongRange(sourceRangeStart, sourceRangeStart + rangeLength - 1) fun find(sourceNumber: Long) = if (sourceRange.contains(sourceNumber)) destinationRangeStart + (sourceNumber - sourceRangeStart) else null } class Converter(private val mappings: List<Mapping>) { fun convert(sourceNumber: Long) = mappings.firstNotNullOfOrNull { it.find(sourceNumber) } ?: sourceNumber fun convert(inputRanges: Set<InputRange>): Set<InputRange> = inputRanges.flatMap { convert(it) }.toSet() fun convert(inputRange: InputRange): Set<InputRange> { val mappingsInOrder = overlappingMappings(inputRange) if (mappingsInOrder.isEmpty()) { return setOf(inputRange) } val firstMappingSourceRange = mappingsInOrder[0].sourceRange val firstMappingStart = firstMappingSourceRange.start if (inputRange.startNumber < firstMappingStart) { return setOf(inputRange.copy(endNumber = firstMappingStart - 1)) + convert(inputRange.copy(startNumber = firstMappingStart)) } if (inputRange.endNumber <= firstMappingSourceRange.endInclusive) { return mapped(inputRange) } return mapped(inputRange.copy(endNumber = firstMappingSourceRange.endInclusive)) + convert(inputRange.copy(startNumber = firstMappingSourceRange.endInclusive + 1)) } private fun mapped(inputRange: InputRange): Set<InputRange> = setOf(InputRange(convert(inputRange.startNumber), convert(inputRange.endNumber))) private fun overlappingMappings(inputRange: InputRange) = mappings .sortedBy { it.sourceRange.first } .filter { it.sourceRange.overlapsWith(inputRange) } } private fun LongRange.overlapsWith(inputRange: InputRange) = !(inputRange.endNumber < start || inputRange.startNumber > endInclusive) class ConverterChain(private val converters: List<Converter>) { fun convert(sourceNumber: InputRange) = converters.fold(setOf(sourceNumber), { accumulator, converter -> converter.convert(accumulator) }) }
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/AlmanacKt.class", "javap": "Compiled from \"Almanac.kt\"\npublic final class com.oocode.AlmanacKt {\n public static final com.oocode.Almanac almanacFrom(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/CamelCards.kt
package com.oocode fun camelCardHandsFrom(input: String): CamelCardHands = CamelCardHands(input.split("\n") .map { line -> line.split(" ").let { CamelCardHand(it[0]) to it[1].toInt() } }) class CamelCardHands(private val handsWithBids: List<Pair<CamelCardHand, Int>>) { fun totalWinnings(): Int { val sortedBy = handsWithBids.sortedBy { it.first } return sortedBy.foldIndexed(0, { index, accumulator, cardWithBid -> accumulator + (cardWithBid.second * (index + 1)) }) } } data class CamelCardHand(val cards: String) : Comparable<CamelCardHand> { enum class Type { HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND } private val labels = "AKQT98765432J".reversed() override operator fun compareTo(other: CamelCardHand): Int { if (this.type() == other.type()) { fun makeEasilyComparable(cards: String) = cards.map { labels.indexOf(it) }.map { 'a'.plus(it) }.toString() return makeEasilyComparable(this.cards).compareTo(makeEasilyComparable(other.cards)) } return this.type().compareTo(other.type()) } private fun type(): Type { val cardsWithJSubstituted = cards.replace('J', mostCommonNonJCard()) val groupsOfSameCards = cardsWithJSubstituted.groupBy { it } if (groupsOfSameCards.size == 1) return Type.FIVE_OF_A_KIND if (groupsOfSameCards.size == 2) if (groupsOfSameCards.map { it.value.size }.max() == 4) return Type.FOUR_OF_A_KIND else return Type.FULL_HOUSE if (groupsOfSameCards.size == 3) if (groupsOfSameCards.map { it.value.size }.max() == 3) return Type.THREE_OF_A_KIND else return Type.TWO_PAIR if (groupsOfSameCards.size == 4) return Type.ONE_PAIR else return Type.HIGH_CARD } private fun mostCommonNonJCard() = if(cards == "JJJJJ") // very special case 'J' else cards.groupBy { it } .filter { it.key != 'J' } .map { it.value } .sortedBy { it.size } .reversed()[0][0] // doesn't matter which one of equal commonality } fun camelCardHandFrom(s: String) = CamelCardHand(s)
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/CamelCardsKt.class", "javap": "Compiled from \"CamelCards.kt\"\npublic final class com.oocode.CamelCardsKt {\n public static final com.oocode.CamelCardHands camelCardHandsFrom(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/Bag.kt
package com.oocode fun powerOf(input: String) = input.split("\n").sumOf { line -> gameFrom(line).power() } data class Bag(val red: Int, val green: Int, val blue: Int) { fun possibilityTotal(input: String) = input.split("\n").sumOf { line -> line.possibilityValue(this) } fun power() = red * green * blue } private fun String.possibilityValue(bag: Bag) = gameFrom(this).possibilityValue(bag) data class Game(val number: Int, val reveals: Set<Reveal>) { fun possibilityValue(bag: Bag) = if (reveals.all { it.isPossibleGiven(bag) }) number else 0 fun minimumBag() = reveals.maxBag() fun power() = minimumBag().power() } private fun Set<Reveal>.maxBag() = Bag(red = maxRed(), green = maxGreen(), blue = maxBlue()) private fun Set<Reveal>.maxRed() = maxOf { it.red } private fun Set<Reveal>.maxGreen() = maxOf { it.green } private fun Set<Reveal>.maxBlue() = maxOf { it.blue } data class Reveal(val red: Int = 0, val green: Int = 0, val blue: Int = 0) { fun isPossibleGiven(bag: Bag) = red <= bag.red && green <= bag.green && blue <= bag.blue } // "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green" fun gameFrom(line: String): Game { val number = line.split(":")[0].split(" ")[1].toInt() val revealStrings = line.split(":")[1].split(";") return Game(number, revealStrings.map { revealFrom(it) }.toSet()) } fun revealFrom(revealString: String): Reveal { val colorNumberPairs = revealString.split(",").associate { asColorNumberPair(it.trim()) } return Reveal( red = colorNumberPairs["red"] ?: 0, green = colorNumberPairs["green"] ?: 0, blue = colorNumberPairs["blue"] ?: 0, ) } fun asColorNumberPair(colorNumberPairString: String): Pair<String, Int> = colorNumberPairString.split(" ")[1] to colorNumberPairString.split(" ")[0].toInt()
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/BagKt.class", "javap": "Compiled from \"Bag.kt\"\npublic final class com.oocode.BagKt {\n public static final int powerOf(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 // String input\n ...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/PipesGrid.kt
package com.oocode fun pipesGridFrom(input: String): PipesGrid { val lines = input.split("\n") val tiles = lines.mapIndexed { y, line -> tilesFrom(y, line) } return PipesGrid(tiles) } data class PipesGrid(val tiles: List<List<Tile>>) { fun furthestDistanceFromStart() = path().size / 2 fun path(): MutableList<Tile> { val path = mutableListOf<Tile>() var current: Tile? = start() while (current != null) { path.add(current) current = nextTile(current, path) } return path } fun start() = tiles.flatten().first { it.type == START } fun nextTile(current: Tile, path: List<Tile>): Tile? = neighbouringTiles(current.position) .filter { !path.contains(it.tile) } .filter { it.canBeReachedFrom(it.directionTowardsThis.opposite) } .filter { current.canBeReachedFrom(it.directionTowardsThis) } .map { it.tile } .firstOrNull() fun neighbouringTiles(sourcePosition: Position) = neighbouringPositions(sourcePosition) .map { NeighbouringTile(it.outwardDirection, tileAt(it.position)) } private fun tileAt(position: Position): Tile = tiles[position.y][position.x] override fun toString(): String = tiles .map { it.map { it.type.toString() }.joinToString("") } .joinToString("\n") private fun neighbouringPositions(position: Position): Set<NeighbouringPosition> = Compass.values() .map { NeighbouringPosition(position + it.relativePosition, it) } .filter { isInBounds(it) } .toSet() private fun isInBounds(neighbouringPosition: NeighbouringPosition) = neighbouringPosition.position.let { position -> position.x >= 0 && position.y >= 0 && position.x < width && position.y < height } val width: Int get() = tiles[0].size val height: Int get() = tiles.size } enum class Compass(val relativePosition: Position) { North(Position(0, -1)), South(Position(0, 1)), East(Position(1, 0)), West(Position(-1, 0)); val opposite: Compass get() = when(this) { North -> South South -> North East -> West West -> East } } interface TileType { fun canBeReachedFrom(positionRelativeToMe: Compass): Boolean } data class ConnectingTileType(val representation: String, val outgoing1: Compass, val outgoing2: Compass) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = outgoing1 == positionRelativeToMe || outgoing2 == positionRelativeToMe override fun toString() = representation } data class Ground(val representation: String) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = false override fun toString() = representation } private data class NeighbouringPosition(val position: Position, val outwardDirection: Compass) data class NeighbouringTile(val directionTowardsThis: Compass, val tile: Tile) { fun canBeReachedFrom(direction: Compass) = tile.canBeReachedFrom(direction) } data class Start(val representation: String) : TileType { override fun canBeReachedFrom(positionRelativeToMe: Compass) = true override fun toString() = representation } val NE = ConnectingTileType("L", Compass.North, Compass.East) val NW = ConnectingTileType("J", Compass.North, Compass.West) val NS = ConnectingTileType("|", Compass.North, Compass.South) val EW = ConnectingTileType("-", Compass.East, Compass.West) val SE = ConnectingTileType("F", Compass.South, Compass.East) val SW = ConnectingTileType("7", Compass.South, Compass.West) val GROUND = Ground(".") val START = Start("S") data class Position(val x: Int, val y: Int) { operator fun plus(other: Position): Position = Position(x + other.x, y + other.y) } data class Tile(val type: TileType, val position: Position) { fun canBeReachedFrom(direction: Compass): Boolean = direction.let { type.canBeReachedFrom(it) } } fun tilesFrom(y: Int, line: String): List<Tile> = line.mapIndexed { x, c -> tileFor(c.toString(), x, y) } fun tileFor(name: String, x: Int, y: Int) = Tile(tileTypeFor(name), Position(x, y)) fun tileTypeFor(name: String) = when (name) { "|" -> NS "-" -> EW "F" -> SE "7" -> SW "L" -> NE "J" -> NW "." -> GROUND "S" -> START else -> { throw RuntimeException("Unexpected name: $name") } }
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/PipesGrid.class", "javap": "Compiled from \"PipesGrid.kt\"\npublic final class com.oocode.PipesGrid {\n private final java.util.List<java.util.List<com.oocode.Tile>> tiles;\n\n public com.oocode.PipesGrid(java.util.List<? extends java.uti...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/EngineSchematic.kt
package com.oocode fun engineSchematicFrom(input: String): EngineSchematic { val lines = input.split("\n") val numbers = lines.flatMapIndexed { index, line -> numbersFrom(line, index) }.toSet() val symbols = lines.flatMapIndexed { index, line -> symbolsFrom(line, index) }.toSet() val gearIndicators = lines.flatMapIndexed { index, line -> gearIndicatorsFrom(line, index) }.toSet() return EngineSchematic(numbers, symbols, gearIndicators) } private fun Number.isNextToASymbol(symbols: Set<Symbol>) = symbols.any { symbol -> isNextTo(symbol.position) } private fun Pair<Int, Int>.isNextTo(position: Pair<Int, Int>) = Math.abs(first - position.first) <= 1 && Math.abs(second - position.second) <= 1 private fun numbersFrom(line: String, y: Int) = Regex("(\\d+)") .findAll(line) .map { Number(Pair(it.range.first, y), it.value) } .toSet() private fun symbolsFrom(line: String, y: Int): Set<Symbol> = line.mapIndexedNotNull { x, c -> if (c.isSymbol()) Symbol(Pair(x, y)) else null }.toSet() private fun gearIndicatorsFrom(line: String, y: Int): Set<GearIndicator> = line.mapIndexedNotNull { x, c -> if (c.isGearIndicator()) GearIndicator(Pair(x, y)) else null }.toSet() private fun Char.isSymbol() = !isDigit() && this != '.' private fun Char.isGearIndicator() = this == '*' data class Number(val startPosition: Pair<Int, Int>, val value: String) { fun positions(): Set<Pair<Int, Int>> = value.mapIndexed { index, _ -> startPosition.copy(startPosition.first + index) }.toSet() fun isNextTo(position: Pair<Int, Int>) = positions().any { it.isNextTo(position) } } data class Symbol(val position: Pair<Int, Int>) data class GearIndicator(val position: Pair<Int, Int>) class EngineSchematic( private val numbers: Set<Number>, private val symbols: Set<Symbol>, private val gearIndicators: Set<GearIndicator> ) { fun total() = partNumbers().sumOf { it.value.toInt() } private fun partNumbers() = numbers.filter { number -> number.isNextToASymbol(symbols) }.toSet() fun gearRatiosTotal() = gearIndicators .map { gearIndicator -> numbers .filter { number -> number.isNextTo(gearIndicator.position) } .map { it.value.toInt() } } .filter { it.size == 2 } .sumOf { it[0] * it[1] } }
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/EngineSchematicKt.class", "javap": "Compiled from \"EngineSchematic.kt\"\npublic final class com.oocode.EngineSchematicKt {\n public static final com.oocode.EngineSchematic engineSchematicFrom(java.lang.String);\n Code:\n 0: aload...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/ScratchCard.kt
package com.oocode fun scratchCardScoreFrom(input: String): Int = input.split("\n").mapIndexed { index, line -> scratchCardComparisonFrom(index + 1, line).score() }.sum() fun scratchCardsFrom(input: String): Map<Int, List<ScratchCardComparison>> { val scratchCardComparisons = input.split("\n").mapIndexed { index, line -> scratchCardComparisonFrom(index + 1, line) } val scratchCardComparisonsByCardNumber = scratchCardComparisons.associateBy { it.cardNumber } val withCopies = mutableListOf<ScratchCardComparison>() IntRange(1, scratchCardComparisons.size).forEach { iterateWithCopies(it, scratchCardComparisonsByCardNumber) { scratchCard -> withCopies.add(scratchCard) } } return withCopies.groupBy { it.cardNumber } } fun scratchCardNumberFrom(input: String) = scratchCardsFrom(input).values.sumOf { it.size } fun iterateWithCopies( cardNumber: Int, scratchCards: Map<Int, ScratchCardComparison>, f: (scratchCard: ScratchCardComparison) -> Any ) { if (cardNumber > scratchCards.size) return val head = scratchCards[cardNumber]!! f(head) val rangeOfCardsToCopy = IntRange(cardNumber + 1, cardNumber + head.numberOfCorrectGuesses()) rangeOfCardsToCopy.forEach { iterateWithCopies(it, scratchCards, f) } } fun scratchCardComparisonFrom(cardNumber: Int, line: String): ScratchCardComparison = line.split(":")[1].split("|").let { val winningNumbers = numbersFrom(it[0]) val guesses = numbersFrom(it[1]) return ScratchCardComparison(cardNumber, winningNumbers, guesses) } private fun numbersFrom(s: String) = s.trim().split(Regex("\\s+")) .map { it.toInt() } .toSet() data class ScratchCardComparison( val cardNumber: Int, private val winningNumbers: Set<Int>, private val guesses: Set<Int> ) { fun score() = numberOfCorrectGuesses().let { if (it == 0) 0 else twoToPowerOf(it - 1) } fun numberOfCorrectGuesses() = winningNumbers.intersect(guesses).size } fun twoToPowerOf(i: Int) = IntRange(0, i - 1) .fold(1, { accumlator, _ -> accumlator * 2 })
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/ScratchCardKt.class", "javap": "Compiled from \"ScratchCard.kt\"\npublic final class com.oocode.ScratchCardKt {\n public static final int scratchCardScoreFrom(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ...
ivanmoore__advent-of-code-2023__36ab66d/src/main/kotlin/com/oocode/CamelMap.kt
package com.oocode fun directionsFrom(input: String): CamelMap { val lines = input.split("\n") val instructions = lines[0] .map { if (it == 'L') Choice.Left else Choice.Right } val nodes = lines.drop(2).map { nodeFrom(it) } return CamelMap(instructions, nodes) } enum class Choice { Left, Right } data class CamelMap( private val instructions: List<Choice>, private val nodes: List<Node> ) { private val nodesByName = nodes.associateBy { it.name } fun numberOfSteps(): Long { val startNodes = nodes.filter { it.name.endsWith("A") } val numberOfStepsForEveryStartingNode = startNodes.map { numberOfSteps(it) } return findLCMOfListOfNumbers(numberOfStepsForEveryStartingNode) } private fun numberOfSteps(startNode: Node): Long { var currentNode = startNode var result = 0L while (true) { instructions.forEach { instruction -> if (currentNode.name.endsWith("Z")) return result result++ currentNode = nodesByName[currentNode.follow(instruction)]!! } } } } fun nodeFrom(line: String): Node = line .replace("(", "") .replace(")", "") .split("=") .let { val name = it[0].trim() val children = it[1].split(",") return Node(name, Children(children[0].trim(), children[1].trim())) } data class Children(val left: String, val right: String) data class Node(val name: String, val children: Children) { fun follow(instruction: Choice) = if(instruction==Choice.Left) children.left else children.right } // Copied from https://www.baeldung.com/kotlin/lcm (and then replaced Int with Long) // because I'm not interested in this part of the solution. // I would expect this to be a thing you could find in a library fun findLCM(a: Long, b: Long): Long { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } fun findLCMOfListOfNumbers(numbers: List<Long>): Long { var result = numbers[0] for (i in 1 until numbers.size) { result = findLCM(result, numbers[i]) } return result }
[ { "class_path": "ivanmoore__advent-of-code-2023__36ab66d/com/oocode/CamelMapKt.class", "javap": "Compiled from \"CamelMap.kt\"\npublic final class com.oocode.CamelMapKt {\n public static final com.oocode.CamelMap directionsFrom(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ...
widi-nugroho__kotlin-statistics__a116609/src/main/kotlin/descriptive/Descriptive.kt
package descriptive import java.util.* import kotlin.math.floor import kotlin.math.sqrt object Descriptive { fun mean (a:List<Double>):Double{ var res=0.0 for (i in a){ res+=i } return res/a.size } fun median(a:List<Double>):Double{ val sorted=a.sorted() if (sorted.size%2==0){ val i1=sorted.size/2 val i2=i1-1 return (sorted[i1]+sorted[i2])/2 }else{ val i= floor((sorted.size/2).toDouble()).toInt() return sorted[i] } } fun mode(a:List<Double>):Double{ val res= mutableMapOf<Double,Int>() val listnya= mutableListOf<Pair<Double,Int>>() for (i in a){ if (res.containsKey(i)){ res[i]=res[i]!!+1 }else{ res[i]=1 } } for ((k,v) in res){ var a = Pair(k,v) listnya.add(a) } listnya.sortBy { it.second } return listnya.last().first } fun varians(a:List<Double>):Double{ val mean= mean(a) var difftotal=0.0 for (i in a){ var diff=i-mean difftotal+=diff*diff } var res=difftotal/a.size return res } fun standardDeviaton(a:List<Double>):Double{ return(sqrt(varians(a))) } } fun main(){ var a=mutableListOf<Double>(5.0,2.0,2.0,2.0,7.0,4.0,1.0) println(a.sorted()) println(Descriptive.median(a)) println(Descriptive.mode(a)) println(Descriptive.varians(a)) println(Descriptive.standardDeviaton(a)) var c=Random(10) println(c) }
[ { "class_path": "widi-nugroho__kotlin-statistics__a116609/descriptive/DescriptiveKt.class", "javap": "Compiled from \"Descriptive.kt\"\npublic final class descriptive.DescriptiveKt {\n public static final void main();\n Code:\n 0: bipush 7\n 2: anewarray #8 // cla...
kotler-dev__kotlin-leetcode__0659e72/src/main/kotlin/exercise/easy/id121/Solution121.kt
package exercise.easy.id121 class Solution121 { fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 var min = Int.MAX_VALUE var max = 0 for (i in 0..<prices.size) { if (prices[i] < min) { min = prices[i] max = 0 } if (prices[i] > max) max = prices[i] if (max - min > profit) profit = max - min } return profit } /* fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 var min = Int.MAX_VALUE var max = 0 val minn = prices.slice(1..<prices.size).minBy { it } val m = prices.slice(1..<prices.size).maxBy { it } val mIndex = prices.lastIndexOf(m) for (i in 0..mIndex) { if (prices[i] < min) { min = prices[i] max = m } if (prices[i] > max) max = prices[i] if (max - min > profit) profit = max - min } return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 for (i in prices.indices) { for (j in i + 1..<prices.size) { if (prices[j] - prices[i] > profit) { profit = prices[j] - prices[i] } } } return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 val min = prices.slice(0..prices.size - 1).indices.minBy { prices[it] } val minIndex = prices.lastIndexOf(prices[min]) val p = prices.slice(minIndex..prices.size - 1) val max = p.indices.maxBy { p[it] } val maxIndex = p.lastIndexOf(p[max]) val result = p[maxIndex] - prices[minIndex] if (result > profit) profit = result return profit } fun maxProfit(prices: IntArray): Int { var profit = 0 for ((index, value) in prices.withIndex()) { val i1 = index + 1 if (i1 < prices.size) { if (prices[i1] > value) { val max = prices.slice(i1..prices.size - 1).max() if (profit < max - value) { profit = max - value } } } } return profit } fun maxProfit(prices: IntArray): Int { var profit = 0 val minIndex = prices.indices.minBy { prices[it] } ?: 0 val slice = prices.slice(minIndex..prices.size - 1) val maxIndex = slice.indices.maxBy { slice[it] } ?: 0 val result = slice[maxIndex] - prices[minIndex] if (result > profit) profit = result return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 val maxSlice = prices.slice(1..prices.size - 1) val maxIndex = maxSlice.indices.maxBy { maxSlice[it] } ?: 0 val minSlice = prices.slice(0..maxSlice.lastIndexOf(maxSlice[maxIndex])) val minIndex = minSlice.indices.minBy { minSlice[it] } ?: 0 val result = maxSlice[maxIndex] - minSlice[minIndex] if (result > profit) profit = result return profit } */ }
[ { "class_path": "kotler-dev__kotlin-leetcode__0659e72/exercise/easy/id121/Solution121.class", "javap": "Compiled from \"Solution121.kt\"\npublic final class exercise.easy.id121.Solution121 {\n public exercise.easy.id121.Solution121();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
kotler-dev__kotlin-leetcode__0659e72/src/main/kotlin/exercise/medium/id57/Solution57.kt
package exercise.medium.id57 import kotlin.math.max import kotlin.math.min class Solution57 { fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) if (newInterval.isEmpty()) return intervals println("[${newInterval[0]}, ${newInterval[1]}]") var start = newInterval[0] var end = newInterval[1] val left = 0 val right = 1 val merged = mutableListOf<IntArray>() var index = 0 while (index < intervals.size && intervals[index][right] < start) { merged.add(intervals[index]) index++ } while (index < intervals.size && intervals[index][left] <= end) { start = min(start, intervals[index][left]) end = max(end, intervals[index][right]) index++ } merged.add(intArrayOf(start, end)) while (index < intervals.size) { merged.add(intervals[index]) index++ } return merged.toTypedArray() } /* fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) println("[${newInterval[0]}, ${newInterval[1]}]") val start = newInterval[0] val end = newInterval[1] val left = 0 val right = 1 val merged1 = mutableListOf<IntArray>() var index1 = 0 while (index1 < intervals.size && intervals[index1][right] < start) { merged1.add(intervals[index1]) index1++ } if (intervals.size == 1) index1-- val merged2 = mutableListOf<IntArray>() var index2 = intervals.size - 1 while (index2 >= 0 && intervals[index2][left] > end) { merged2.add(intervals[index2]) index2-- } if (intervals.size > 1) { val min = min(start, intervals[index1][left]) val max = max(end, intervals[index2][right]) merged1.add(intArrayOf(min, max)) } merged2.forEach { merged1.add(it) } return merged1.toTypedArray() } var index2 = index while (index2 < intervals.size) { if (intervals[index2][left] > end) { array.add(intervals[index2]) index2++ } } for ((index, arr) in intervals.withIndex()) { if (arr[right] < start) { array.add(arr) } } while (index < intervals.size ) { val value = intervals[index][right] if (value < start) { array.add(intervals[index]) } else if (value < intervals[index][leftIndex]) { intervals[index][right] = end array.add(intervals[index]) sliceStart = index break } } for (index in intervals.indices) { val value = intervals[index][rightIndex] if (value < start) { array.add(intervals[index]) } else if (value < intervals[index][leftIndex]) { intervals[index][rightIndex] = end array.add(intervals[index]) sliceStart = index break } } fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { println("[${newInterval[0]}, ${newInterval[1]}]") val arrayFlatten = mutableListOf<Int>() for (index in intervals.indices) { arrayFlatten.add(intervals[index][0]) arrayFlatten.add(intervals[index][1]) } val arrayNonOverlapping = mutableListOf<Int>() for (index in 0..<arrayFlatten.size) { if (arrayFlatten[index] !in newInterval[0]..newInterval[1]) { println("==> ${arrayFlatten[index]}") arrayNonOverlapping.add(arrayFlatten[index]) } } val arr = mutableListOf<IntArray>() for (index in 0..arrayNonOverlapping.size - 1 step 2) { arr.add(intArrayOf(arrayNonOverlapping[index], arrayNonOverlapping[index + 1])) } return arr.toTypedArray() } fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { println("[${newInterval[0]}, ${newInterval[1]}]") val list = intervals.flatMap { it.asIterable() }.toMutableList() val start = newInterval[0] val end = newInterval[1] if (start !in list) list.add(start) if (end !in list) list.add(end) list.sort() var shiftLeft = 1 var shiftRight = 1 if (list.size % 2 != 0) shiftLeft-- val part1: List<Int> = list.slice(0..<list.indexOf(start) - shiftLeft) if (part1.size % 2 == 0) shiftRight++ val part2: List<Int> = list.slice(list.indexOf(end) + shiftRight..<list.size) val part3: List<Int> = listOf(part1, part2).flatten() val arr2 = mutableListOf<IntArray>() for (index in 0..part3.size - 1 step 2) { arr2.add(intArrayOf(part3[index], part3[index + 1])) } return arr2.toTypedArray() } */ }
[ { "class_path": "kotler-dev__kotlin-leetcode__0659e72/exercise/medium/id57/Solution57.class", "javap": "Compiled from \"Solution57.kt\"\npublic final class exercise.medium.id57.Solution57 {\n public exercise.medium.id57.Solution57();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
ghasemdev__affogato__36ec37d/affogato-core-ktx/src/main/java/com/parsuomash/affogato/core/ktx/collections/Map.kt
package com.parsuomash.affogato.core.ktx.collections /** * Returns a [HashMap] containing all elements. * * Example: * ```Kotlin * mapOf(1 to 2, 2 to 3).toHashMap() // {1=2, 2=3} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.toHashMap(): HashMap<K, V> = HashMap(this) /** * Returns a [LinkedHashMap] containing all elements. * * Example: * ```Kotlin * mapOf(1 to 2, 2 to 3).toLinkedMap() // {1=2, 2=3} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.toLinkedMap(): LinkedHashMap<K, V> = LinkedHashMap(this) /** * Returns a map of all elements sorted by value. * * Example: * ```Kotlin * mapOf(5 to 1, 10 to 10, 1 to 0).sortedByValue() // {1:0, 5:1, 10:10} * mapOf("11" to 1, "1" to 10, "a" to 0).sortedByValue() // {"1":10, "11":1, "a":0} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.sortedByValue(): Map<K, V> = toList().sortedBy { it.second.hashCode() }.toMap() /** * Returns a map of all elements sorted by dec value. * * Example: * ```Kotlin * mapOf(5 to 1, 10 to 10, 1 to 0).sortedByValueDescending() // {10:10, 5:1, 1:0} * mapOf("11" to 1, "1" to 10, "a" to 0).sortedByValueDescending() // {"a":0, "11":1, "1":10} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.sortedByValueDescending(): Map<K, V> = toList().sortedByDescending { it.second.hashCode() }.toMap() /** * Returns a map of all elements sorted by key. * * Example: * ```Kotlin * mapOf(1 to 0, 5 to 1, 10 to 10, 7 to 0).sortedByKey() * // {1:0, 7:0, 5:1, 10:10} * mapOf(1 to "a", 2 to "0", 3 to "11", 4 to "01", 5 to "1").sortedByKey() * // {2:"0", 4:"01", 5:"1", 3:"11", 1:"a"} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.sortedByKey(): Map<K, V> = toList().sortedBy { it.first.hashCode() }.toMap() /** * Returns a map of all elements sorted by dec key. * * Example: * ```Kotlin * mapOf(1 to 0, 5 to 1, 10 to 10, 7 to 0).sortedByKeyDescending() * // {10:10, 5:1, 1:0, 7:0} * mapOf(2 to "0", 3 to "11", 4 to "01", 5 to "1").sortedByKeyDescending() * // {3:"11", 5:"1", 4:"01", 2:"0"} * ``` * @since 1.1.0 */ inline fun <reified K, V> Map<K, V>.sortedByKeyDescending(): Map<K, V> = toList().sortedByDescending { it.first.hashCode() }.toMap()
[ { "class_path": "ghasemdev__affogato__36ec37d/com/parsuomash/affogato/core/ktx/collections/MapKt$sortedByValueDescending$$inlined$sortedByDescending$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class com.parsuomash.affogato.core.ktx.collections.MapKt$sortedByValueDescending$$inlined$so...
suzp1984__Algorithms-Collection__ea67847/kotlin/basics/src/main/kotlin/UnionFind.kt
package io.github.suzp1984.algorithms class UnionFind(size : Int) { val ids : Array<Int> init { ids = Array(size) { it } } private fun find(p : Int) : Int { if (p < 0 || p > ids.size) throw IllegalArgumentException("array out of scope") return ids[p] } fun isConnected(q : Int, p : Int) : Boolean { if (q >= 0 && q < ids.size && p >= 0 && p < ids.size) { return ids[p] == ids[q] } throw IllegalArgumentException("array out of scope") } fun unionElements(p : Int, q : Int) { val pId = find(p) val qId = find(q) if (pId == qId) { return } ids.indices .filter { ids[it] == pId } .forEach { ids[it] = qId } } } class UnionFind2(size : Int) { private val ids : Array<Int> init { ids = Array(size) { it } } private fun find(p : Int) : Int { if (p < 0 || p > ids.size) throw IllegalArgumentException("array out of scope") var i = p while (i != ids[i]) i = ids[i] return i } fun isConnected(q : Int, p : Int) : Boolean { return find(q) == find(p) } fun unionElements(p : Int, q : Int) { val pId = find(p) val qId = find(q) if (pId == qId) { return } ids[pId] = qId } }
[ { "class_path": "suzp1984__Algorithms-Collection__ea67847/io/github/suzp1984/algorithms/UnionFind.class", "javap": "Compiled from \"UnionFind.kt\"\npublic final class io.github.suzp1984.algorithms.UnionFind {\n private final java.lang.Integer[] ids;\n\n public io.github.suzp1984.algorithms.UnionFind(int);...
suzp1984__Algorithms-Collection__ea67847/kotlin/basics/src/main/kotlin/ElementSort.kt
package io.github.suzp1984.algorithms import java.util.* import kotlin.math.min fun <T> Array<T>.swap(i : Int, j : Int) { val t = this[i] this[i] = this[j] this[j] = t } fun <T : Comparable<T>> Array<T>.selectionSort() { indices.forEach { i -> var minIndex = i (i + 1 until size) .asSequence() .filter { this[it] < this[minIndex] } .forEach { minIndex = it } swap(minIndex, i) } } fun <T : Comparable<T>> Array<T>.insertionSort() { (1 until size).forEach { i -> (i downTo 1) .asSequence() .takeWhile { this[it] < this[it - 1] } .forEach { swap(it, it - 1) } } } fun <T : Comparable<T>> Array<T>.improvedInsertionSort() { (1 until size).forEach { i -> val t = this[i] val seqIndex = (i downTo 1) .asSequence() .takeWhile { this[it-1] > t } seqIndex.forEach { this[it] = this[it-1] } val lastIndex = seqIndex.lastOrNull() if (lastIndex != null) this[lastIndex - 1] = t } } fun <T : Comparable<T>> Array<T>.bubbleSort() { (0 until size).forEach { (1 until size - it).forEach { if (this[it] < this[it-1]) { swap(it, it-1) } } } } private fun <T : Comparable<T>> Array<T>.__merge(l : Int, mid : Int, r : Int) { val aux = copyOfRange(l, r + 1) var i = l var j = mid + 1 (l until r + 1).forEach { when { i > mid -> { this[it] = aux[j-l] j++ } j > r -> { this[it] = aux[i-l] i++ } aux[i-l] < aux[j-l] -> { this[it] = aux[i-l] i++ } else -> { this[it] = aux[j-l] j++ } } } } fun <T : Comparable<T>> Array<T>.mergeSort() { fun <T : Comparable<T>> Array<T>.__mergeSort(l : Int, r : Int) { if (l >= r) return val mid = l/2 + r/2 __mergeSort(l, mid) __mergeSort(mid+1, r) __merge(l, mid, r) } __mergeSort(0, size-1) } fun <T : Comparable<T>> Array<T>.bottomUpMergeSort() { var sz = 1 while (sz <= size) { var i = 0 while (i + sz < size) { __merge(i, i + sz - 1, min(i + sz + sz - 1, size - 1)) i += sz + sz } sz += sz } } fun <T : Comparable<T>> Array<T>.quickSort() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortRandom() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortDoublePartition() { fun <T : Comparable<T>> Array<T>.__double_partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var i = l + 1 var j = r while (true) { while (i <= r && this[i] < t) i++ while (j >= l + 1 && this[j] > t) j-- if (i > j) break swap(i, j) i++ j-- } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __double_partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortTriplePartition() { fun <T : Comparable<T>> Array<T>.__triple_partition(l : Int, r : Int) { if (l >= r) { return } swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var lt = l var gt = r + 1; var i = l + 1; while (i < gt) { if (this[i] < t) { swap(i, lt + 1) lt++ i++ } else if (this[i] > t) { swap(i, gt - 1) gt-- } else { i++ } } swap(l, lt) __triple_partition(l, lt - 1) __triple_partition(gt, r) } __triple_partition(0, size - 1) }
[ { "class_path": "suzp1984__Algorithms-Collection__ea67847/io/github/suzp1984/algorithms/ElementSortKt.class", "javap": "Compiled from \"ElementSort.kt\"\npublic final class io.github.suzp1984.algorithms.ElementSortKt {\n public static final <T> void swap(T[], int, int);\n Code:\n 0: aload_0\n ...
jjeda__playground__5d1ee6c/src/oop/algorithm/ProgressionNextNumber.kt
package oop.algorithm class ProgressionNextNumber { fun solution(common: IntArray): Int { return ProgressionHelper(progression = common.toList()).nextInt() } } class ProgressionHelper( private val progression: List<Int> ) { fun nextInt(): Int { val metadata = getMetadata() val nextNumberGenerator = when (metadata.type) { ProgressionType.ARITHMETIC -> ArithmeticalProgressionNextNumberGenerator ProgressionType.GEOMETRIC -> GeometricProgressionNextNumberGenerator } return nextNumberGenerator.generateWith(metadata) } private fun getMetadata(): ProgressionInformation { val (first, second) = progression return if (isArithmetic()) { ProgressionInformation(progression, ProgressionType.ARITHMETIC, second - first) } else { ProgressionInformation(progression, ProgressionType.GEOMETRIC, second / first) } } private fun isArithmetic(): Boolean { val (first, second, third) = progression return second * 2 == first + third } } data class ProgressionInformation( val progression: List<Int>, val type: ProgressionType, val distance: Int, ) enum class ProgressionType { ARITHMETIC, GEOMETRIC } sealed interface ProgressionNextNumberGenerator { fun generateWith(metadata: ProgressionInformation): Int } object ArithmeticalProgressionNextNumberGenerator : ProgressionNextNumberGenerator { override fun generateWith(metadata: ProgressionInformation) = metadata.progression.last() + metadata.distance } object GeometricProgressionNextNumberGenerator : ProgressionNextNumberGenerator { override fun generateWith(metadata: ProgressionInformation) = metadata.progression.last() * metadata.distance }
[ { "class_path": "jjeda__playground__5d1ee6c/oop/algorithm/ProgressionNextNumber.class", "javap": "Compiled from \"ProgressionNextNumber.kt\"\npublic final class oop.algorithm.ProgressionNextNumber {\n public oop.algorithm.ProgressionNextNumber();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
daniilsjb__advent-of-code-2023__46a8376/src/day07/Day07.kt
package day07 import java.io.File fun main() { val data = parse("src/day07/Day07.txt") println("🎄 Day 07 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Hand( val cards: String, val bid: Int, ) private fun String.toHand(): Hand { val (cards, bid) = split(" ") return Hand(cards, bid.toInt()) } private fun parse(path: String): List<Hand> = File(path) .readLines() .map(String::toHand) // From weakest to strongest. private val HAND_TYPES = listOf( listOf(1, 1, 1, 1, 1), listOf(2, 1, 1, 1), listOf(2, 2, 1), listOf(3, 1, 1), listOf(3, 2), listOf(4, 1), listOf(5), ) private val PART1_LETTER_MAPPINGS = mapOf( 'T' to 0x9UL, 'J' to 0xAUL, 'Q' to 0xBUL, 'K' to 0xCUL, 'A' to 0xDUL, ) private val PART2_LETTER_MAPPINGS = mapOf( 'J' to 0x0UL, 'T' to 0x9UL, 'Q' to 0xAUL, 'K' to 0xBUL, 'A' to 0xCUL, ) private fun String.toCode(mappings: Map<Char, ULong>): ULong = fold(0UL) { acc, card -> // If the card doesn't correspond to a letter, it must be a digit. (acc shl 4) or (mappings[card] ?: (card.digitToInt() - 1).toULong()) } private fun String.toFrequencies(): List<Int> = this.groupingBy { it } .eachCount() .values .sortedDescending() private fun solve(data: List<Pair<ULong, Hand>>): Int = data.sortedBy { (code, _) -> code } .mapIndexed { index, (_, hand) -> (index + 1) * hand.bid } .sum() private fun Hand.encoded1(): ULong { val code = cards.toCode(PART1_LETTER_MAPPINGS) val type = HAND_TYPES.indexOf(cards.toFrequencies()) return (type shl 20).toULong() or code } private fun part1(data: List<Hand>): Int = solve(data.map { hand -> hand.encoded1() to hand }) private fun Hand.encoded2(): ULong { val code = cards.toCode(PART2_LETTER_MAPPINGS) val frequencies = cards .filter { it != 'J' } .toFrequencies() .toMutableList() val jokers = cards.count { it == 'J' } if (frequencies.size > 0) { frequencies[0] += jokers } else { frequencies.add(jokers) } val type = HAND_TYPES.indexOf(frequencies) return (type shl 20).toULong() or code } private fun part2(data: List<Hand>): Int = solve(data.map { hand -> hand.encoded2() to hand })
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day07/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class day07.Day07Kt {\n private static final java.util.List<java.util.List<java.lang.Integer>> HAND_TYPES;\n\n private static final java.util.Map<java.lang.Character, kotlin.UL...
daniilsjb__advent-of-code-2023__46a8376/src/day09/Day09.kt
package day09 import java.io.File fun main() { val data = parse("src/day09/Day09.txt") println("🎄 Day 09 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Int>> = File(path) .readLines() .map { it.split(" ").map(String::toInt) } private fun part1(data: List<List<Int>>): Int = data.sumOf { history -> generateSequence(history) { it.zipWithNext { a, b -> b - a } } .takeWhile { !it.all { diff -> diff == 0 } } .sumOf { it.last() } } private fun part2(data: List<List<Int>>): Int = data.sumOf { history -> generateSequence(history) { it.zipWithNext { a, b -> b - a } } .takeWhile { !it.all { diff -> diff == 0 } } .toList() .foldRight(0) { it, acc -> it.first() - acc }.toInt() }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day09/Day09.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day08/Day08.kt
package day08 import java.io.File fun main() { val data = parse("src/day08/Day08.txt") println("🎄 Day 08 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Instructions( val directions: String, val network: Map<String, Pair<String, String>>, ) private fun parse(path: String): Instructions { val lines = File(path).readLines() val directions = lines.first() val network = lines.drop(2) .mapNotNull { """(\w+) = \((\w+), (\w+)\)""".toRegex().find(it)?.destructured } .associate { (key, left, right) -> key to (left to right) } return Instructions(directions, network) } private fun lcm(a: Long, b: Long): Long { var n1 = a var n2 = b while (n2 != 0L) { n1 = n2.also { n2 = n1 % n2 } } return (a * b) / n1 } private fun Instructions.generateNodeSequence(start: String): Sequence<Pair<Int, String>> = generateSequence(seed = 0 to start) { (index, node) -> val nextDirection = directions[index % directions.length] val nextNode = if (nextDirection == 'L') { network.getValue(node).let { (next, _) -> next } } else { network.getValue(node).let { (_, next) -> next } } (index + 1) to nextNode } private fun part1(data: Instructions): Long = data.generateNodeSequence(start = "AAA") .dropWhile { (_, node) -> node != "ZZZ" } .first().let { (index, _) -> index.toLong() } private fun Instructions.periodFrom(start: String): Long { val path = mutableMapOf<Pair<String, Int>, Long>() return generateNodeSequence(start) .dropWhile { (index, node) -> val key = node to index % directions.length if (key !in path) { true.also { path[key] = index.toLong() } } else { false } } .first().let { (index, node) -> val directionIndex = index % directions.length val startingIndex = path.getValue(node to directionIndex) index.toLong() - startingIndex } } private fun part2(data: Instructions): Long = data.network.keys .filter { it.last() == 'A' } .map(data::periodFrom) .reduce(::lcm)
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day08/Day08.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day06/Day06.kt
package day06 import java.io.File import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt fun main() { val data = parse("src/day06/Day06.txt") println("🎄 Day 06 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Race( val time: Long, val distance: Long, ) private fun parse(path: String): Pair<List<String>, List<String>> = File(path) .readLines() .map { it.split("\\s+".toRegex()).drop(1).map(String::trim) } .let { (ts, ds) -> ts to ds } private fun solve(data: List<Race>): Long = data.fold(1) { acc, (t, d) -> val x1 = floor((t - sqrt(t * t - 4.0 * d)) / 2.0 + 1.0).toInt() val x2 = ceil((t + sqrt(t * t - 4.0 * d)) / 2.0 - 1.0).toInt() acc * (x2 - x1 + 1) } private fun part1(data: Pair<List<String>, List<String>>): Long = data.let { (ts, ds) -> ts.map(String::toLong) to ds.map(String::toLong) } .let { (ts, ds) -> ts.zip(ds) { t, d -> Race(t, d) } } .let { solve(it) } private fun part2(data: Pair<List<String>, List<String>>): Long = data.let { (ts, ds) -> ts.joinToString("") to ds.joinToString("") } .let { (ts, ds) -> Race(ts.toLong(), ds.toLong()) } .let { solve(listOf(it)) }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day06/Day06Kt.class", "javap": "Compiled from \"Day06.kt\"\npublic final class day06.Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day06/Day06.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day01/Day01.kt
package day01 import java.io.File fun main() { val data = parse("src/day01/Day01.txt") println("🎄 Day 01 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<String> = File(path).readLines() private fun part1(data: List<String>): Int = data.map { it.mapNotNull(Char::digitToIntOrNull) } .sumOf { it.first() * 10 + it.last() } private val spelledDigits = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) private fun String.parseDigits(): List<Int> { val digits = mutableListOf<Int>() scan@ for ((i, c) in this.withIndex()) { // Ordinary digits may be parsed directly. if (c.isDigit()) { digits.add(c.digitToInt()) continue@scan } // Spelled out digits must be matched individually. for ((spelling, value) in spelledDigits) { val endIndex = i + spelling.length if (this.length >= endIndex) { if (this.substring(i, endIndex) == spelling) { digits.add(value) continue@scan } } } } return digits } private fun part2(data: List<String>): Int = data.map { it.parseDigits() } .sumOf { it.first() * 10 + it.last() }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day01/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class day01.Day01Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> spelledDigits;\n\n public static final void main();\n Code:\n 0: ldc ...
daniilsjb__advent-of-code-2023__46a8376/src/day23/Day23.kt
package day23 import java.io.File import kotlin.math.max fun main() { val data = parse("src/day23/Day23.txt") println("🎄 Day 23 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private val directions = mapOf( '.' to listOf((1 to 0), (-1 to 0), (0 to 1), (0 to -1)), '>' to listOf((1 to 0)), '<' to listOf((-1 to 0)), 'v' to listOf((0 to 1)), '^' to listOf((0 to -1)), ) private data class Vertex( val x: Int, val y: Int, ) private fun dfs( graph: Map<Vertex,Map<Vertex, Int>>, source: Vertex, target: Vertex, visited: Set<Vertex> = setOf(), ): Int { if (source == target) { return 0 } var distance = Int.MIN_VALUE for ((adjacent, weight) in graph.getValue(source)) { if (adjacent !in visited) { distance = max(distance, weight + dfs(graph, adjacent, target, visited + adjacent)) } } return distance } private fun solve(grid: List<List<Char>>): Int { val sz = grid.size val source = Vertex(1, 0) val target = Vertex(sz - 2, sz - 1) val vertices = mutableListOf(source, target) for ((y, row) in grid.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { continue } val neighbors = listOfNotNull( grid.getOrNull(y)?.getOrNull(x - 1), grid.getOrNull(y)?.getOrNull(x + 1), grid.getOrNull(y - 1)?.getOrNull(x), grid.getOrNull(y + 1)?.getOrNull(x), ) if (neighbors.count { it == '#' } <= 1) { vertices += Vertex(x, y) } } } val graph = vertices.associateWith { mutableMapOf<Vertex, Int>() } for (origin in vertices) { val options = ArrayDeque<Pair<Vertex, Int>>().apply { add(origin to 0) } val visited = mutableSetOf(origin) while (options.isNotEmpty()) { val (vertex, n) = options.removeFirst() val (vx, vy) = vertex if (n != 0 && vertex in vertices) { graph.getValue(origin)[vertex] = n continue } for ((dx, dy) in directions.getValue(grid[vy][vx])) { val nx = vx + dx val ny = vy + dy if (nx !in 0..<sz || ny !in 0..<sz) { continue } if (grid[ny][nx] == '#') { continue } if (Vertex(nx, ny) in visited) { continue } options += Vertex(nx, ny) to (n + 1) visited += Vertex(nx, ny) } } } return dfs(graph, source, target) } private fun part1(data: List<List<Char>>): Int = solve(data) private fun part2(data: List<List<Char>>): Int = solve(data.map { it.map { c -> if (c in "<^v>") '.' else c } })
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day23/Day23Kt.class", "javap": "Compiled from \"Day23.kt\"\npublic final class day23.Day23Kt {\n private static final java.util.Map<java.lang.Character, java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>>> directions;\n\n public static...
daniilsjb__advent-of-code-2023__46a8376/src/day24/Day24.kt
package day24 import java.io.File import kotlin.math.max fun main() { val data = parse("src/day24/Day24.txt") println("🎄 Day 24 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") // For Part 2, see the Python implementation. } private data class Vec3( val x: Long, val y: Long, val z: Long, ) private data class Hailstone( val position: Vec3, val velocity: Vec3, ) private fun String.toHailstone(): Hailstone { val (lhs, rhs) = this.split(" @ ") val position = lhs.split(", ") .map(String::trim) .map(String::toLong) .let { (x, y, z) -> Vec3(x, y, z) } val velocity = rhs.split(", ") .map(String::trim) .map(String::toLong) .let { (x, y, z) -> Vec3(x, y, z) } return Hailstone(position, velocity) } private fun parse(path: String): List<Hailstone> = File(path) .readLines() .map(String::toHailstone) private fun intersect(a: Hailstone, b: Hailstone, min: Long, max: Long): Boolean { val dx = (b.position.x - a.position.x).toDouble() val dy = (b.position.y - a.position.y).toDouble() val det = (b.velocity.x * a.velocity.y - b.velocity.y * a.velocity.x).toDouble() val u = (dy * b.velocity.x - dx * b.velocity.y) / det val v = (dy * a.velocity.x - dx * a.velocity.y) / det if (u < 0 || v < 0) { return false } val x = a.position.x + a.velocity.x * u val y = a.position.y + a.velocity.y * u if (x.toLong() !in min..max) { return false } if (y.toLong() !in min..max) { return false } return true } private fun part1(data: List<Hailstone>): Int { val min = 200000000000000L val max = 400000000000000L var counter = 0 for ((i, a) in data.withIndex()) { for ((j, b) in data.withIndex()) { if (j > i && intersect(a, b, min, max)) { counter += 1 } } } return counter }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day24/Day24.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day12/Day12.kt
package day12 import java.io.File fun main() { val data = parse("src/day12/Day12.txt") println("🎄 Day 12 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Row( val springs: String, val numbers: List<Int>, ) private fun String.toRow(): Row { val (springs, numbers) = this.split(" ") return Row(springs, numbers.split(",").map(String::toInt)) } private fun parse(path: String): List<Row> = File(path) .readLines() .map(String::toRow) private typealias Cache = MutableMap<Pair<String, List<Int>>, Long> private fun solve(springs: String, numbers: List<Int>, cache: Cache = mutableMapOf()): Long { if (cache.containsKey(springs to numbers)) { return cache.getValue(springs to numbers) } if (springs.isEmpty()) { return if (numbers.isEmpty()) 1L else 0L } if (numbers.isEmpty()) { return if (springs.contains('#')) 0L else 1L } var count = 0L if (springs.first() in ".?") { count += solve(springs.substring(1), numbers, cache) } if (springs.first() in "#?") { val n = numbers.first() if (springs.length > n) { val group = springs.substring(0, n) if (!group.contains('.') && springs[n] != '#') { count += solve(springs.substring(n + 1), numbers.drop(1), cache) } } if (springs.length == n) { if (!springs.contains('.')) { count += solve("", numbers.drop(1), cache) } } } cache[springs to numbers] = count return count } private fun part1(data: List<Row>): Long = data.sumOf { (springs, numbers) -> solve(springs, numbers) } private fun part2(data: List<Row>): Long = data.sumOf { (springs, numbers) -> solve( generateSequence { springs }.take(5).toList().joinToString("?"), generateSequence { numbers }.take(5).toList().flatten()) }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day12/Day12.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day15/Day15.kt
package day15 import java.io.File fun main() { val data = parse("src/day15/Day15.txt") println("🎄 Day 15 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<String> = File(path) .readText() .split(",") private fun String.hash(): Int = fold(0) { acc, it -> (acc + it.code) * 17 and 0xFF } private fun part1(data: List<String>): Int = data.sumOf(String::hash) private data class Lens( val label: String, val focalLength: Int, ) private fun part2(data: List<String>): Int { val boxes = Array(256) { mutableListOf<Lens>() } for (step in data) { val (label) = step.split('=', '-') val location = label.hash() if (step.contains('=')) { val focalLength = step.last().digitToInt() val index = boxes[location].indexOfFirst { it.label == label } if (index >= 0) { boxes[location][index] = Lens(label, focalLength) } else { boxes[location] += Lens(label, focalLength) } } else { boxes[location].removeIf { it.label == label } } } return boxes.withIndex().sumOf { (boxNumber, box) -> box.withIndex().sumOf { (lensNumber, lens) -> (boxNumber + 1) * (lensNumber + 1) * lens.focalLength } } }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day15/Day15.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day14/Day14.kt
package day14 import java.io.File fun main() { val data = parse("src/day14/Day14.txt") println("🎄 Day 14 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun part1(data: List<List<Char>>): Int { val h = data.size val w = data[0].size var counter = 0 for (col in 0..<w) { var top = 0 for (row in 0..<h) { when (data[row][col]) { 'O' -> counter += h - top++ '#' -> top = row + 1 } } } return counter } private fun part2(data: List<List<Char>>): Int { val h = data.size val w = data[0].size val cycles = mutableMapOf<String, Int>() val loads = mutableListOf<Int>() val grid = data.map { it.toMutableList() } for (i in 1..1_000_000_000) { // North for (col in 0..<w) { var dst = 0 for (row in 0..<h) { when (grid[row][col]) { '#' -> dst = row + 1 'O' -> { grid[row][col] = '.' grid[dst][col] = 'O' dst += 1 } } } } // West for (row in 0..<h) { var dst = 0 for (col in 0..<w) { when (grid[row][col]) { '#' -> dst = col + 1 'O' -> { grid[row][col] = '.' grid[row][dst] = 'O' dst += 1 } } } } // South for (col in w - 1 downTo 0) { var dst = h - 1 for (row in h - 1 downTo 0) { when (grid[row][col]) { '#' -> dst = row - 1 'O' -> { grid[row][col] = '.' grid[dst][col] = 'O' dst -= 1 } } } } // East for (row in h - 1 downTo 0) { var dst = w - 1 for (col in w - 1 downTo 0) { when (grid[row][col]) { '#' -> dst = col - 1 'O' -> { grid[row][col] = '.' grid[row][dst] = 'O' dst -= 1 } } } } val cycle = grid.flatten().toString() cycles[cycle]?.let { start -> val remainder = (1_000_000_000 - start) % (i - start) val loop = cycles.values.filter { it >= start } return loads[loop[remainder] - 1] } cycles[cycle] = i loads += grid.withIndex().sumOf { (y, row) -> row.count { it == 'O' } * (h - y) } } error("Could not detect a cycle.") }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day14/Day14.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day13/Day13.kt
package day13 import java.io.File import kotlin.math.min fun main() { val data = parse("src/day13/Day13.txt") println("🎄 Day 13 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private typealias Pattern = List<List<Char>> private fun parse(path: String): List<Pattern> = File(path) .readText() .split("\n\n", "\r\n\r\n") .map { it.lines().map(String::toList) } private fun Pattern.row(index: Int): List<Char> = this[index] private fun Pattern.col(index: Int): List<Char> = this.indices.map { this[it][index] } private fun verticalDifference(pattern: Pattern, y: Int): Int { val distance = min(y, pattern.size - y) return (0..<distance).sumOf { dy -> val lineTop = pattern.row(y - dy - 1) val lineBottom = pattern.row(y + dy) lineTop.zip(lineBottom).count { (a, b) -> a != b } } } private fun horizontalDifference(pattern: Pattern, x: Int): Int { val distance = min(x, pattern[0].size - x) return (0..<distance).sumOf { dx -> val lineLeft = pattern.col(x - dx - 1) val lineRight = pattern.col(x + dx) lineLeft.zip(lineRight).count { (a, b) -> a != b } } } private fun solve(data: List<Pattern>, tolerance: Int): Int { return data.sumOf { pattern -> val height = pattern.size for (y in 1..<height) { if (verticalDifference(pattern, y) == tolerance) { return@sumOf 100 * y } } val width = pattern[0].size for (x in 1..<width) { if (horizontalDifference(pattern, x) == tolerance) { return@sumOf x } } error("Reflection line could not be found.") } } private fun part1(data: List<Pattern>): Int = solve(data, tolerance = 0) private fun part2(data: List<Pattern>): Int = solve(data, tolerance = 1)
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day13/Day13.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day22/Day22.kt
package day22 import java.io.File import kotlin.math.max fun main() { val data = parse("src/day22/Day22.txt") val (supports, standsOn) = simulate(data) println("🎄 Day 22 🎄") println() println("[Part 1]") println("Answer: ${part1(data.size, supports, standsOn)}") println() println("[Part 2]") println("Answer: ${part2(data.size, supports, standsOn)}") } private data class Brick( val x0: Int, val x1: Int, val y0: Int, val y1: Int, val z0: Int, val z1: Int, ) private fun String.toBrick(): Brick { val (lhs, rhs) = this.split('~') val (x0, y0, z0) = lhs.split(',') val (x1, y1, z1) = rhs.split(',') return Brick( x0 = x0.toInt(), x1 = x1.toInt(), y0 = y0.toInt(), y1 = y1.toInt(), z0 = z0.toInt(), z1 = z1.toInt(), ) } private fun parse(path: String): List<Brick> = File(path) .readLines() .map(String::toBrick) .sortedBy { it.z0 } private fun overlap(a: Brick, b: Brick): Boolean = (a.x1 >= b.x0 && b.x1 >= a.x0) && (a.y1 >= b.y0 && b.y1 >= a.y0) private fun simulate(data: List<Brick>): Pair<List<Set<Int>>, List<Set<Int>>> { val bricks = data.toMutableList() for ((i, upper) in bricks.withIndex()) { var z = 1 for (lower in bricks.subList(0, i)) { if (overlap(upper, lower)) { z = max(z, lower.z1 + 1) } } bricks[i] = upper.copy( z0 = z, z1 = z + (upper.z1 - upper.z0), ) } bricks.sortBy { it.z0 } val supports = bricks.map { mutableSetOf<Int>() } val standsOn = bricks.map { mutableSetOf<Int>() } for ((i, upper) in bricks.withIndex()) { for ((j, lower) in bricks.subList(0, i).withIndex()) { if (upper.z0 == lower.z1 + 1) { if (overlap(upper, lower)) { supports[j] += i standsOn[i] += j } } } } return Pair(supports, standsOn) } private fun part1(n: Int, supports: List<Set<Int>>, standsOn: List<Set<Int>>): Int = (0..<n).count { i -> supports[i].all { j -> standsOn[j].size > 1 } } private fun part2(n: Int, supports: List<Set<Int>>, standsOn: List<Set<Int>>): Int { var count = 0 for (i in 0..<n) { val queue = ArrayDeque<Int>() .apply { addAll(supports[i].filter { j -> standsOn[j].size == 1 }) } val falling = mutableSetOf(i) falling += queue while (queue.isNotEmpty()) { val j = queue.removeFirst() for (k in supports[j]) { if (k !in falling && falling.containsAll(standsOn[k])) { queue += k falling += k } } } count += falling.size - 1 } return count }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day22/Day22Kt.class", "javap": "Compiled from \"Day22.kt\"\npublic final class day22.Day22Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day22/Day22.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day04/Day04.kt
package day04 import java.io.File import kotlin.math.pow fun main() { val data = parse("src/day04/Day04.txt") println("🎄 Day 04 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun String.toMatches(): Int { val (_, winningPart, playerPart) = split(": ", " | ") val winningNumbers = winningPart .split(" ") .mapNotNull(String::toIntOrNull) .toSet() val playerNumbers = playerPart .split(" ") .mapNotNull(String::toIntOrNull) return playerNumbers.count { it in winningNumbers } } private fun parse(path: String): List<Int> = File(path) .readLines() .map(String::toMatches) private fun part1(data: List<Int>): Int = data.sumOf { 2.0.pow(it).toInt() / 2 } private fun part2(data: List<Int>): Int { val pile = MutableList(data.size) { 1 } for ((i, matches) in data.withIndex()) { for (offset in 1..matches) { pile[i + offset] += pile[i] } } return pile.sum() }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day04/Day04.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day03/Day03.kt
package day03 import java.io.File fun main() { val data = parse("src/day03/Day03.txt") println("🎄 Day 03 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Part( val rx: IntRange, val ry: IntRange, val value: Int, ) private data class Symbol( val x: Int, val y: Int, val value: Char, ) private data class Schematic( val parts: List<Part>, val symbols: List<Symbol>, ) private val PATTERN = """(\d+)|[^.]""".toRegex() private fun parse(path: String): Schematic { val parts = mutableListOf<Part>() val symbols = mutableListOf<Symbol>() val data = File(path).readLines() for ((y, line) in data.withIndex()) { val (matchedParts, matchedSymbols) = PATTERN.findAll(line) .partition { it.value[0].isDigit() } parts.addAll(matchedParts.map { val a = it.range.first val b = it.range.last val rx = (a - 1)..(b + 1) val ry = (y - 1)..(y + 1) Part(rx, ry, it.value.toInt()) }) symbols.addAll(matchedSymbols.map { Symbol(x = it.range.first, y, it.value[0]) }) } return Schematic(parts, symbols) } private fun part1(data: Schematic): Int { val (parts, symbols) = data return parts.sumOf { (rx, ry, value) -> if (symbols.any { (sx, sy) -> (sx in rx) && (sy in ry) }) { value } else { 0 } } } private fun part2(data: Schematic): Int { val (parts, symbols) = data val gears = symbols.filter { it.value == '*' } return gears.sumOf { (sx, sy) -> val adjacentNumbers = parts.mapNotNull { (rx, ry, value) -> if ((sx in rx) && (sy in ry)) value else null } if (adjacentNumbers.count() == 2) { adjacentNumbers.reduce(Int::times) } else { 0 } } }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day03/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n private static final kotlin.text.Regex PATTERN;\n\n public static final void main();\n Code:\n 0: ldc #8 // String s...
daniilsjb__advent-of-code-2023__46a8376/src/day02/Day02.kt
package day02 import java.io.File fun main() { val data = parse("src/day02/Day02.txt") println("🎄 Day 02 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class CubeSet( val redCount: Int, val blueCount: Int, val greenCount: Int, ) private data class Game( val id: Int, val sets: List<CubeSet>, ) private val PATTERN = """(\d+) (red|blue|green)""".toRegex() private fun String.toCubeSet(): CubeSet { val colors = PATTERN.findAll(this) .map { it.destructured } .associate { (count, color) -> color to count.toInt() } return CubeSet( colors.getOrDefault("red", 0), colors.getOrDefault("blue", 0), colors.getOrDefault("green", 0), ) } private fun String.toGame(): Game { val parts = this .split(";", ":") .map(String::trim) val id = parts.first() .filter(Char::isDigit) .toInt() val sets = parts .drop(1) .map(String::toCubeSet) return Game(id, sets) } private fun parse(path: String): List<Game> = File(path) .readLines() .map(String::toGame) private fun part1(data: List<Game>): Int = data.asSequence() .filter { (_, sets) -> sets.all { it.redCount <= 12 } } .filter { (_, sets) -> sets.all { it.blueCount <= 14 } } .filter { (_, sets) -> sets.all { it.greenCount <= 13 } } .sumOf(Game::id) private fun part2(data: List<Game>): Int = data.sumOf { (_, sets) -> sets.maxOf(CubeSet::redCount) * sets.maxOf(CubeSet::blueCount) * sets.maxOf(CubeSet::greenCount) }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day02/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n private static final kotlin.text.Regex PATTERN;\n\n public static final void main();\n Code:\n 0: ldc #8 // String s...
daniilsjb__advent-of-code-2023__46a8376/src/day05/Day05.kt
package day05 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val data = parse("src/day05/Day05.txt") println("🎄 Day 05 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private data class Range( val start: Long, val end: Long, ) private data class Mapping( val src: Range, val dst: Range, ) private data class Almanac( val seeds: List<Long>, val transforms: List<List<Mapping>>, ) private fun String.toMapping(): Mapping = this.split(" ") .map(String::toLong) .let { (dst, src, length) -> Mapping( Range(src, src + length - 1), Range(dst, dst + length - 1), ) } private fun parse(path: String): Almanac { val sections = File(path) .readText() .split("\n\n", "\r\n\r\n") val seeds = sections.first() .split(": ", " ") .mapNotNull(String::toLongOrNull) val maps = sections.asSequence() .drop(1) .map { it.split("\n", "\r\n") } .map { it.drop(1) } .map { it.map(String::toMapping) } .toList() return Almanac(seeds, maps) } private fun intersection(a: Range, b: Range): Range? = if (a.end < b.start || b.end < a.start) { null } else { Range(max(a.start, b.start), min(a.end, b.end)) } private fun part1(data: Almanac): Long { val (seeds, transforms) = data val values = seeds.toMutableList() for (mapping in transforms) { transforming@ for ((i, value) in values.withIndex()) { for ((src, dst) in mapping) { if (value in src.start..src.end) { values[i] = dst.start + (value - src.start) continue@transforming } } } } return values.min() } private fun part2(data: Almanac): Long { val (seeds, transforms) = data val ranges = seeds .chunked(2) .map { (start, length) -> Range(start, start + length - 1) } .toMutableList() for (mappings in transforms) { // List of ranges that already had a mapping applied to them. These are // stored separately because we don't want to transform the same range // multiple times within the same transformation "round". val transformed = mutableListOf<Range>() for ((src, dst) in mappings) { // We may need to break each range into multiple sub-ranges in case // the mapping only applies to its portion. This is the "unmapped" // parts of the split ranges to be re-used later. val remainders = mutableListOf<Range>() for (range in ranges) { val intersection = intersection(range, src) if (intersection == null) { remainders.add(range) continue } val offset = intersection.start - src.start val length = intersection.end - intersection.start transformed.add(Range( dst.start + offset, dst.start + offset + length, )) if (range.start < src.start) { remainders.add(Range(range.start, src.start - 1)) } if (range.end > src.end) { remainders.add(Range(src.end + 1, range.end)) } } ranges.clear() ranges.addAll(remainders) } ranges.addAll(transformed) } return ranges.minOf(Range::start) }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day05/Day05.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day18/Day18.kt
package day18 import java.io.File fun main() { val data = parse("src/day18/Day18.txt") println("🎄 Day 18 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } enum class Direction { U, D, L, R } private data class Instruction( val direction: Direction, val distance: Int, ) private fun parse(path: String): List<String> = File(path).readLines() private fun solve(data: List<Instruction>): Long { val x = mutableListOf<Long>() val y = mutableListOf<Long>() var px = 0L var py = 0L for ((direction, meters) in data) { when (direction) { Direction.D -> py += meters Direction.U -> py -= meters Direction.L -> px -= meters Direction.R -> px += meters } x += px y += py } val area = (x.indices).sumOf { i -> val prev = if (i - 1 < 0) x.lastIndex else i - 1 val next = if (i + 1 > x.lastIndex) 0 else i + 1 x[i] * (y[next] - y[prev]) } / 2 val exterior = data.sumOf { it.distance } val interior = (area - (exterior / 2) + 1) return interior + exterior } private fun part1(data: List<String>): Long = solve(data.map { line -> val (directionPart, distancePart, _) = line.split(" ") val direction = when (directionPart) { "R" -> Direction.R "D" -> Direction.D "L" -> Direction.L "U" -> Direction.U else -> error("Invalid direction!") } val distance = distancePart.toInt() Instruction(direction, distance) }) private fun part2(data: List<String>): Long = solve(data.map { line -> val (_, _, colorPart) = line.split(" ") val color = colorPart.trim('(', ')', '#') val distance = color .substring(0, 5) .toInt(radix = 16) val direction = when (color.last()) { '0' -> Direction.R '1' -> Direction.D '2' -> Direction.L '3' -> Direction.U else -> error("Invalid direction!") } Instruction(direction, distance) })
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day18/Day18Kt$WhenMappings.class", "javap": "Compiled from \"Day18.kt\"\npublic final class day18.Day18Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Meth...
daniilsjb__advent-of-code-2023__46a8376/src/day16/Day16.kt
package day16 import java.io.File fun main() { val data = parse("src/day16/Day16.txt") println("🎄 Day 16 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private data class Vec2( val x: Int, val y: Int, ) private data class Beam( val position: Vec2, val direction: Vec2, ) private fun Beam.advance(): Beam = copy(position = Vec2(position.x + direction.x, position.y + direction.y)) private val List<List<Char>>.w get() = this[0].size private val List<List<Char>>.h get() = this.size private fun List<List<Char>>.contains(beam: Beam): Boolean = beam.position.let { (x, y) -> x >= 0 && y >= 0 && x < w && y < h } private fun List<List<Char>>.at(beam: Beam): Char = beam.position.let { (x, y) -> this[y][x] } private fun solve(grid: List<List<Char>>, initialBeam: Beam): Int { val pool = ArrayDeque<Beam>().apply { add(initialBeam) } val cache = mutableSetOf<Beam>() val trace = mutableSetOf<Vec2>() while (pool.isNotEmpty()) { var beam = pool.removeFirst() while (grid.contains(beam) && beam !in cache) { cache += beam trace += beam.position when (grid.at(beam)) { '-' -> if (beam.direction.y != 0) { pool += beam.copy(direction = Vec2(+1, 0)) pool += beam.copy(direction = Vec2(-1, 0)) break } '|' -> if (beam.direction.x != 0) { pool += beam.copy(direction = Vec2(0, +1)) pool += beam.copy(direction = Vec2(0, -1)) break } '/' -> { val (dx, dy) = beam.direction beam = if (dx == 0) { beam.copy(direction = Vec2(-dy, 0)) } else { beam.copy(direction = Vec2(0, -dx)) } } '\\' -> { val (dx, dy) = beam.direction beam = if (dx == 0) { beam.copy(direction = Vec2(dy, 0)) } else { beam.copy(direction = Vec2(0, dx)) } } } beam = beam.advance() } } return trace.size } private fun part1(data: List<List<Char>>): Int { return solve(data, initialBeam = Beam(Vec2(0, 0), Vec2(1, 0))) } private fun part2(data: List<List<Char>>): Int { val (x0, x1) = (0 to data.w - 1) val (y0, y1) = (0 to data.h - 1) return maxOf( (x0..x1).maxOf { x -> solve(data, initialBeam = Beam(Vec2(x, y0), Vec2(0, +1))) }, (x0..x1).maxOf { x -> solve(data, initialBeam = Beam(Vec2(x, y1), Vec2(0, -1))) }, (y0..y1).maxOf { y -> solve(data, initialBeam = Beam(Vec2(x0, y), Vec2(+1, 0))) }, (y0..y1).maxOf { y -> solve(data, initialBeam = Beam(Vec2(x1, y), Vec2(-1, 0))) }, ) }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day16/Day16.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day11/Day11.kt
package day11 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val data = parse("src/day11/Day11.txt") println("🎄 Day 11 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun solve(data: List<List<Char>>, scale: Long): Long { val emptyRows = data.indices .filter { row -> data[row].all { it == '.' } } val emptyCols = data[0].indices .filter { col -> data.all { it[col] == '.' } } val galaxies = mutableListOf<Pair<Int, Int>>() for ((y, row) in data.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { galaxies.add(x to y) } } } var accumulator = 0L for (a in 0..galaxies.lastIndex) { for (b in (a + 1)..galaxies.lastIndex) { val (ax, ay) = galaxies[a] val (bx, by) = galaxies[b] val x0 = min(ax, bx) val x1 = max(ax, bx) val y0 = min(ay, by) val y1 = max(ay, by) val nx = emptyCols.count { it in x0..x1 } val ny = emptyRows.count { it in y0..y1 } accumulator += (x1 - x0) + nx * (scale - 1) accumulator += (y1 - y0) + ny * (scale - 1) } } return accumulator } private fun part1(data: List<List<Char>>): Long = solve(data, scale = 2L) private fun part2(data: List<List<Char>>): Long = solve(data, scale = 1_000_000L)
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day11/Day11.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day17/Day17.kt
package day17 import java.io.File import java.util.PriorityQueue fun main() { val data = parse("src/day17/Day17.txt") println("🎄 Day 17 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private typealias Graph = List<List<Int>> private fun parse(path: String): Graph = File(path) .readLines() .map { it.map(Char::digitToInt) } private data class Vec2( val x: Int, val y: Int, ) private typealias Vertex = Vec2 private data class Endpoint( val vertex: Vertex, val streakDirection: Vec2, val streakLength: Int, ) private data class Path( val endpoint: Endpoint, val distance: Int, ) : Comparable<Path> { override fun compareTo(other: Path): Int = distance.compareTo(other.distance) } private val Graph.h get() = this.size private val Graph.w get() = this[0].size private fun Graph.neighborsOf(vertex: Vertex): List<Vertex> = listOfNotNull( if (vertex.x - 1 >= 0) Vertex(vertex.x - 1, vertex.y) else null, if (vertex.x + 1 < w) Vertex(vertex.x + 1, vertex.y) else null, if (vertex.y - 1 >= 0) Vertex(vertex.x, vertex.y - 1) else null, if (vertex.y + 1 < h) Vertex(vertex.x, vertex.y + 1) else null, ) private fun part1(graph: Graph): Int { val visited = mutableSetOf<Endpoint>() val (xs, xt) = (0 to graph.w - 1) val (ys, yt) = (0 to graph.h - 1) val source = Vertex(xs, ys) val target = Vertex(xt, yt) val sourceEndpoint = Endpoint(source, Vec2(0, 0), streakLength = 0) val queue = PriorityQueue<Path>() .apply { add(Path(sourceEndpoint, distance = 0)) } while (queue.isNotEmpty()) { val (endpoint, distanceToVertex) = queue.poll() if (endpoint in visited) { continue } else { visited += endpoint } val (vertex, streakDirection, streakLength) = endpoint if (vertex == target) { return distanceToVertex } for (neighbor in graph.neighborsOf(vertex)) { val dx = neighbor.x - vertex.x val dy = neighbor.y - vertex.y val nextDirection = Vec2(dx, dy) if (nextDirection.x == -streakDirection.x && nextDirection.y == -streakDirection.y) { continue } val nextLength = if (nextDirection == streakDirection) streakLength + 1 else 1 if (nextLength == 4) { continue } val endpointToNeighbor = Endpoint(neighbor, nextDirection, nextLength) val distanceToNeighbor = distanceToVertex + graph[neighbor.y][neighbor.x] queue += Path(endpointToNeighbor, distanceToNeighbor) } } error("Could not find any path from source to target.") } private fun part2(graph: Graph): Int { val visited = mutableSetOf<Endpoint>() val (xs, xt) = (0 to graph.w - 1) val (ys, yt) = (0 to graph.h - 1) val source = Vertex(xs, ys) val target = Vertex(xt, yt) val sourceEndpoint = Endpoint(source, Vec2(0, 0), streakLength = 0) val queue = PriorityQueue<Path>() .apply { add(Path(sourceEndpoint, distance = 0)) } while (queue.isNotEmpty()) { val (endpoint, distanceToVertex) = queue.poll() if (endpoint in visited) { continue } else { visited += endpoint } val (vertex, streakDirection, streakLength) = endpoint if (vertex == target && streakLength >= 4) { return distanceToVertex } for (neighbor in graph.neighborsOf(vertex)) { val dx = neighbor.x - vertex.x val dy = neighbor.y - vertex.y val nextDirection = Vec2(dx, dy) if (nextDirection.x == -streakDirection.x && nextDirection.y == -streakDirection.y) { continue } val nextLength = if (nextDirection == streakDirection) streakLength + 1 else 1 if (nextLength > 10) { continue } if (streakDirection != Vec2(0, 0) && nextDirection != streakDirection && streakLength < 4) { continue } val endpointToNeighbor = Endpoint(neighbor, nextDirection, nextLength) val distanceToNeighbor = distanceToVertex + graph[neighbor.y][neighbor.x] queue += Path(endpointToNeighbor, distanceToNeighbor) } } error("Could not find any path from source to target.") }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day17/Day17Kt.class", "javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day17/Day17.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day21/Day21.kt
package day21 import java.io.File fun main() { val data = parse("src/day21/Day21.txt") println("🎄 Day 21 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<List<Char>> = File(path) .readLines() .map(String::toList) private fun solve(data: List<List<Char>>, start: Pair<Int, Int>, n: Int): Long { var plots = setOf(start) repeat(n) { val next = mutableSetOf<Pair<Int, Int>>() for ((px, py) in plots) { for ((dx, dy) in listOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1))) { val nx = px + dx val ny = py + dy if (nx in data.indices && ny in data.indices) { if (data[ny][nx] != '#') { next += nx to ny } } } } plots = next } return plots.size.toLong() } private fun part1(data: List<List<Char>>): Long { for ((y, row) in data.withIndex()) { for ((x, col) in row.withIndex()) { if (col == 'S') { return solve(data, Pair(x, y), 64) } } } error("Starting point not found.") } private fun part2(data: List<List<Char>>): Long { val size = data.size val steps = 26_501_365 val sx = size / 2 val sy = size / 2 val n = (steps / size - 1).toLong() val evenGrids = n * n val evenCount = evenGrids * solve(data, start = Pair(sx, sy), n = 2 * size + 1) val oddGrids = (n + 1) * (n + 1) val oddCount = oddGrids * solve(data, start = Pair(sx, sy), n = 2 * size) val corners = solve(data, start = Pair(sx, size - 1), n = size - 1) + // Top solve(data, start = Pair(size - 1, sy), n = size - 1) + // Left solve(data, start = Pair(sx, 0), n = size - 1) + // Bottom solve(data, start = Pair(0, sy), n = size - 1) // Right val smallSections = solve(data, start = Pair(size - 1, size - 1), n = size / 2 - 1) + // Top-left solve(data, start = Pair(size - 1, 0), n = size / 2 - 1) + // Bottom-left solve(data, start = Pair(0, 0), n = size / 2 - 1) + // Bottom-right solve(data, start = Pair(0, size - 1), n = size / 2 - 1) // Top-right val largeSections = solve(data, start = Pair(size - 1, size - 1), n = size * 3 / 2 - 1) + // Top-left solve(data, start = Pair(size - 1, 0), n = size * 3 / 2 - 1) + // Bottom-left solve(data, start = Pair(0, 0), n = size * 3 / 2 - 1) + // Bottom-right solve(data, start = Pair(0, size - 1), n = size * 3 / 2 - 1) // Top-right return evenCount + oddCount + corners + (n + 1) * smallSections + n * largeSections }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/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/day21/Day21.txt\n 2: invokestatic #12 ...
daniilsjb__advent-of-code-2023__46a8376/src/day19/Day19.kt
package day19 import java.io.File fun main() { val (workflows, parts) = parse("src/day19/Day19.txt") println("🎄 Day 19 🎄") println() println("[Part 1]") println("Answer: ${part1(workflows, parts)}") println() println("[Part 2]") println("Answer: ${part2(workflows)}") } private data class Condition( val key: Char, val cmp: Char, val num: Int, ) private data class Rule( val condition: Condition?, val transition: String, ) private typealias Part = Map<Char, Int> private typealias Workflows = Map<String, List<Rule>> private fun String.toPart(): Part = this.trim('{', '}') .split(',') .map { it.split('=') } .associate { (k, n) -> k.first() to n.toInt() } private fun String.toRule(): Rule { if (!this.contains(':')) { return Rule(condition = null, transition = this) } val (lhs, transition) = this.split(':') val condition = Condition( key = lhs[0], cmp = lhs[1], num = lhs.substring(2).toInt(), ) return Rule(condition, transition) } private fun String.toWorkflow(): Pair<String, List<Rule>> { val (name, rules) = this.trim('}').split('{') return Pair(name, rules.split(',').map(String::toRule)) } private fun parse(path: String): Pair<Workflows, List<Part>> { val (workflowsPart, partsPart) = File(path) .readText() .split("\n\n", "\r\n\r\n") val workflows = workflowsPart.lines() .map(String::toWorkflow) .associate { (name, rules) -> name to rules } val parts = partsPart.lines() .map(String::toPart) return Pair(workflows, parts) } private fun count(part: Part, workflows: Workflows): Int { var target = "in" while (target != "A" && target != "R") { val rules = workflows.getValue(target) for ((condition, transition) in rules) { if (condition == null) { target = transition break } val (key, cmp, num) = condition val satisfies = if (cmp == '>') { part.getValue(key) > num } else { part.getValue(key) < num } if (satisfies) { target = transition break } } } return if (target == "A") { part.values.sum() } else { 0 } } private fun part1(workflows: Workflows, parts: List<Part>): Int = parts.sumOf { count(it, workflows) } private fun part2(workflows: Workflows): Long { val queue = ArrayDeque<Pair<String, Map<Char, IntRange>>>() .apply { add("in" to mapOf( 'x' to 1..4000, 'm' to 1..4000, 'a' to 1..4000, 's' to 1..4000, )) } var total = 0L while (queue.isNotEmpty()) { val (target, startingRanges) = queue.removeFirst() if (target == "A" || target == "R") { if (target == "A") { val product = startingRanges.values .map { (it.last - it.first + 1).toLong() } .reduce { acc, it -> acc * it } total += product } continue } val ranges = startingRanges.toMutableMap() val rules = workflows.getValue(target) for ((condition, transition) in rules) { if (condition == null) { queue += transition to ranges break } val (key, cmp, num) = condition val range = ranges.getValue(key) val (t, f) = if (cmp == '>') { IntRange(num + 1, range.last) to IntRange(range.first, num) } else { IntRange(range.first, num - 1) to IntRange(num, range.last) } queue += transition to ranges.toMutableMap().apply { set(key, t) } ranges[key] = f } } return total }
[ { "class_path": "daniilsjb__advent-of-code-2023__46a8376/day19/Day19Kt.class", "javap": "Compiled from \"Day19.kt\"\npublic final class day19.Day19Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day19/Day19.txt\n 2: invokestatic #12 ...
mjurisic__advent-of-code-2020__9fabcd6/src/org/mjurisic/aoc2020/day12/Day12.kt
package org.mjurisic.aoc2020.day12 import java.io.File import kotlin.math.abs class Day12 { companion object { @JvmStatic fun main(args: Array<String>) = try { val ship = Ship(0, 0) val waypoint = Waypoint(10, -1) File(ClassLoader.getSystemResource("resources/input12.txt").file).forEachLine { val command = it.first() val value = it.substring(1, it.length).toInt() moveWaypointInDirection(command, waypoint, value) if (command == 'F') { moveShipForward(ship, waypoint, value) } else if (command == 'R' || command == 'L') { rotateWaypoint(command, ship, waypoint, value) } } val manhattan = abs(ship.x) + abs(ship.y) println(manhattan) } catch (e: Exception) { e.printStackTrace() } private fun moveShipForward(ship: Ship, waypoint: Waypoint, value: Int) { val dx = waypoint.x - ship.x val dy = waypoint.y - ship.y repeat(value) { ship.x += dx ship.y += dy } waypoint.x = ship.x + dx waypoint.y = ship.y + dy } private fun rotateWaypoint(direction: Char, ship: Ship, waypoint: Waypoint, value: Int) { val dx = waypoint.x - ship.x val dy = waypoint.y - ship.y if (direction == 'L' && value == 90 || direction == 'R' && value == 270) { waypoint.y = ship.y - dx waypoint.x = ship.x + dy } else if (direction == 'R' && value == 90 || direction == 'L' && value == 270) { waypoint.y = ship.y + dx waypoint.x = ship.x - dy } else if (value == 180) { waypoint.y = ship.y - dy waypoint.x = ship.x - dx } } private fun moveWaypointInDirection(dir: Char, waypoint: Waypoint, value: Int) { when (dir) { 'N' -> waypoint.y = waypoint.y - value 'S' -> waypoint.y = waypoint.y + value 'E' -> waypoint.x = waypoint.x + value 'W' -> waypoint.x = waypoint.x - value } } } } class Ship(var x: Int, var y: Int) { override fun toString(): String { return "Ship(x=$x, y=$y)" } } class Waypoint(var x: Int, var y: Int) { override fun toString(): String { return "Waypoint(x=$x, y=$y)" } }
[ { "class_path": "mjurisic__advent-of-code-2020__9fabcd6/org/mjurisic/aoc2020/day12/Day12$Companion.class", "javap": "Compiled from \"Day12.kt\"\npublic final class org.mjurisic.aoc2020.day12.Day12$Companion {\n private org.mjurisic.aoc2020.day12.Day12$Companion();\n Code:\n 0: aload_0\n 1: i...
mjurisic__advent-of-code-2020__9fabcd6/src/org/mjurisic/aoc2020/day14/Day14.kt
package org.mjurisic.aoc2020.day14 import java.io.File import java.math.BigInteger class Day14 { companion object { @JvmStatic fun main(args: Array<String>) = try { var mask = "" val mem = HashMap<String, BigInteger>() File(ClassLoader.getSystemResource("resources/input14.txt").file).forEachLine { if (it.startsWith("mask")) { mask = it.substring(7) } else { val groups = Regex("mem\\[(\\d+)] = (\\d+)").find(it)!!.groups val address = groups[1]!!.value val value = BigInteger(groups[2]!!.value) writeValues(mem, address, mask, value) } } var sum = BigInteger("0") mem.values.forEach { sum = sum.add(it) } println(sum) } catch (e: Exception) { e.printStackTrace() } private fun writeValues( mem: java.util.HashMap<String, BigInteger>, address: String, bitmask: String, value: BigInteger ) { val applyBitmask = applyBitmask(bitmask, BigInteger(address)) val explodeBitmask = explodeBitmask(applyBitmask, 0, listOf(applyBitmask.replace('X', '0'))) explodeBitmask.forEach{ mem[it] = value } } private fun explodeBitmask(bitmask: String, start: Int, input: List<String>): List<String> { val exploded = ArrayList<String>() exploded.addAll(input) if (start == bitmask.length) { return exploded } if (bitmask[start] == 'X') { for (i in 0 until exploded.size) { val replaced = exploded[i].replaceRange(start, start + 1, "1") exploded.add(replaced) } } return explodeBitmask(bitmask, start + 1, exploded) } private fun applyBitmask(bitmask: String, address: BigInteger): String { var result = "" val reversedAddress = address.toString(2).reversed() bitmask.reversed().forEachIndexed { i, c -> var charValue = '0' if (i < reversedAddress.length) { charValue = reversedAddress[i] } when (c) { '1' -> result += '1' '0' -> result += charValue 'X' -> result += 'X' } } return result.reversed() } private fun calculateValue(mask: String, value: BigInteger): BigInteger { var result = "" val stringValue = value.toString(2).reversed() mask.reversed().forEachIndexed { i, c -> var charValue = '0' if (i < stringValue.length) { charValue = stringValue[i] } when (c) { '0' -> result += '0' '1' -> result += '1' 'X' -> result += charValue } } return BigInteger(result.reversed(), 2) } } }
[ { "class_path": "mjurisic__advent-of-code-2020__9fabcd6/org/mjurisic/aoc2020/day14/Day14$Companion.class", "javap": "Compiled from \"Day14.kt\"\npublic final class org.mjurisic.aoc2020.day14.Day14$Companion {\n private org.mjurisic.aoc2020.day14.Day14$Companion();\n Code:\n 0: aload_0\n 1: i...
mjurisic__advent-of-code-2020__9fabcd6/src/org/mjurisic/aoc2020/day7/Day7.kt
package org.mjurisic.aoc2020.day7 import java.io.File import java.util.function.Consumer class Day7 { companion object { @JvmStatic fun main(args: Array<String>) = try { val nodes = HashMap<String, Node>() val vertices = ArrayList<Vertex>() File(ClassLoader.getSystemResource("resources/input7.txt").file).forEachLine { val bagColor = it.substring(0, it.indexOf("bags") - 1) val bagContent = it.substring(it.indexOf("contain") + 8, it.length - 1) val edges = ArrayList<Vertex>() if (bagContent != "no other bags") { bagContent.split(",").forEach(Consumer { val bag = it.trim() val strength = bag.substring(0, bag.indexOf(" ")) val color = bag.substring(bag.indexOf(" ") + 1, bag.lastIndexOf(" ")) val vertex = Vertex(bagColor, color, strength.toInt()) edges.add(vertex) vertices.add(vertex) }) } nodes.put(bagColor, Node(bagColor, edges)) } // part 1 // println(nodes.filter { isContained(it.value, vertices, nodes, "shiny gold") }.size) val sourceNode = nodes["shiny gold"] println(countBags(sourceNode!!, nodes, vertices)) } catch (e: Exception) { e.printStackTrace() } // part 1 private fun isContained( bag: Node, vertices: java.util.ArrayList<Vertex>, nodes: HashMap<String, Node>, color: String ): Boolean { if (bag.color == color) { return false } if (contains(bag, vertices, nodes, color)) { return true } return false } private fun contains( bag: Node, vertices: java.util.ArrayList<Vertex>, nodes: HashMap<String, Node>, color: String ): Boolean { if (bag.color == color) { return false } if (vertices.any { it.source == bag.color && it.destination == color }) { return true } if (vertices.filter { it.source == bag.color }.map { nodes[it.destination] }.any { contains( it!!, vertices, nodes, color ) }) { return true } return false } // part 2 private fun countBags( sourceNode: Node, nodes: java.util.HashMap<String, Node>, vertices: java.util.ArrayList<Vertex> ): Int { var count = 0 sourceNode.vertices.forEach { count += it.strength val childNode = nodes[it.destination]!! count += it.strength * countBags(childNode, nodes, vertices) } return count } } } class Node(var color: String, var vertices: List<Vertex>) { override fun toString(): String { return "Node(color='$color', vertices=$vertices)" } } class Vertex(var source: String, var destination: String, var strength: Int) { override fun toString(): String { return "Vertex(source='$source', destination='$destination', strength=$strength)" } }
[ { "class_path": "mjurisic__advent-of-code-2020__9fabcd6/org/mjurisic/aoc2020/day7/Day7.class", "javap": "Compiled from \"Day7.kt\"\npublic final class org.mjurisic.aoc2020.day7.Day7 {\n public static final org.mjurisic.aoc2020.day7.Day7$Companion Companion;\n\n public org.mjurisic.aoc2020.day7.Day7();\n ...
hastebrot__kotlinx.math__aea1a4d/src/main/kotlin/combinatorics/Permutations.kt
package combinatorics import java.util.LinkedList interface Circular<out T> : Iterable<T> { fun state(): T fun inc() fun isZero(): Boolean // `true` in exactly one state fun hasNext(): Boolean // `false` if the next state `isZero()` override fun iterator() : Iterator<T> { return object : Iterator<T> { var started = false override fun next(): T { if(started) { inc() } else { started = true } return state() } override fun hasNext() = this@Circular.hasNext() } } } class Ring(val size: Int) : Circular<Int> { private var state = 0 override fun state() = state override fun inc() {state = (1 + state) % size} override fun isZero() = (state == 0) override fun hasNext() = (state != size - 1) init { assert(size > 0) } } abstract class CircularList<out E, out H: Circular<E>>(val size: Int) : Circular<List<E>> { protected abstract val state: List<H> // state.size == size override fun inc() { state.forEach { it.inc() if(! it.isZero()) return } } override fun isZero() = state.all {it.isZero()} override fun hasNext() = state.any {it.hasNext()} } abstract class IntCombinations(size: Int) : CircularList<Int, Ring>(size) class BinaryBits(N: Int) : IntCombinations(N) { override val state = Array(N, {Ring(2)}).toList() override fun state() = state.map {it.state()}.reversed() } class Permutations(N: Int) : IntCombinations(N) { override val state = mutableListOf<Ring>() init { for(i in N downTo 1) { state += Ring(i) } } override fun state(): List<Int> { val items = (0..size - 1).toCollection(LinkedList()) return state.map {ring -> items.removeAt(ring.state())} } } fun main(args: Array<String>) { val n = 100 val sumNumbers = Ring(n).sum() println("In theory, the sum of numbers 0..${n - 1} is ${n * (n - 1) / 2}.") println("Which is consistent with a practical result of $sumNumbers.\n") BinaryBits(5).asSequence().filter {it.sum() == 2}.take(5).forEach { println(it) } println("\npermutations of 3 elements:") for(configuration in Permutations(3)) { println(configuration) } }
[ { "class_path": "hastebrot__kotlinx.math__aea1a4d/combinatorics/Permutations.class", "javap": "Compiled from \"Permutations.kt\"\npublic final class combinatorics.Permutations extends combinatorics.IntCombinations {\n private final java.util.List<combinatorics.Ring> state;\n\n public combinatorics.Permuta...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/boj/week02/recursive_function/FibonacciSequence5.kt
package boj.week02.recursive_function import java.util.* /** * * no.10870 * https://www.acmicpc.net/problem/10870 * * 피보나치 수는 0과 1로 시작한다. 0번째 피보나치 수는 0이고, 1번째 피보나치 수는 1이다. 그 다음 2번째 부터는 바로 앞 두 피보나치 수의 합이 된다. * 이를 식으로 써보면 Fn = Fn-1 + Fn-2 (n ≥ 2)가 된다. * n=17일때 까지 피보나치 수를 써보면 다음과 같다. * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 * n이 주어졌을 때, n번째 피보나치 수를 구하는 프로그램을 작성하시오. * * 입력 * 첫째 줄에 n이 주어진다. n은 20보다 작거나 같은 자연수 또는 0이다. * * 출력 * 첫째 줄에 n번째 피보나치 수를 출력한다. */ fun main() { val inputValue = Scanner(System.`in`) println("${fibonacci(inputValue.nextInt())}") } fun fibonacci(n: Int): Int { if (n <= 1) { return n } return fibonacci(n - 1) + fibonacci(n - 2) }
[ { "class_path": "boris920308__HoOne__8881468/boj/week02/recursive_function/FibonacciSequence5Kt.class", "javap": "Compiled from \"FibonacciSequence5.kt\"\npublic final class boj.week02.recursive_function.FibonacciSequence5Kt {\n public static final void main();\n Code:\n 0: new #8 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv02/Lv2_12939_최댓값과최솟값.kt
package programmers.lv02 /** * * no.12939 * 최댓값과 최솟값 * https://school.programmers.co.kr/learn/courses/30/lessons/12939 * * 문제 설명 * 문자열 s에는 공백으로 구분된 숫자들이 저장되어 있습니다. * str에 나타나는 숫자 중 최소값과 최대값을 찾아 이를 "(최소값) (최대값)"형태의 문자열을 반환하는 함수, solution을 완성하세요. * 예를들어 s가 "1 2 3 4"라면 "1 4"를 리턴하고, "-1 -2 -3 -4"라면 "-4 -1"을 리턴하면 됩니다. * * 제한 조건 * s에는 둘 이상의 정수가 공백으로 구분되어 있습니다. * 입출력 예 * s return * "1 2 3 4" "1 4" * "-1 -2 -3 -4" "-4 -1" * "-1 -1" "-1 -1" * */ fun main() { println(solution("1 2 3 4")) println(solution("-1 -2 -3 -4")) } private fun solution(s: String): String { var answer = "" val splitString = s.split(" ") answer = splitString.minOf { it.toInt() }.toString() + " " + splitString.maxOf { it.toInt() }.toString() return answer }
[ { "class_path": "boris920308__HoOne__8881468/programmers/lv02/Lv2_12939_최댓값과최솟값Kt.class", "javap": "Compiled from \"Lv2_12939_최댓값과최솟값.kt\"\npublic final class programmers.lv02.Lv2_12939_최댓값과최솟값Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String 1 2 3 4\...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv02/Lv2_12951_JadenCase문자열만들기.kt
package programmers.lv02 /** * * no.12951 * JadenCase 문자열 만들기 * https://school.programmers.co.kr/learn/courses/30/lessons/12951 * * JadenCase란 모든 단어의 첫 문자가 대문자이고, 그 외의 알파벳은 소문자인 문자열입니다. * 단, 첫 문자가 알파벳이 아닐 때에는 이어지는 알파벳은 소문자로 쓰면 됩니다. (첫 번째 입출력 예 참고) * 문자열 s가 주어졌을 때, s를 JadenCase로 바꾼 문자열을 리턴하는 함수, solution을 완성해주세요. * * 제한 조건 * s는 길이 1 이상 200 이하인 문자열입니다. * s는 알파벳과 숫자, 공백문자(" ")로 이루어져 있습니다. * 숫자는 단어의 첫 문자로만 나옵니다. * 숫자로만 이루어진 단어는 없습니다. * 공백문자가 연속해서 나올 수 있습니다. * 입출력 예 * s return * "3people unFollowed me" "3people Unfollowed Me" * "for the last week" "For The Last Week" */ fun main() { println(solution("3people unFollowed me")) println(solution("for the last week")) } private fun solution(s: String): String { var answer = "" val sArray = s.toCharArray() sArray.forEachIndexed { index, c -> if (index == 0) { sArray[index] = sArray[index].uppercaseChar() } if (c.isLetter() && index != 0) { if (sArray[index -1].toString() != " ") { sArray[index] = sArray[index].lowercaseChar() } else { sArray[index] = sArray[index].uppercaseChar() } } } answer = String(sArray) return answer }
[ { "class_path": "boris920308__HoOne__8881468/programmers/lv02/Lv2_12951_JadenCase문자열만들기Kt.class", "javap": "Compiled from \"Lv2_12951_JadenCase문자열만들기.kt\"\npublic final class programmers.lv02.Lv2_12951_JadenCase문자열만들기Kt {\n public static final void main();\n Code:\n 0: ldc #8 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_68644.kt
package programmers.lv01 /** * no.68644 * 두 개 뽑아서 더하기 * https://school.programmers.co.kr/learn/courses/30/lessons/68644 * * 문제 설명 * 정수 배열 numbers가 주어집니다. * numbers에서 서로 다른 인덱스에 있는 두 개의 수를 뽑아 더해서 만들 수 있는 모든 수를 * 배열에 오름차순으로 담아 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * numbers의 길이는 2 이상 100 이하입니다. * numbers의 모든 수는 0 이상 100 이하입니다. * * 입출력 예 * numbers result * [2,1,3,4,1] [2,3,4,5,6,7] * [5,0,2,7] [2,5,7,9,12] * * 입출력 예 설명 * 입출력 예 #1 * 2 = 1 + 1 입니다. (1이 numbers에 두 개 있습니다.) * 3 = 2 + 1 입니다. * 4 = 1 + 3 입니다. * 5 = 1 + 4 = 2 + 3 입니다. * 6 = 2 + 4 입니다. * 7 = 3 + 4 입니다. * 따라서 [2,3,4,5,6,7] 을 return 해야 합니다. * * 입출력 예 #2 * 2 = 0 + 2 입니다. * 5 = 5 + 0 입니다. * 7 = 0 + 7 = 5 + 2 입니다. * 9 = 2 + 7 입니다. * 12 = 5 + 7 입니다. * 따라서 [2,5,7,9,12] 를 return 해야 합니다. */ fun main() { solution(intArrayOf(2, 1, 3, 4, 1)) } private fun solution(numbers: IntArray): IntArray { val resultList = mutableListOf<Int>() for (i in numbers.indices) { for (j in i + 1 until numbers.size) { val sum = numbers[i] + numbers[j] if (!resultList.contains(sum)) { resultList.add(sum) } } } return resultList.sorted().toIntArray() }
[ { "class_path": "boris920308__HoOne__8881468/programmers/lv01/Lv1_68644Kt.class", "javap": "Compiled from \"Lv1_68644.kt\"\npublic final class programmers.lv01.Lv1_68644Kt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: newarray int\n 3: astore_0\n 4: aload_...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12901.kt
package programmers.lv01 /** * no.12901 * 2016년 * https://school.programmers.co.kr/learn/courses/30/lessons/12901 * * 2016년 1월 1일은 금요일입니다. * 2016년 a월 b일은 무슨 요일일까요? * 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. * 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT 입니다. * 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요. * * 제한 조건 * 2016년은 윤년입니다. * 2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다) * * 입출력 예 * a b result * 5 24 "TUE" */ fun main() { solution(5, 24) } private fun solution(a: Int, b: Int): String { var answer = "" val daysInMonth = listOf(0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) val daysOfWeek = listOf("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT", ) var days = 0 for (month in 1 until a) { days += daysInMonth[month] } days += b - 1 answer = daysOfWeek[(days + 5) % 7] return answer }
[ { "class_path": "boris920308__HoOne__8881468/programmers/lv01/Lv1_12901Kt.class", "javap": "Compiled from \"Lv1_12901.kt\"\npublic final class programmers.lv01.Lv1_12901Kt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: bipush 24\n 3: invokestatic #10 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12935.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12935 * * 문제 설명 * 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. * 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. * 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다. * * 제한 조건 * arr은 길이 1 이상인 배열입니다. * 인덱스 i, j에 대해 i ≠ j이면 arr[i] ≠ arr[j] 입니다. * 입출력 예 * arr return * [4,3,2,1] [4,3,2] * [10] [-1] */ fun main() { solution(intArrayOf(4,3,2,1)) solution(intArrayOf(10)) solution(intArrayOf()) } private fun solution(arr: IntArray): IntArray { if (arr.isEmpty()) return intArrayOf(-1) var answer = intArrayOf() var minValue = arr.first(); arr.forEach { if (it < minValue) { minValue = it } } answer = arr.filter { it != minValue }.toIntArray() if (answer.isEmpty()) return intArrayOf(-1) return answer } //private fun solution_1(arr: IntArray): IntArray { // if (arr.size == 1) return intArrayOf(-1) // return arr.sorted().toIntArray().copyOfRange(1, arr.size); //} private fun solution_2(arr: IntArray): IntArray = if(arr.size == 1) intArrayOf(-1) else arr.filter { it != arr.min() }.toIntArray()
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12935Kt.class", "javap": "Compiled from \"Lv1_12935.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12935Kt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: newarray int\n 3: as...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_77884.kt
package main.kotlin.programmers.lv01 import kotlin.math.sqrt /** * * https://school.programmers.co.kr/learn/courses/30/lessons/77884 * * 약수의 개수와 덧셈 * 문제 설명 * 두 정수 left와 right가 매개변수로 주어집니다. * left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * 1 ≤ left ≤ right ≤ 1,000 * 입출력 예 * left right result * 13 17 43 * 24 27 52 * 입출력 예 설명 * 입출력 예 #1 * * 다음 표는 13부터 17까지의 수들의 약수를 모두 나타낸 것입니다. * 수 약수 약수의 개수 * 13 1, 13 2 * 14 1, 2, 7, 14 4 * 15 1, 3, 5, 15 4 * 16 1, 2, 4, 8, 16 5 * 17 1, 17 2 * 따라서, 13 + 14 + 15 - 16 + 17 = 43을 return 해야 합니다. * 입출력 예 #2 * * 다음 표는 24부터 27까지의 수들의 약수를 모두 나타낸 것입니다. * 수 약수 약수의 개수 * 24 1, 2, 3, 4, 6, 8, 12, 24 8 * 25 1, 5, 25 3 * 26 1, 2, 13, 26 4 * 27 1, 3, 9, 27 4 * 따라서, 24 - 25 + 26 + 27 = 52를 return 해야 합니다. * */ fun main() { solution(13, 17) } private fun solution(left: Int, right: Int): Int { var answer: Int = 0 for (i in left..right) { if (countDivisors(i) % 2 == 0) { answer += i } else { answer -= i } } println(answer) return answer } private fun countDivisors(n: Int): Int { var count = 0 val sqrtN = sqrt(n.toDouble()).toInt() for (i in 1..sqrtN) { if (n % i == 0) { count += 2 // i와 n/i는 모두 약수이므로 2를 추가 } } // 만약 n이 제곱수인 경우 중복으로 카운트된 약수를 제거 if (sqrtN * sqrtN == n) { count-- } return count }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_77884Kt.class", "javap": "Compiled from \"Lv1_77884.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_77884Kt {\n public static final void main();\n Code:\n 0: bipush 13\n 2: bipush 17\n ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_70128.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/70128 * * 문제 설명 * 길이가 같은 두 1차원 정수 배열 a, b가 매개변수로 주어집니다. * a와 b의 내적을 return 하도록 solution 함수를 완성해주세요. * * 이때, a와 b의 내적은 a[0]*b[0] + a[1]*b[1] + ... + a[n-1]*b[n-1] 입니다. (n은 a, b의 길이) * * 제한사항 * a, b의 길이는 1 이상 1,000 이하입니다. * a, b의 모든 수는 -1,000 이상 1,000 이하입니다. * 입출력 예 * a b result * [1,2,3,4] [-3,-1,0,2] 3 * [-1,0,1] [1,0,-1] -2 * * 입출력 예 설명 * 입출력 예 #1 * a와 b의 내적은 1*(-3) + 2*(-1) + 3*0 + 4*2 = 3 입니다. * * 입출력 예 #2 * a와 b의 내적은 (-1)*1 + 0*0 + 1*(-1) = -2 입니다. */ fun main() { solution(intArrayOf(1,2,3,4), intArrayOf(-3,-1,0,2)) } private fun solution(a: IntArray, b: IntArray): Int { var answer: Int = 0 for (i in a.indices) { answer += a[i] * b[i] } return answer }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_70128Kt.class", "javap": "Compiled from \"Lv1_70128.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_70128Kt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: newarray int\n 3: as...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12912.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12912 * * 두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요. * 예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다. * * 제한 조건 * a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요. * a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다. * a와 b의 대소관계는 정해져있지 않습니다. * 입출력 예 * a b return * 3 5 12 * 3 3 3 * 5 3 12 * */ fun main() { solution(3, 5) solution(3, 3) solution(5, 3) } private fun solution(a: Int, b: Int): Long { var answer: Long = 0 if (a > b) { for (i in b..a) { answer += i } } else { for (i in a..b) { answer += i } } return answer } private fun secondSolution(a: Int, b: Int): Long { val start : Long = (if(a>b) b else a).toLong() val end : Long = (if(a>b) a else b).toLong() return (start..end).sum() }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12912Kt.class", "javap": "Compiled from \"Lv1_12912.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12912Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: iconst_5\n 2: invokestatic...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12926.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12926 * * 시저 암호 * 문제 설명 * 어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다. * 예를 들어 "AB"는 1만큼 밀면 "BC"가 되고, 3만큼 밀면 "DE"가 됩니다. * "z"는 1만큼 밀면 "a"가 됩니다. * 문자열 s와 거리 n을 입력받아 s를 n만큼 민 암호문을 만드는 함수, solution을 완성해 보세요. * * 제한 조건 * 공백은 아무리 밀어도 공백입니다. * s는 알파벳 소문자, 대문자, 공백으로만 이루어져 있습니다. * s의 길이는 8000이하입니다. * n은 1 이상, 25이하인 자연수입니다. * 입출력 예 * s n result * "AB" 1 "BC" * "z" 1 "a" * "a B z" 4 "e F d" */ fun main() { // println(solution("a b y Z", 2)) solution("a b y Z", 2) } private fun solution(s: String, n: Int): String { var answer = "" // " " = 32 // a = 97, z = 122 // A = 65, Z = 90 for (char in s) { println(" - - - - - start - - - - - ") println("char = $char, ascii = ${char.toInt()}") if (isLowerCase(char.toInt())) { println("isLowerCase") if (isLowerCase(char.toInt() + n)) { answer += (char.toInt() + n).toChar() } else { println("LowerCase err, char.toInt() + n = ${char.toInt() + n}, ${(char.toInt() + n).toChar()} ") println("char.toInt() + n = ${char.toInt() + n}") println("${(96 + (char.toInt() + n).toInt() - 122).toChar()}") answer += (96 + (char.toInt() + n).toInt() - 122).toChar() } } if (isUpperCase(char.toInt())) { println("isUpperCase") if (isUpperCase(char.toInt() + n)) { answer += (char.toInt() + n).toChar() } else { println("UpperCase err, char.toInt() + n = ${char.toInt() + n}, ${(char.toInt() + n).toChar()} ") println("char.toInt() + n = ${char.toInt() + n}") println("${(64 + (char.toInt() + n).toInt() - 90).toChar()}") answer += (64 + (char.toInt() + n).toInt() - 90).toChar() } } if (char.toInt() == 32) { println("is ") answer += " " } println("answer = $answer") } return answer } private fun isLowerCase(ascii: Int): Boolean { return ascii in 97 .. 122 } private fun isUpperCase(ascii: Int): Boolean { return ascii in 65..90 }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12926Kt.class", "javap": "Compiled from \"Lv1_12926.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12926Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String a b y Z\...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12918.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12918 * * 문자열 다루기 기본 * 문제 설명 * 문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. * 예를 들어 s가 "a234"이면 False를 리턴하고 "1234"라면 True를 리턴하면 됩니다. * * 제한 사항 * s는 길이 1 이상, 길이 8 이하인 문자열입니다. * s는 영문 알파벳 대소문자 또는 0부터 9까지 숫자로 이루어져 있습니다. * 입출력 예 * s return * "a234" false * "1234" true * */ fun main() { println(solution("a234")) println(solution("1234")) } private fun solution(s: String): Boolean { return (s.length == 4 || s.length == 6) && isNumericString(s) } private fun isNumericString(s: String): Boolean { val regex = Regex("""^\d+$""") return regex.matches(s) } private fun solution_1(s: String) = (s.length == 4 || s.length == 6) && s.toIntOrNull() != null
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12918Kt.class", "javap": "Compiled from \"Lv1_12918.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12918Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String a234\n ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12950.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12950 * * 행렬의 덧셈 * 문제 설명 * 행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. * 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요. * * 제한 조건 * 행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다. * 입출력 예 * arr1 arr2 return * [[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]] * [[1],[2]] [[3],[4]] [[4],[6]] */ fun main() { solution(arrayOf(intArrayOf(1,2), intArrayOf(2,3)), arrayOf(intArrayOf(3,4), intArrayOf(5,6))) } private fun solution(arr1: Array<IntArray>, arr2: Array<IntArray>): Array<IntArray> { val rowSize = arr1.size val colSize = arr1[0].size val answer = Array(rowSize) { IntArray(colSize) } for (i in 0 until rowSize) { for (j in 0 until colSize) { answer[i][j] = arr1[i][j] + arr2[i][j] } } return answer }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12950Kt.class", "javap": "Compiled from \"Lv1_12950.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12950Kt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: anewarray #8 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12940.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12940 * * 최대공약수와 최소공배수 * 문제 설명 * 두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. * 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. * 예를 들어 두 수 3, 12의 최대공약수는 3, 최소공배수는 12이므로 solution(3, 12)는 [3, 12]를 반환해야 합니다. * * 제한 사항 * 두 수는 1이상 1000000이하의 자연수입니다. * 입출력 예 * n m return * 3 12 [3, 12] * 2 5 [1, 10] * 입출력 예 설명 * 입출력 예 #1 * 위의 설명과 같습니다. * * 입출력 예 #2 * 자연수 2와 5의 최대공약수는 1, 최소공배수는 10이므로 [1, 10]을 리턴해야 합니다. */ fun main() { solution(3, 12) println(" - - - - - - - - - - ") solution(2, 5) } private fun solution(n: Int, m: Int): IntArray { var answer = intArrayOf(0, 0) answer[0] = findGCD(n, m) answer[1] = findLCM(n, m) println(answer.toList()) return answer } private fun findGCD(a: Int, b: Int): Int { return if (b == 0) { a } else { findGCD(b, a % b) } } private fun findLCM(a: Int, b: Int): Int { val gcd = findGCD(a, b) return a * b / gcd }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12940Kt.class", "javap": "Compiled from \"Lv1_12940.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12940Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: bipush 12\n 3: invo...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_68935.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/68935 * * 3진법 뒤집기 * 문제 설명 * 자연수 n이 매개변수로 주어집니다. * n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * n은 1 이상 100,000,000 이하인 자연수입니다. * 입출력 예 * n result * 45 7 * 125 229 * 입출력 예 설명 * 입출력 예 #1 * * 답을 도출하는 과정은 다음과 같습니다. * n (10진법) n (3진법) 앞뒤 반전(3진법) 10진법으로 표현 * 45 1200 0021 7 * 따라서 7을 return 해야 합니다. * 입출력 예 #2 * * 답을 도출하는 과정은 다음과 같습니다. * n (10진법) n (3진법) 앞뒤 반전(3진법) 10진법으로 표현 * 125 11122 22111 229 * 따라서 229를 return 해야 합니다. */ fun main() { solution(45) } private fun solution(n: Int): Int { return Integer.parseInt(n.toString(3).reversed(), 3) } private fun solution_1(n: Int): Int { return n.toString(3).reversed().toInt(10) }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_68935Kt.class", "javap": "Compiled from \"Lv1_68935.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_68935Kt {\n public static final void main();\n Code:\n 0: bipush 45\n 2: invokestatic #10 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_86051.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/86051?language=kotlin * * 문제 설명 * 0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. * numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요. * * 제한사항 * 1 ≤ numbers의 길이 ≤ 9 * 0 ≤ numbers의 모든 원소 ≤ 9 * numbers의 모든 원소는 서로 다릅니다. * 입출력 예 * numbers result * [1,2,3,4,6,7,8,0] 14 * [5,8,4,0,6,7,9] 6 * 입출력 예 설명 * 입출력 예 #1 * * 5, 9가 numbers에 없으므로, 5 + 9 = 14를 return 해야 합니다. * 입출력 예 #2 * * 1, 2, 3이 numbers에 없으므로, 1 + 2 + 3 = 6을 return 해야 합니다. * */ fun main() { solution(intArrayOf(1,2,3,4,6,7,8,0)) } private fun solution(numbers: IntArray): Int { var answer: Int = 0 for (i in 0..9) { if (!(numbers.contains(i))) { answer += i } } println("answer = $answer") return answer } private fun solution_1(numbers: IntArray): Int = (0..9).filterNot(numbers::contains).sum() private fun solution_2(numbers: IntArray): Int = 45 - numbers.sum()
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_86051Kt.class", "javap": "Compiled from \"Lv1_86051.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_86051Kt {\n public static final void main();\n Code:\n 0: bipush 8\n 2: newarray int\n ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12934_square.kt
package main.kotlin.programmers.lv01 import kotlin.math.pow import kotlin.math.sqrt /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12934 * * 문제 설명 * 임의의 양의 정수 n에 대해, n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다. * n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고, n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요. * * 제한 사항 * n은 1이상, 50000000000000 이하인 양의 정수입니다. * 입출력 예 * n return * 121 144 * 3 -1 * 입출력 예 설명 * 입출력 예#1 * 121은 양의 정수 11의 제곱이므로, (11+1)를 제곱한 144를 리턴합니다. * * 입출력 예#2 * 3은 양의 정수의 제곱이 아니므로, -1을 리턴합니다. * */ fun main() { println("result = ${solution(12)}") println("result = ${solution(13)}") println("result = ${solution(121)}") println("result = ${solution(3)}") } private fun solution(n: Long): Long{ var answer:Long = 0 val sqrt = sqrt(n.toDouble()).toLong() println("n = $n , sqrt = $sqrt") answer = if (sqrt * sqrt == n) { (sqrt + 1).toDouble().pow(2.0).toLong() } else { -1 } return answer }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12934_squareKt.class", "javap": "Compiled from \"Lv1_12934_square.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12934_squareKt {\n public static final void main();\n Code:\n 0: new #8 ...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12928_divisors.kt
package main.kotlin.programmers.lv01 import kotlin.math.ceil import kotlin.math.sqrt /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12928 * * 문제 설명 * 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요. * * 제한 사항 * n은 0 이상 3000이하인 정수입니다. * 입출력 예 * n return * 12 28 * 5 6 * 입출력 예 설명 * 입출력 예 #1 * 12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28입니다. * * 입출력 예 #2 * 5의 약수는 1, 5입니다. 이를 모두 더하면 6입니다. */ private fun findDivisors(number: Int): List<Int> { val divisors = mutableListOf<Int>() if (number == 1) { divisors.add(1) } val sqrt = ceil(sqrt(number.toDouble())).toInt() println("get number = $number , sqrt = $sqrt") for (i in 1 until sqrt) { if (number % i == 0) { divisors.add(i) divisors.add(number / i) } } if(sqrt * sqrt == number) { divisors.add(sqrt) } return divisors } private fun solution(n: Int): Int { if (n == 1) return 1 var answer = 0 val sqrt = ceil(sqrt(n.toDouble())).toInt() for (i in 1 until sqrt) { if (n % i == 0) { answer += i answer += (n / i) } } if(sqrt * sqrt == n) { answer += sqrt } return answer } fun main() { println("findDivisors(0) = ${findDivisors(0).sorted()}") println("input = 0, result = ${solution(0)}") println(" * * * * * ") println("findDivisors(1) = ${findDivisors(1).sorted()}") println("input = 1, result = ${solution(1)}") println(" * * * * * ") println("findDivisors(2) = ${findDivisors(2).sorted()}") println("input = 2, result = ${solution(2)}") println(" * * * * * ") println("findDivisors(16) = ${findDivisors(16).sorted()}") println("input = 16, result = ${solution(16)}") println(" * * * * * ") }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12928_divisorsKt.class", "javap": "Compiled from \"Lv1_12928_divisors.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12928_divisorsKt {\n private static final java.util.List<java.lang.Integer> findDivisors(int);\n C...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12954_x_n.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12954 * * 문제 설명 * 함수 solution은 정수 x와 자연수 n을 입력 받아, x부터 시작해 x씩 증가하는 숫자를 n개 지니는 리스트를 리턴해야 합니다. * 다음 제한 조건을 보고, 조건을 만족하는 함수, solution을 완성해주세요. * * 제한 조건 * x는 -10000000 이상, 10000000 이하인 정수입니다. * n은 1000 이하인 자연수입니다. * 입출력 예 * x n answer * 2 5 [2,4,6,8,10] * 4 3 [4,8,12] * -4 2 [-4, -8] */ fun main() { println("result = ${solution(2, 5).toList()}") println("result = ${secondSolution(4, 3).toList()}") println("result = ${solution(-4, 2).toList()}") println("result = ${secondSolution(0, 3).toList()}") } private fun solution(x: Int, n: Int): LongArray { val answer = LongArray(n) for (i in 0 until n) { answer[i] = x * (i.toLong() + 1); } return answer } private fun secondSolution(x: Int, n: Int): LongArray = LongArray(n) { i -> x.toLong() * (i+1) }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12954_x_nKt.class", "javap": "Compiled from \"Lv1_12954_x_n.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12954_x_nKt {\n public static final void main();\n Code:\n 0: new #8 // cla...
boris920308__HoOne__8881468/hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12948_hide_number.kt
package main.kotlin.programmers.lv01 /** * * https://school.programmers.co.kr/learn/courses/30/lessons/12948 * * 문제 설명 * 프로그래머스 모바일은 개인정보 보호를 위해 고지서를 보낼 때 고객들의 전화번호의 일부를 가립니다. * 전화번호가 문자열 phone_number로 주어졌을 때, 전화번호의 뒷 4자리를 제외한 나머지 숫자를 전부 *으로 가린 문자열을 리턴하는 함수, solution을 완성해주세요. * * 제한 조건 * phone_number는 길이 4 이상, 20이하인 문자열입니다. * 입출력 예 * phone_number return * "01033334444" "*******4444" * "027778888" "*****8888" */ fun main() { solution("01033334444") solution("027778888") } private fun solution(phone_number: String): String { var answer = "" val numLength = phone_number.length for(i in 1..numLength - 4) { answer += "*" } val result = answer + phone_number.subSequence(numLength - 4, numLength) return result } private fun secondSolution(phone_number: String): String { return "${"".padStart(phone_number.length - 4, '*')}${phone_number.takeLast(4)}" }
[ { "class_path": "boris920308__HoOne__8881468/main/kotlin/programmers/lv01/Lv1_12948_hide_numberKt.class", "javap": "Compiled from \"Lv1_12948_hide_number.kt\"\npublic final class main.kotlin.programmers.lv01.Lv1_12948_hide_numberKt {\n public static final void main();\n Code:\n 0: ldc #8...
frankschmitt__advent_of_code__69f2dad/2017/13-packet_scanners/src/main/kotlin/de/qwhon/aoc/PacketScanner.kt
package de.qwhon.aoc import java.io.File /** A simple helper class for keeping track of scanners. * */ data class ScannerRecord(val depth: Int, val range: Int) /** parse the input file, and return a List of scanner records. * */ fun parseInputFile(fileName: String): List<ScannerRecord> { val file = File(fileName) val tmp = HashMap<Int, Int>() file.forEachLine { val contents = it.split(": ") tmp[contents[0].toInt()] = contents[1].toInt() } return tmp.map { ScannerRecord(depth = it.key, range = it.value) } } /** compute the minimum delay necessary to pass through the firewall without getting caught. * we return the first number that fulfills: * for every scanner N: scanner_N is not at position 0 at timestamp (depth_N + delay) * since (depth_N + delay) is the timestamp at which our packet reaches level N, this solves our puzzle */ fun minimumDelayForInputFile(fileName: String): Int { val input = parseInputFile(fileName) return generateSequence(seed = 0) { i -> i + 1 } .find { i -> input.none { scanner -> (i + scanner.depth) % ((scanner.range - 1) * 2) == 0 } }!! } /** compute the severity of the violations for passing through the firewall without initial delay. * we compute the severity as: * for every scanner N: violation occurs iff scanner_N is at position 0 at timestamp (depth_N + delay) * since (depth_N + delay) is the timestamp at which our packet reaches level N, this returns all scanners * that catch our packet. Computing the severity is then a simple sum of depth*range, which can be computed by a fold. */ fun severityOfViolationsForInputFile(fileName: String): Int { val input = parseInputFile(fileName) return input.filter { scanner -> scanner.depth % ((scanner.range - 1) * 2) == 0 } .fold(initial = 0) { accu, scanner -> accu + scanner.depth * scanner.range } }
[ { "class_path": "frankschmitt__advent_of_code__69f2dad/de/qwhon/aoc/PacketScannerKt.class", "javap": "Compiled from \"PacketScanner.kt\"\npublic final class de.qwhon.aoc.PacketScannerKt {\n public static final java.util.List<de.qwhon.aoc.ScannerRecord> parseInputFile(java.lang.String);\n Code:\n 0...
davidcurrie__advent-of-code-2022__0e0cae3/src/day5/Day5.kt
package day5 import java.io.File fun main() { val parts = File("src/day5/input.txt").readText(Charsets.UTF_8).split("\n\n") val lines = parts[0].split("\n") val length = (lines.last().length + 1) / 4 val columns = List(length) { mutableListOf<Char>() } lines.dropLast(1).forEach { line -> for (i in 0 until length) { val char = line[(i * 4) + 1] if (char != ' ') { columns[i].add(char) } } } val pattern = "move (\\d*) from (\\d*) to (\\d*)".toRegex() val partOne = columns.map { column -> column.map { it }.toMutableList() } parts[1].split("\n").dropLast(1).forEach { line -> val numbers = pattern.find(line)!!.groupValues.drop(1).map(String::toInt) for (i in 0 until numbers[0]) { partOne[numbers[2]-1].add(0, partOne[numbers[1]-1].removeAt(0)) } } println(partOne.map { column -> column.first() }.joinToString("")) val partTwo = columns.map { column -> column.map { it }.toMutableList() } parts[1].split("\n").dropLast(1).forEach { line -> val numbers = pattern.find(line)!!.groupValues.drop(1).map(String::toInt) for (i in 0 until numbers[0]) { partTwo[numbers[2]-1].add(0, partTwo[numbers[1]-1].removeAt(numbers[0] - i - 1)) } } println(partTwo.map { column -> column.first() }.joinToString("")) }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day5/Day5Kt.class", "javap": "Compiled from \"Day5.kt\"\npublic final class day5.Day5Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day23/Day23.kt
package day23 import java.io.File import java.util.* import kotlin.math.max import kotlin.math.min fun main() { var elves = File("src/day23/input.txt").readLines().mapIndexed { row, line -> line.toList().mapIndexed { column, char -> if (char == '#') Pair(column, row) else null }.filterNotNull() }.flatten() val directions = listOf( listOf(Pair(0, -1), Pair(-1, -1), Pair(1, -1)), listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)), listOf(Pair(-1, 0), Pair(-1, -1), Pair(-1, 1)), listOf(Pair(1, 0), Pair(1, -1), Pair(1, 1)) ) val deltas = directions.flatten().toSet() var round = 1 while(true) { val proposedMoves = elves.map { elf -> val neighbouringElves = deltas.map { delta -> elf + delta }.filter { location -> location in elves } if (neighbouringElves.isEmpty()) { elf } else { val direction = directions.indices.map { i -> directions[(i + round - 1).mod(directions.size)] } .firstOrNull { direction -> direction.none { d -> (elf + d) in neighbouringElves } } elf + (direction?.first() ?: Pair(0, 0)) } } val frequencies = proposedMoves.groupingBy { it }.eachCount() val newElves = elves.indices.map { i -> if (frequencies[proposedMoves[i]] == 1) proposedMoves[i] else elves[i] } if (elves == newElves) { println(round) break } elves = newElves if (round == 10) { val (topLeft, bottomRight) = rectangle(elves) val area = (1 + bottomRight.first - topLeft.first) * (1 + bottomRight.second - topLeft.second) val empty = area - elves.size println(empty) } round++ } } fun printElves(elves: List<Pair<Int, Int>>) { val (topLeft, bottomRight) = rectangle(elves) for (row in topLeft.second .. bottomRight.second) { for (column in topLeft.first .. bottomRight.first) { print(if (Pair(column, row) in elves) '#' else '.') } println() } println() } private fun rectangle(elves: List<Pair<Int, Int>>): Pair<Pair<Int, Int>, Pair<Int, Int>> { val topLeft = elves.reduce { a, b -> Pair(min(a.first, b.first), min(a.second, b.second)) } val bottomRight = elves.reduce { a, b -> Pair(max(a.first, b.first), max(a.second, b.second)) } return Pair(topLeft, bottomRight) } operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return Pair(first + other.first, second + other.second) }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day23/Day23Kt$main$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class day23.Day23Kt$main$$inlined$groupingBy$1 implements kotlin.collections.Grouping<kotlin.Pair<? extends java.lang.Integer, ? extends java....
davidcurrie__advent-of-code-2022__0e0cae3/src/day24/Day24.kt
package day24 import java.io.File import java.util.* fun main() { val valley = Valley.parse(File("src/day24/input.txt").readLines()) val there = solve(valley, Valley.START, valley.finish) println(there.first) val back = solve(there.second, valley.finish, Valley.START) val thereAgain = solve(back.second, Valley.START, valley.finish) println(there.first + back.first + thereAgain.first) } fun solve(valley: Valley, from: Pair<Int, Int>, to: Pair<Int, Int>): Pair<Int, Valley> { val maps = mutableListOf(valley) val visited = mutableSetOf<Pair<Int, Pair<Int, Int>>>() val queue = PriorityQueue<Pair<Int, Pair<Int, Int>>>( compareBy { it.first + (to.first - it.second.first) + (to.second - it.second.second) } ) queue.add(Pair(0, from)) while (queue.isNotEmpty()) { val pair = queue.poll() if (pair in visited) continue visited.add(pair) val (minute, location) = pair if (location == to) { return Pair(minute, maps[minute]) } val nextMinute = minute + 1 if (maps.size == nextMinute) { maps.add(maps.last().next()) } val map = maps[nextMinute] queue.addAll(map.options(location).map { Pair(minute + 1, it) }) } throw IllegalStateException("End never reached") } data class Valley(val width: Int, val height: Int, val blizzardsAndWalls: Map<Pair<Int, Int>, List<Char>>) { val finish = Pair(width - 2, height - 1) companion object { val START = Pair(1, 0) fun parse(lines: List<String>): Valley { val blizzardWalls = lines.mapIndexed { row, line -> line.mapIndexed { column, char -> Pair(column, row) to listOf(char) }.filter { '.' !in it.second }.toMap() }.reduce { a, b -> a + b } return Valley(lines.first().length, lines.size, blizzardWalls) } } fun print(location: Pair<Int, Int>): String { val buffer = StringBuffer() for (row in (0 until height)) { for (column in (0 until width)) { val c = Pair(column, row) if (c == location) { buffer.append("E") } else { val b = blizzardsAndWalls[c] ?: emptyList() buffer.append(if (b.isEmpty()) '.' else if (b.size == 1) b.first() else b.size) } } buffer.appendLine() } return buffer.toString() } fun next(): Valley { return Valley(width, height, blizzardsAndWalls.map { (c, l) -> l.map { d -> Pair(c, d) } }.flatten().map { p -> Pair(when (p.second) { '^' -> Pair(p.first.first, if (p.first.second == 1) (height - 2) else (p.first.second - 1)) '>' -> Pair(if (p.first.first == width - 2) 1 else (p.first.first + 1), p.first.second) 'v' -> Pair(p.first.first, if (p.first.second == height - 2) 1 else (p.first.second + 1)) '<' -> Pair(if (p.first.first == 1) (width - 2) else (p.first.first - 1), p.first.second) '#' -> p.first else -> throw IllegalStateException("Unknown direction ${p.second}") }, p.second) }.fold(mutableMapOf()) { m, p -> m[p.first] = (m[p.first] ?: emptyList()) + p.second; m }) } fun options(location: Pair<Int, Int>): List<Pair<Int, Int>> { val deltas = listOf(Pair(0, 0), Pair(0, -1), Pair(1, 0), Pair(0, 1), Pair(-1, 0)) return deltas.map { d -> Pair(location.first + d.first, location.second + d.second) } .filter { c -> (c.first > 0 && c.first < width - 1 && c.second > 0 && c.second < height - 1) || c == finish || c == START } .filterNot { c -> c in blizzardsAndWalls } } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day24/Day24Kt$solve$$inlined$compareBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class day24.Day24Kt$solve$$inlined$compareBy$1<T> implements java.util.Comparator {\n final kotlin.Pair $to$inlined;\n\n public day24.Day24Kt...
davidcurrie__advent-of-code-2022__0e0cae3/src/day12/Day12.kt
package day12 import java.io.File fun main() { val grid = File("src/day12/input.txt").readLines().mapIndexed { y, line -> line.mapIndexed { x, c -> Pair(x, y) to c } }.flatten().toMap() val start = grid.filter { it.value == 'S' }.map { it.key }.first() val end = grid.filter { it.value == 'E' }.map { it.key }.first() val lowest = grid.filter { height(it.value) == 0 }.map { it.key }.toSet() println(solve(start, setOf(end), grid) { last, next -> next <= last + 1 }) println(solve(end, lowest, grid) { last, next -> next >= last - 1 }) } private fun solve( start: Pair<Int, Int>, end: Set<Pair<Int, Int>>, grid: Map<Pair<Int, Int>, Char>, validTransition: (Int, Int) -> Boolean ): Int { val directions = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) val visited = mutableSetOf<Pair<Int, Int>>() val stack = mutableListOf(listOf(start)) while (stack.isNotEmpty()) { val path = stack.removeAt(0) if (path.last() in end) { return (path.size - 1) } if (path.last() in visited) { continue } visited.add(path.last()) val options = directions .asSequence() .map { direction -> Pair(path.last().first + direction.first, path.last().second + direction.second) } .filter { next -> next in grid.keys } .filter { next -> validTransition(height(grid[path.last()]!!), height(grid[next]!!)) } .map { next -> path + next } .toList() stack.addAll(options) } throw IllegalStateException("No solution") } fun height(c: Char): Int { return when (c) { 'S' -> 0 'E' -> 25 else -> c - 'a' } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day12/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class day12.Day12Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day15/Day15.kt
package day15 import java.io.File import kotlin.math.abs fun main() { val regexp = Regex("Sensor at x=(-?\\d*), y=(-?\\d*): closest beacon is at x=(-?\\d*), y=(-?\\d*)") val sensors = File("src/day15/input.txt").readLines() .map { regexp.matchEntire(it)!!.groupValues } .map { values -> Sensor(Pair(values[1].toInt(), values[2].toInt()), Pair(values[3].toInt(), values[4].toInt())) }.toSet() val row = 2000000 // 10 println(sensors.map { it.excludes(row) }.reduce().sumOf { it.last - it.first }) val max = 4000000 // 20 // Part 2 using the fact everything must be excluded by a single range in every other row for (row in 0 .. max) { val exclusions = sensors.map { sensor -> sensor.excludes(row) }.reduce() if (exclusions.size > 1) { val column = (0..max).firstOrNull { exclusions.none { exclusion -> exclusion.contains(it) } } ?: continue println(column * 4000000L + row) break } } // Part 2 using the fact that the beacon must be just outside a sensor's exclusion range for (row in 0 .. max) { val exclusions = sensors.map { sensor -> sensor.excludes(row) } val options = exclusions.map { range -> listOf(range.first - 1, range.last + 1) }.flatten().filter { it in 0..max } val column = options.firstOrNull { option -> exclusions.none { exclusion -> exclusion.contains(option) } } if (column != null) { println(column * 4000000L + row) break } } } fun List<IntRange>.reduce(): List<IntRange> { if (size < 2) return this for (i in 0 until size - 1) { for (j in i + 1 until size) { if (this[i].overlap(this[j]) || this[i].adjacent(this[j])) { val result = this.subList(0, i).toMutableList() result.addAll(this.subList(i + 1, j)) result.addAll(this.subList(j + 1, size)) result.addAll(this[i].merge(this[j])) return result.reduce() } } } return this } fun IntRange.overlap(other: IntRange): Boolean { return first <= other.last && last >= other.first } fun IntRange.adjacent(other: IntRange): Boolean { return first == other.last + 1 || last == other.first - 1 } fun IntRange.merge(other: IntRange): List<IntRange> { return if (overlap(other) || adjacent(other)) listOf(IntRange(kotlin.math.min(first, other.first), kotlin.math.max(last, other.last))) else listOf(this, other) } data class Sensor(val sensor: Pair<Int, Int>, val beacon: Pair<Int, Int>) { private val distance = abs(sensor.first - beacon.first) + abs(sensor.second - beacon.second) fun excludes(row: Int): IntRange { val distanceFromRow = abs(sensor.second - row) val difference = distance - distanceFromRow if (difference < 0) return IntRange.EMPTY return (sensor.first - difference .. sensor.first + difference) } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day15/Day15Kt.class", "javap": "Compiled from \"Day15.kt\"\npublic final class day15.Day15Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day14/Day14.kt
package day14 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val rocks = File("src/day14/input.txt").readLines().map { line -> Rock(line.split(" -> ").map { coord -> coord.split(",").let { Pair(it[0].toInt(), it[1].toInt()) } }) } println(solve(rocks, false)) println(solve(rocks, true)) } fun solve(rocks: List<Rock>, floor: Boolean): Int { val rocksBoundary = rocks.map { it.boundary }.reduce(Box::merge) val settledSand = mutableSetOf<Pair<Int, Int>>() val start = Pair(500, 0) outer@ while (true) { var sand = start while (true) { sand = listOf(Pair(0, 1), Pair(-1, 1), Pair(1, 1)).map { delta -> sand + delta } .firstOrNull { option -> option !in settledSand && (!rocksBoundary.contains(option) || rocks.none { rock -> rock.hit(option) }) && (!floor || option.second != rocksBoundary.bottom + 2) } ?: break if (!floor && sand.second > rocksBoundary.bottom) break@outer } settledSand.add(sand) if (sand == start) break } return settledSand.size } operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return Pair(first + other.first, second + other.second) } data class Box(val a: Pair<Int, Int>, val b: Pair<Int, Int>) { private val topLeft = Pair(min(a.first, b.first), min(a.second, b.second)) private val bottomRight = Pair(max(a.first, b.first), max(a.second, b.second)) val bottom = bottomRight.second fun contains(coord: Pair<Int, Int>): Boolean = coord.first >= topLeft.first && coord.first <= bottomRight.first && coord.second >= topLeft.second && coord.second <= bottomRight.second fun merge(other: Box): Box = Box( Pair(min(topLeft.first, other.topLeft.first), min(topLeft.second, other.topLeft.second)), Pair(max(bottomRight.first, other.bottomRight.first), max(bottomRight.second, other.bottomRight.second)) ) } data class Rock(val coords: List<Pair<Int, Int>>) { private val boxes = coords.zipWithNext().map { pair -> Box(pair.first, pair.second) } val boundary = boxes.reduce(Box::merge) fun hit(coord: Pair<Int, Int>): Boolean { return boundary.contains(coord) && boxes.any { it.contains(coord) } } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day14/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class day14.Day14Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day13/Day13.kt
package day13 import java.io.File fun main() { val pairs = File("src/day13/input.txt").readText().split("\n\n") .map { it.split("\n") } .map { listOf(parse(it[0]), parse(it[1])) } println(pairs.mapIndexed { index, pair -> if (check(pair[0], pair[1])!!) index + 1 else 0 }.sumOf { it }) val dividers = listOf(mutableListOf(mutableListOf(2)), mutableListOf(mutableListOf(6))) val packets = pairs.flatten().toMutableList() packets.addAll(dividers) packets.sortWith { left, right -> if (check(left, right)!!) -1 else 1 } println(packets.mapIndexed { i, p -> if (p in dividers) i + 1 else 1 }.fold(1, Int::times)) } fun check(left: MutableList<*>, right: MutableList<*>): Boolean? { for (i in left.indices) { var l = left[i] if (i == right.size) return false var r = right[i] if (l is Int && r is Int) { if (l < r) { return true } else if (l > r) { return false } } else { if (l is Int) { l = mutableListOf(l) } if (r is Int) { r = mutableListOf(r) } if (l is MutableList<*> && r is MutableList<*>) { val check = check(l, r) if (check != null) return check } } } if (right.size > left.size) return true return null } fun parse(s: String): MutableList<*> { val stack = mutableListOf<MutableList<Any>>() var n: Int? = null var result: MutableList<Any>? = null for (c in s) { when (c) { '[' -> { val list = mutableListOf<Any>() if (stack.isEmpty()) { result = list } else { stack.last().add(list) } stack.add(list) n = null } ']' -> { if (n != null) { stack.last().add(n) } n = null stack.removeLast() } ',' -> { if (n != null) { stack.last().add(n) } n = null } else -> { n = if (n != null) (10 * n) else 0 n += c.toString().toInt() } } } return result!! }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day13/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class day13.Day13Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day22/Day22.kt
package day22 import java.io.File import kotlin.reflect.KFunction3 fun main() { val input = File("src/day22/input.txt").readText().split("\n\n") val tiles = mutableSetOf<Pair<Int, Int>>() val walls = mutableSetOf<Pair<Int, Int>>() input[0].split("\n").forEachIndexed { row, s -> s.toList().forEachIndexed { column, c -> when (c) { '.' -> tiles.add(Pair(column + 1, row + 1)) '#' -> walls.add(Pair(column + 1, row + 1)) } } } val directions = input[1].toList().fold(emptyList<Any>()) { acc, c -> when (c) { 'L' -> acc + 'L' 'R' -> acc + 'R' else -> if (acc.isNotEmpty() && acc.last() is Int) (acc.dropLast(1) + ((acc.last() as Int * 10) + c.toString() .toInt())) else (acc + c.toString().toInt()) } } println(solve(tiles, walls, directions, ::flatWrap)) println(solve(tiles, walls, directions, ::cubeWrap)) } private fun solve( tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, directions: List<Any>, wrap: KFunction3<Set<Pair<Int, Int>>, Set<Pair<Int, Int>>, State, State> ): Int { var state = State(tiles.filter { it.second == 1 }.minByOrNull { it.first }!!, 0) val deltas = listOf(Pair(1, 0), Pair(0, 1), Pair(-1, 0), Pair(0, -1)) directions.forEach { direction -> when (direction) { 'L' -> state = State(state.coord, (state.facing - 1).mod(deltas.size)) 'R' -> state = State(state.coord, (state.facing + 1).mod(deltas.size)) else -> for (i in 1..direction as Int) { var nextState = State( Pair( state.coord.first + deltas[state.facing].first, state.coord.second + deltas[state.facing].second ), state.facing ) if (nextState.coord !in (walls + tiles)) { nextState = wrap(tiles, walls, nextState) } if (nextState.coord in walls) break state = nextState } } } return state.password() } data class State(val coord: Pair<Int, Int>, val facing: Int) { fun password() = 4 * coord.first + 1000 * coord.second + facing } private fun flatWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State { return State(when (state.facing) { 0 -> (tiles + walls).filter { it.second == state.coord.second }.minByOrNull { it.first }!! 1 -> (tiles + walls).filter { it.first == state.coord.first }.minByOrNull { it.second }!! 2 -> (tiles + walls).filter { it.second == state.coord.second }.maxByOrNull { it.first }!! 3 -> (tiles + walls).filter { it.first == state.coord.first }.maxByOrNull { it.second }!! else -> throw IllegalStateException() }, state.facing ) } private fun cubeWrap(tiles: Set<Pair<Int, Int>>, walls: Set<Pair<Int, Int>>, state: State): State { return when (state.facing) { 0 -> { when (state.coord.second) { in 1..50 -> { State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2) } in 51..100 -> { State((tiles + walls).filter { it.first == 50 + state.coord.second }.maxByOrNull { it.second }!!, 3) } in 101..150 -> { State((tiles + walls).filter { it.second == 151 - state.coord.second }.maxByOrNull { it.first }!!, 2) } else -> { State((tiles + walls).filter { it.first == state.coord.second - 100 }.maxByOrNull { it.second }!!, 3) } } } 1 -> { when (state.coord.first) { in 1..50 -> { State((tiles + walls).filter { it.first == 100 + state.coord.first }.minByOrNull { it.second }!!, 1) } in 51..100 -> { State((tiles + walls).filter { it.second == 100 + state.coord.first }.maxByOrNull { it.first }!!, 2) } else -> { State((tiles + walls).filter { it.second == state.coord.first - 50 }.maxByOrNull { it.first }!!, 2) } } } 2 -> { when (state.coord.second) { in 1..50 -> { State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0) } in 51..100 -> { State((tiles + walls).filter { it.first == state.coord.second - 50 }.minByOrNull { it.second }!!, 1) } in 101..150 -> { State((tiles + walls).filter { it.second == 151 - state.coord.second }.minByOrNull { it.first }!!, 0) } else -> { State((tiles + walls).filter { it.first == state.coord.second - 100 }.minByOrNull { it.second }!!, 1) } } } 3 -> { when (state.coord.first) { in 1..50 -> { State((tiles + walls).filter { it.second == 50 + state.coord.first }.minByOrNull { it.first }!!, 0) } in 51..100 -> { State((tiles + walls).filter { it.second == 100 + state.coord.first }.minByOrNull { it.first }!!, 0) } else -> { State((tiles + walls).filter { it.first == state.coord.first - 100 }.maxByOrNull { it.second }!!, 3) } } } else -> throw IllegalStateException() } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day22/Day22Kt.class", "javap": "Compiled from \"Day22.kt\"\npublic final class day22.Day22Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day9/Day9.kt
package day9 import java.io.File import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign fun main() { val input = File("src/day9/input.txt").readLines() .map { line -> line.split(" ") } .map { parts -> Pair(parts[0], parts[1].toInt()) } .toList() println(solve(input, 2)) println(solve(input, 10)) } fun solve(input: List<Pair<String, Int>>, knots: Int): Int { val rope = MutableList(knots) { Pair(0, 0) } val visited = mutableSetOf<Pair<Int, Int>>() visited.add(rope.last()) val deltas = mapOf("U" to Pair(0, 1), "D" to Pair(0, -1), "L" to Pair(-1, 0), "R" to Pair(1, 0)) input.forEach { pair -> for (i in 1..pair.second) { val delta = deltas[pair.first]!! rope[0] = Pair(rope[0].first + delta.first, rope[0].second + delta.second) for (j in 1 until knots) { if (abs(rope[j - 1].second - rope[j].second) == 2 || abs(rope[j - 1].first - rope[j].first) == 2) { rope[j] = Pair( rope[j].first + sign(rope[j - 1].first - rope[j].first), rope[j].second + sign(rope[j - 1].second - rope[j].second) ) } } visited.add(rope.last()) } } return visited.size } fun sign(input: Int): Int { return sign(input.toDouble()).toInt() } fun outputRope(rope: MutableList<Pair<Int, Int>>) { for (j in max(0, rope.maxOf { it.second }) downTo min(0, rope.minOf { it.second })) { for (i in min(0, rope.minOf { it.first })..max(0, rope.maxOf { it.first })) { var output = "." if (i == 0 && j == 0) { output = "s" } for (k in rope.indices) { if (i == rope[k].first && j == rope[k].second) { output = when (k) { 0 -> "H" rope.size - 1 -> "T" else -> k.toString() } break } } print(output) } println() } println() }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day9/Day9Kt.class", "javap": "Compiled from \"Day9.kt\"\npublic final class day9.Day9Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day8/Day8.kt
package day8 import java.io.File fun main() { val lines = File("src/day8/input.txt").readLines() val trees = mutableMapOf<Pair<Int, Int>, Int>() for (j in lines.indices) { for (i in 0 until lines[j].length) { trees[Pair(i, j)] = lines[j][i].toString().toInt() } } val visible = mutableSetOf<Pair<Int, Int>>() for (j in lines.indices) { visible.addAll(visible(trees, Pair(0, j), Pair(1, 0))) visible.addAll(visible(trees, Pair(lines[j].length - 1, j), Pair(-1, 0))) } for (i in 0 until lines[0].length) { visible.addAll(visible(trees, Pair(i, 0), Pair(0, 1))) visible.addAll(visible(trees, Pair(i, lines.size - 1), Pair(0, -1))) } println(visible.size) println(trees.keys.maxOfOrNull { scenicScore(trees, it) }) } fun scenicScore(trees: Map<Pair<Int, Int>, Int>, tree: Pair<Int, Int>): Int { val deltas = listOf(Pair(0, 1), Pair(1, 0), Pair(-1, 0), Pair(0, -1)) var total = 1 for (delta in deltas) { var coord = tree var score = 0 while (true) { coord = Pair(coord.first + delta.first, coord.second + delta.second) if (coord in trees.keys) { if (trees[coord]!! < trees[tree]!!) { score++ } else { score++ break } } else { break } } total *= score } return total } fun visible(trees: Map<Pair<Int, Int>, Int>, start: Pair<Int, Int>, delta: Pair<Int, Int>) : Set<Pair<Int, Int>> { val visible = mutableSetOf<Pair<Int, Int>>() visible.add(start) var height = trees[start]!! var coord = start while (true) { coord = Pair(coord.first + delta.first, coord.second + delta.second) if (coord !in trees.keys) { break } if (trees[coord]!! > height) { height = trees[coord]!! visible.add(coord) } } return visible }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day8/Day8Kt.class", "javap": "Compiled from \"Day8.kt\"\npublic final class day8.Day8Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day18/Day18.kt
package day18 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val lavas = File("src/day18/input.txt").readLines().map { it.split(',') }.map { Triple(it[0].toInt(), it[1].toInt(), it[2].toInt()) } val deltas = listOf( Triple(1, 0, 0), Triple(-1, 0, 0), Triple(0, 1, 0), Triple(0, -1, 0), Triple(0, 0, 1), Triple(0, 0, -1) ) println(lavas.sumOf { lava -> deltas.map { delta -> lava + delta }.count { other -> other !in lavas } }) val min = lavas.reduce { t1, t2 -> Triple(min(t1.first, t2.first), min(t1.second, t2.second), min(t1.third, t2.third))} val max = lavas.reduce { t1, t2 -> Triple(max(t1.first, t2.first), max(t1.second, t2.second), max(t1.third, t2.third))} val pockets = mutableListOf<Triple<Int, Int, Int>>() val nonPockets = mutableListOf<Triple<Int, Int, Int>>() for (x in min.first .. max.first) { for (y in min.second .. max.second) { loop@ for (z in min.third .. max.third) { val start = Triple(x, y, z) if (start in lavas || start in pockets || start in nonPockets) continue val potentialPocket = mutableListOf(start) val stack = mutableListOf(start) while (stack.isNotEmpty()) { val next = stack.removeAt(0) val surrounding = deltas.map { delta -> next + delta }.filter { it !in lavas }.filter { it !in potentialPocket } val reachedEdge = surrounding.any { it.first <= min.first || it.second <= min.second || it.third <= min.third || it.first >= max.first || it.second >= max.second || it.third >= max.third } if (reachedEdge) { nonPockets.addAll(potentialPocket) continue@loop } stack.addAll(surrounding) potentialPocket.addAll(surrounding) } pockets.addAll(potentialPocket) // it is a pocket! } } } println(lavas.sumOf { lava -> deltas.map { delta -> lava + delta }.count { other -> other !in lavas && other !in pockets } }) } private operator fun Triple<Int, Int, Int>.plus(other: Triple<Int, Int, Int>) = Triple(first + other.first, second + other.second, third + other.third)
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day18/Day18Kt.class", "javap": "Compiled from \"Day18.kt\"\npublic final class day18.Day18Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day20/Day20.kt
package day20 import java.io.File fun main() { val input = File("src/day20/input.txt").readLines().map { it.toLong() } println(grove(mix(input.mapIndexed { index, delta -> index to delta }.toMutableList()))) println(grove((1..10).fold(input.mapIndexed { index, delta -> index to delta * 811589153L } .toMutableList()) { positions, _ -> mix(positions) })) } fun mix(positions: MutableList<Pair<Int, Long>>): MutableList<Pair<Int, Long>> { positions.indices.forEach { index -> val from = positions.indexOfFirst { (initialIndex) -> initialIndex == index } val value = positions[from] val delta = value.second if (delta != 0L) { positions.removeAt(from) val to = (from + delta).mod(positions.size) positions.add(to, value) } } return positions } fun grove(positions: List<Pair<Int, Long>>): Long { val zeroPosition = positions.indexOfFirst { (_, delta) -> delta == 0L } return listOf(1000, 2000, 3000).sumOf { positions[(zeroPosition + it).mod(positions.size)].second } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day20/Day20Kt.class", "javap": "Compiled from \"Day20.kt\"\npublic final class day20.Day20Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day16/Day16.kt
package day16 import java.io.File import kotlin.math.max fun main() { val regexp = Regex("Valve (.*) has flow rate=(.*); tunnels? leads? to valves? (.*)") val valves = File("src/day16/input.txt").readLines() .map { regexp.matchEntire(it)!!.groupValues }.associate { values -> values[1] to Valve(values[1], values[2].toInt(), values[3].split(", ")) } val distances = mutableMapOf<Pair<String, String>, Int>() valves.forEach { (from, valve) -> valves.keys.forEach { to -> distances[Pair(from, to)] = if (from == to) 0 else if (to in valve.leadsTo) 1 else 1000 } } for (k in valves.keys) { for (i in valves.keys) { for (j in valves.keys) { if (distances[Pair(i, j)]!! > (distances[Pair(i, k)]!! + distances[Pair(k, j)]!!)) { distances[Pair(i, j)] = distances[Pair(i, k)]!! + distances[Pair(k, j)]!! } } } } println(solve(valves, distances, 30)) val nonZeroValves = valves.values.filter { it.rate > 0 }.map { it.name } var maxRate = 0L for (i in 0..nonZeroValves.size / 2) { combinations(nonZeroValves, i).forEach { myValves -> val myRate = solve(valves.filter { (k, _) -> k == "AA" || k in myValves }, distances, 26) val elephantRate = solve(valves.filter { (k, _) -> k == "AA" || k !in myValves }, distances, 26) maxRate = max(maxRate, myRate + elephantRate) } } println(maxRate) } fun combinations(values: List<String>, size: Int): Set<Set<String>> { val result = mutableSetOf<Set<String>>() combinations(values, ArrayList(), result, size, 0) return result } fun combinations(values: List<String>, current: MutableList<String>, accumulator: MutableSet<Set<String>>, size: Int, pos: Int) { if (current.size == size) { accumulator.add(current.toSet()) return } for (i in pos..values.size - size + current.size) { current.add(values[i]) combinations(values, current, accumulator, size, i + 1) current.removeAt(current.size - 1) } } fun solve(valves: Map<String, Valve>, distances: Map<Pair<String, String>, Int>, maxTime: Int): Long { val stack = mutableListOf(Path(0, 0, listOf("AA"))) val visited = mutableMapOf<Set<String>, Long>() var maxRate = 0L while (stack.isNotEmpty()) { val path = stack.removeAt(0) if (path.time > maxTime) continue if ((visited[path.turnedOn.toSet()] ?: 0) > path.totalRate) continue visited[path.turnedOn.toSet()] = path.totalRate val currentName = path.turnedOn.last() maxRate = max(maxRate, path.totalRate) valves.values.filter { it.rate != 0 }.filter { it.name !in path.turnedOn }.forEach { valve -> val distance = distances[Pair(currentName, valve.name)]!! val turnedOnAt = path.time + distance + 1 stack.add(Path(turnedOnAt, path.totalRate + (valve.rate * (maxTime - turnedOnAt)), path.turnedOn + valve.name)) } } return maxRate } data class Valve(val name: String, val rate: Int, val leadsTo: List<String>) data class Path(val time: Int, val totalRate: Long, val turnedOn: List<String>)
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day16/Day16Kt.class", "javap": "Compiled from \"Day16.kt\"\npublic final class day16.Day16Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day11/Day11.kt
package day11 import java.io.File fun main() { println(solve(readInput(), 20, 3)) println(solve(readInput(), 10000, 1)) } private fun readInput(): List<Monkey> { val regex = """Monkey \d*: Starting items: (.*) Operation: new = (.*) Test: divisible by (\d*) If true: throw to monkey (\d*) If false: throw to monkey (\d*)""".toRegex() return File("src/day11/input.txt").readText().split("\n\n").map { val values = regex.matchEntire(it)!!.groupValues Monkey( values[1].split(", ").map(String::toLong).toMutableList(), values[2].split(" "), values[3].toLong(), values[4].toInt(), values[5].toInt() ) }.toList() } fun solve(monkeys: List<Monkey>, rounds: Int, relief: Int): Long { val common = monkeys.fold(1L) { acc, m -> acc * m.divisibleBy } for (round in 1 .. rounds) { for (i in monkeys.indices) { monkeys[i].process(relief, common).forEach { pair -> monkeys[pair.first].items.add(pair.second) } } } return monkeys.map { it.inspects }.sorted().reversed().let { (first, second) -> first * second } } class Monkey(var items: MutableList<Long>, private val test: List<String>, val divisibleBy: Long, private val ifTrue: Int, private val ifFalse: Int) { var inspects = 0L fun process(relief: Int, common: Long): List<Pair<Int, Long>> { val result = items.map { item -> val b = if (test[2] == "old") item else test[2].toLong() val testResult: Long = if (test[1] == "*") item * b else item + b val afterRelief = (testResult / relief) % common Pair(if (afterRelief % divisibleBy == 0L) ifTrue else ifFalse, afterRelief) }.toList() inspects += items.size items.clear() return result } }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day11/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11Kt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInput:()Ljava/util/List;\n 3: bipush ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day17/Day17.kt
package day17 import java.io.File fun main() { val jetPattern = File("src/day17/input.txt").readLines().first() val rockShapes = listOf( listOf(Pair(0,0), Pair(1,0), Pair(2,0), Pair(3,0)), listOf(Pair(0,1), Pair(1,0), Pair(1,1), Pair(1,2), Pair(2,1)), listOf(Pair(0,0), Pair(1,0), Pair(2,0), Pair(2,1), Pair(2,2)), listOf(Pair(0,0), Pair(0,1), Pair(0,2), Pair(0,3)), listOf(Pair(0,0), Pair(0,1), Pair(1,0), Pair(1,1)) ) var jetPatternIndex = 0 val stoppedRocks = mutableSetOf<Pair<Long, Long>>() val heights = mutableListOf<Long>() val cycleHeights = mutableListOf<Long>() val cycleRocks = mutableListOf<Long>() for (rock in 0 .. 1_000_000_000_000) { val rockShapeIndex = (rock % rockShapes.size).toInt() val rockShape = rockShapes[rockShapeIndex] var coord = Pair(2L, 3 + (stoppedRocks.maxOfOrNull { it.second + 1 } ?: 0)) while (true) { val jet = jetPattern[jetPatternIndex] jetPatternIndex = (jetPatternIndex + 1) % jetPattern.length val acrossCoord = if (jet == '>') { Pair(coord.first + 1L, coord.second) } else { Pair(coord.first - 1L, coord.second) } if (allowed(rockCoords(acrossCoord, rockShape), stoppedRocks)) { coord = acrossCoord } val downCoord = Pair(coord.first, coord.second - 1) if (allowed(rockCoords(downCoord, rockShape), stoppedRocks)) { coord = downCoord } else { stoppedRocks.addAll(rockCoords(coord, rockShape)) break } } val height = stoppedRocks.maxOf { it.second } + 1 heights.add(height) if (rock == 2022L - 1) println(height) if (jetPatternIndex == 0) { cycleHeights.add(height) cycleRocks.add(rock) } if (cycleHeights.size > 3 && (cycleHeights[cycleHeights.size - 1] - cycleHeights[cycleHeights.size - 2]) == (cycleHeights[cycleHeights.size - 2] - cycleHeights[cycleHeights.size - 3])) break } val cycleHeightDiff = cycleHeights[cycleHeights.size - 1] - cycleHeights[cycleHeights.size - 2] val cycleRockDiff = cycleRocks[cycleRocks.size - 1] - cycleRocks[cycleRocks.size - 2] val cycleStarts = cycleRocks[0] + 1 val remainder = (1_000_000_000_000 - cycleStarts) % cycleRockDiff val remainderHeight = heights[(cycleStarts + remainder - 1).toInt()] println(remainderHeight + (((1_000_000_000_000 - cycleStarts) / cycleRockDiff) * cycleHeightDiff)) } fun allowed(rockCoords: List<Pair<Long, Long>>, stoppedRocks: Set<Pair<Long, Long>>): Boolean { rockCoords.forEach { if (it.second < 0) return false if (it.first < 0) return false if (it.first > 6) return false if (it in stoppedRocks) return false } return true } fun rockCoords(coord: Pair<Long, Long>, rockShape: List<Pair<Int, Int>>): List<Pair<Long, Long>> = rockShape.map { Pair(coord.first + it.first, coord.second + it.second) }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day17/Day17Kt.class", "javap": "Compiled from \"Day17.kt\"\npublic final class day17.Day17Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day21/Day21.kt
package day21 import java.io.File import kotlin.math.roundToLong fun main() { val input = File("src/day21/input.txt").readLines() .map { it.split(": ") } .associate { it[0] to it[1] } println(part1(input, "root")) input["root"]!!.split(" ").let { val lhs = part2(input, it[0]) val rhs = part2(input, it[2]) println(((rhs.second - lhs.second) / (lhs.first - rhs.first)).roundToLong()) } } fun part1(input: Map<String, String>, monkey: String): Long { val output = input[monkey]!! if (output.contains(" ")) { output.split(" ").let { parts -> val a = part1(input, parts[0]) val b = part1(input, parts[2]) return when (parts[1]) { "+" -> a + b "-" -> a - b "*" -> a * b "/" -> a / b else -> throw IllegalStateException("Unknown operation ${parts[1]}") } } } return output.toLong() } fun part2(input: Map<String, String>, monkey: String): Pair<Double, Double> { val result: Pair<Double, Double> if (monkey == "humn") { result = Pair(1.0, 0.0) } else { val output = input[monkey]!! if (output.contains(" ")) { output.split(" ").let { parts -> val a = part2(input, parts[0]) val b = part2(input, parts[2]) result = when (parts[1]) { "+" -> Pair(a.first + b.first, a.second + b.second) "-" -> Pair(a.first - b.first, a.second - b.second) "*" -> if (a.first == 0.0) Pair( a.second * b.first, a.second * b.second ) else if (b.first == 0.0) Pair( b.second * a.first, b.second * a.second ) else throw IllegalStateException("Multiplication by humn") "/" -> if (b.first == 0.0) Pair( a.first / b.second, a.second / b.second ) else throw IllegalStateException("Division by humn") else -> throw IllegalStateException("Unknown operation ${parts[1]}") } } } else { result = Pair(0.0, output.toDouble()) } } return result }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day21/Day21Kt.class", "javap": "Compiled from \"Day21.kt\"\npublic final class day21.Day21Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2022__0e0cae3/src/day19/Day19.kt
package day19 import java.io.File import java.lang.IllegalStateException import java.util.PriorityQueue import kotlin.math.ceil import kotlin.math.max fun main() { val regexp = Regex("\\d+") val blueprints = File("src/day19/input.txt").readLines() .map { regexp.findAll(it).drop(1).map { it.value.toInt() }.toList().let { matches -> listOf( Quadruple(matches[0], 0, 0, 0), Quadruple(matches[1], 0, 0, 0), Quadruple(matches[2], matches[3], 0, 0), Quadruple(matches[4], 0, matches[5], 0) ) } } println(blueprints.map { maxGeodes(it, 24) }.mapIndexed { i, geodes -> (i + 1) * geodes }.sum()) println(blueprints.take(3).map { maxGeodes(it, 32) }.reduce(Int::times)) } fun maxGeodes(blueprint: List<Quadruple>, totalMinutes: Int): Int { var maxGeodes = 0 val queue = PriorityQueue<State>().apply { add(State(1, Quadruple(1, 0, 0, 0), Quadruple(1, 0, 0, 0))) } while (queue.isNotEmpty()) { val state = queue.poll() maxGeodes = max(maxGeodes, state.materials.geode) if (state.minute == totalMinutes) continue val theoreticalMaxGeodes = state.materials.geode + (state.minute..totalMinutes).sumOf { it + state.robots.geode } if (theoreticalMaxGeodes > maxGeodes) { queue.addAll(state.next(blueprint, totalMinutes)) } } return maxGeodes } data class Quadruple(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) { operator fun plus(other: Quadruple) = Quadruple(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode) operator fun minus(other: Quadruple) = Quadruple(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode) operator fun times(multiple: Int) = Quadruple(ore * multiple, clay * multiple, obsidian * multiple, geode * multiple) fun timeToBuild(required: Quadruple): Int = maxOf( if (required.ore <= 0) 0 else ceil(required.ore.toDouble() / ore).toInt(), if (required.clay <= 0) 0 else ceil(required.clay.toDouble() / clay).toInt(), if (required.obsidian <= 0) 0 else ceil(required.obsidian.toDouble() / obsidian).toInt(), if (required.geode <= 0) 0 else ceil(required.geode.toDouble() / geode).toInt() ) + 1 companion object { fun of(index: Int) = when (index) { 0 -> Quadruple(1, 0, 0, 0) 1 -> Quadruple(0, 1, 0, 0) 2 -> Quadruple(0, 0, 1, 0) 3 -> Quadruple(0, 0, 0, 1) else -> throw IllegalStateException() } } } data class State(val minute: Int, val robots: Quadruple, val materials: Quadruple) : Comparable<State> { fun next(blueprint: List<Quadruple>, totalMinutes: Int): List<State> { val nextBuildStates = mutableListOf<State>() if (blueprint.maxOf { it.ore } > robots.ore && materials.ore > 0) { nextBuildStates += nextForRobot(blueprint, 0) } if (blueprint.maxOf { it.clay } > robots.clay && materials.ore > 0) { nextBuildStates += nextForRobot(blueprint, 1) } if (blueprint.maxOf { it.obsidian } > robots.obsidian && materials.ore > 0 && materials.clay > 0) { nextBuildStates += nextForRobot(blueprint, 2) } if (materials.ore > 0 && materials.obsidian > 0) { nextBuildStates += nextForRobot(blueprint, 3) } val nextBuildStatesWithinTime = nextBuildStates.filter { it.minute <= totalMinutes }.toMutableList() return nextBuildStatesWithinTime.ifEmpty { listOf(State(totalMinutes, robots, materials + (robots * (totalMinutes - minute)))) } } private fun nextForRobot(blueprint: List<Quadruple>, index: Int): State { return robots.timeToBuild(blueprint[index] - materials) .let { time -> State( minute + time, robots + Quadruple.of(index), materials - blueprint[index] + (robots * time) ) } } override fun compareTo(other: State) = other.materials.geode.compareTo(materials.geode) }
[ { "class_path": "davidcurrie__advent-of-code-2022__0e0cae3/day19/Day19Kt.class", "javap": "Compiled from \"Day19.kt\"\npublic final class day19.Day19Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
rolf-rosenbaum__aoc-2022__59cd426/src/main/day07/day07.kt
package day07 import readInput private const val THRESHOLD_PART1 = 100000 private const val TOTAL_DISC_SIZE = 70000000 private const val SIZE_FOR_UPDATE = 30000000 data class Directory( val name: String, val files: MutableSet<Int>, val dirs: MutableMap<String, Directory>, val parent: Directory? = null ) { val totalSize: Int get() = files.sum() + dirs.values.sumOf { it.totalSize } val allDirectories: List<Directory> get() = listOf(this) + dirs.values.flatMap { it.allDirectories } private fun root(): Directory = parent?.root() ?: this fun changeInto(arg: String): Directory { return when (arg) { "/" -> root() ".." -> parent ?: root() else -> dirs[arg] ?: Directory(arg, mutableSetOf(), mutableMapOf(), this) } } override fun hashCode(): Int = name.hashCode() override fun equals(other: Any?): Boolean = if (other is Directory) name == other.name else false } fun main() { val input = readInput("main/day07/Day07") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { return input.parseDirectories().allDirectories .filter { it.totalSize <= THRESHOLD_PART1 } .sumOf { it.totalSize } } fun part2(input: List<String>): Int { val root = input.parseDirectories() return root.allDirectories.filter { it.totalSize >= SIZE_FOR_UPDATE - (TOTAL_DISC_SIZE - root.totalSize) }.minBy { it.totalSize }.totalSize } fun List<String>.parseDirectories(): Directory { val root = Directory("/", mutableSetOf(), mutableMapOf()) var current = root forEach { line -> when { line.isCd() -> current = current.changeInto(line.lastArg()) line.isDir() -> current.dirs[line.lastArg()] = Directory(line.lastArg(), mutableSetOf(), mutableMapOf(), current) line.isFile() -> current.files.add(line.firstArg().toInt()) } } return root } private fun String.lastArg() = split(" ").last() private fun String.firstArg() = split(" ").first() fun String.isCd() = startsWith("$ cd") fun String.isFile() = first().isDigit() fun String.isDir() = startsWith("dir")
[ { "class_path": "rolf-rosenbaum__aoc-2022__59cd426/day07/Day07Kt.class", "javap": "Compiled from \"day07.kt\"\npublic final class day07.Day07Kt {\n private static final int THRESHOLD_PART1;\n\n private static final int TOTAL_DISC_SIZE;\n\n private static final int SIZE_FOR_UPDATE;\n\n public static fina...