kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
shauryam-exe__DS-Algo-Zone__3a24745/Kotlin/SelectionSort.kt
fun main(args: Array<String>) { //Input the array in the format num1 num2 num3 num4 etc print("Enter the elements for the Array: ") var inputArray = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() var sortedArray = selectionSort(inputArray) println(sortedArray.contentToString()) } fun selectionSort(arr: IntArray): IntArray { for (i in arr.lastIndex downTo 0) { var max = arr[0] var maxIndex = 0 for (j in 0..i) { if (arr[maxIndex]<arr[j]) maxIndex = j } val temp = arr[maxIndex] arr[maxIndex] = arr[i] arr[i] = temp } return arr } //Sample //Input: Enter the elements for the Array: 64 23 -12 -5 0 2 89 20 100 32 650 -230 130 //Output: [-230, -12, -5, 0, 2, 20, 23, 32, 64, 89, 100, 130, 650] //Time Complexity: Worst Case: O(n^2) Best Case: O(n^2) //Space Complexity: O(1)
[ { "class_path": "shauryam-exe__DS-Algo-Zone__3a24745/SelectionSortKt.class", "javap": "Compiled from \"SelectionSort.kt\"\npublic final class SelectionSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
romangraef__PatternToFormula__e140a49/src/PatternFinder.kt
import java.lang.Math.floor import java.lang.Math.max import javax.script.ScriptEngine import javax.script.ScriptEngineManager data class Expression(val expression: String) fun main(args:Array<String>) { while (true) { println("---------------------------") println("Separate numbers by comma.") print("Enter numbers: ") val inputNumbers = readLine()!!.split(",").map { it.trim().toDouble() } val formula = findFormula(inputNumbers) println("Formula: $formula") println("Pattern: " + continuePattern(formula)) } } private fun findFormula(numbers: List<Double>): String { // Find difference between numbers val differences = listOf( numbers[1] - numbers[0], numbers[2] - numbers[1] ) var incrementsByDifference = true var increment = 0.0 if (differences[0] != differences[1]) // If the pattern doesn't increment by difference incrementsByDifference = false else increment = differences[0] // Start-value val nAsExponent = nAsExponent(differences, numbers) val startValueDifference = when { incrementsByDifference -> differences[0] // xn nAsExponent -> getBase(differences) // x^n else -> 1.0 // n^x } val startValue = numbers[0] - startValueDifference // Exponents var base = "n" var exponent = "" if (nAsExponent(differences, numbers)) { base = getBase(differences).cleanRedundancy() + "^" exponent = "n" } else if (!incrementsByDifference) { base = "n^" exponent = getExponent(numbers[1], startValue).cleanRedundancy() } // Add the pieces together var formula = increment.cleanRedundancy() formula += base + exponent + startValue.cleanRedundancy().addSign() return formula } private fun continuePattern(formula: String): String { var output = "" for (i in 1..20) { val expression = Expression(formula.replace("n", i.toString())) output += expression.calculate().cleanRedundancy() + ", " } return output.cleanRedundancy() } fun Double.cleanRedundancy(): String { return when { this == 0.0 -> return "" floor(this) == this -> this.toInt().toString() else -> return this.toString() } } fun String.cleanRedundancy(): String { return if (this.endsWith(", ")) this.substring(0, this.length - 3) else this } fun String.addSign(): String { return if (!this.startsWith("-")) "+" + this else this } fun Expression.calculate(): Double { val addSubSign = max(expression.indexOf("+"), expression.indexOf("-")) val addSub = expression.substring(addSubSign + 1, expression.length).toDouble() val numbers = expression.substring(0, addSubSign) .split(Regex("[*^]")).map { it.toDouble() } if (expression.contains("*")) return numbers[0] * numbers[1] + addSub else if (expression.contains("^")) return Math.pow(numbers[0], numbers[1]) + addSub return 0.0 } private fun getBase(differences: List<Double>): Double { return differences[1] / differences[0] } private fun getExponent(secondNumber: Double, startValue: Double): Double { return Math.log(secondNumber - startValue) / Math.log(2.0) } private fun nAsExponent(differences: List<Double>, numbers: List<Double>): Boolean { val base = getBase(differences) return Math.log(numbers[1] - (base - 1)) / Math.log(base) == 2.0 }
[ { "class_path": "romangraef__PatternToFormula__e140a49/PatternFinderKt.class", "javap": "Compiled from \"PatternFinder.kt\"\npublic final class PatternFinderKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
MeilCli__StalinSort__b245390/Kotlin/src/main/kotlin/StalinSort.kt
fun main(args: Array<String>) { println("Hello Stalin!") writeStalinSort(intArrayOf(4)) writeStalinSort(intArrayOf(6, 2, 5, 7, 3, 8, 8, 4)) writeStalinSort(intArrayOf(5, 3, 7, 8, 9, 5, 3, 5, 7)) /** * Hello Stalin! * Input: 4 * StalinBy: 4 * StalinByDescending: 4 * Input: 6,2,5,7,3,8,8,4 * StalinBy: 6,7,8,8 * StalinByDescending: 6,2 * Input: 5,3,7,8,9,5,3,5,7 * StalinBy: 5,7,8,9 * StalinByDescending: 5,3,3 */ } private fun writeStalinSort(source: IntArray) { println("Input: ${source.joinToString(",")}") println("StalinBy: ${source.asSequence().stalinBy().joinToString(",")}") println("StalinByDescending: ${source.asSequence().stalinByDescending().joinToString(",")}") } fun <T> Sequence<T>.stalinBy(): List<T> where T : Comparable<T> { return stalinSort(this, false) } fun <T> Sequence<T>.stalinByDescending(): List<T> where T : Comparable<T> { return stalinSort(this, true) } private fun <T> stalinSort(source: Sequence<T>, descending: Boolean): List<T> where T : Comparable<T> { val iterator = source.iterator() val result = mutableListOf<T>() if (iterator.hasNext()) { var lastElement = iterator.next() result.add(lastElement) while (iterator.hasNext()) { val element = iterator.next() val compare = when (descending) { true -> element <= lastElement false -> lastElement <= element } if (compare) { result.add(element) lastElement = element } } } return result }
[ { "class_path": "MeilCli__StalinSort__b245390/StalinSortKt.class", "javap": "Compiled from \"StalinSort.kt\"\npublic final class StalinSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokesta...
mepants__Advent-Of-Code-2022__3b42381/Day2_02/src/main/kotlin/Main.kt
import java.io.File enum class Move(val value: Int) { ROCK(1) { override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 3 PAPER -> 0 SCISSORS -> 6 } } override fun losesAgainst() = PAPER override fun winsAgainst() = SCISSORS }, PAPER(2){ override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 6 PAPER -> 3 SCISSORS -> 0 } } override fun losesAgainst() = SCISSORS override fun winsAgainst() = ROCK }, SCISSORS(3){ override fun scoreAgainst(opponentMove: Move): Int { return when (opponentMove) { ROCK -> 0 PAPER -> 6 SCISSORS -> 3 } } override fun losesAgainst() = ROCK override fun winsAgainst() = PAPER }; abstract fun scoreAgainst(opponentMove: Move) : Int abstract fun losesAgainst() : Move abstract fun winsAgainst() : Move companion object { fun fromLetter(letter: Char): Move { return when (letter) { 'A' -> Move.ROCK 'B' -> Move.PAPER 'C' -> Move.SCISSORS else -> throw Exception("Unknown move $letter") } } } } fun main(args: Array<String>) { val FILENAME = "c:\\Users\\micro\\code\\Advent-Of-Code-2022\\Day2_02\\input.txt" fun scoreRound(oppLetter: Char, myLetter: Char) : Int { val opponentMove = Move.fromLetter(oppLetter) val myMove = when (myLetter) { 'X' -> opponentMove.winsAgainst() 'Z' -> opponentMove.losesAgainst() else -> opponentMove } return myMove.value + myMove.scoreAgainst(opponentMove) } var score = 0 val file = File(FILENAME) file.forEachLine { score += scoreRound(it[0], it[2]) } println("My total score is $score") }
[ { "class_path": "mepants__Advent-Of-Code-2022__3b42381/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ...
dirask__codelibrary__75f5296/kotlin/MaxFlowDinic.kt
// https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E) object MaxFlowDinic { data class Edge(val t: Int, val rev: Int, val cap: Int, var f: Int = 0) fun addEdge(graph: Array<ArrayList<Edge>>, s: Int, t: Int, cap: Int) { graph[s].add(Edge(t, graph[t].size, cap)) graph[t].add(Edge(s, graph[s].size - 1, 0)) } fun dinicBfs(graph: Array<out List<Edge>>, src: Int, dest: Int, dist: IntArray): Boolean { dist.fill(-1) dist[src] = 0 val Q = IntArray(graph.size) var sizeQ = 0 Q[sizeQ++] = src var i = 0 while (i < sizeQ) { val u = Q[i++] for (e in graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1 Q[sizeQ++] = e.t } } } return dist[dest] >= 0 } fun dinicDfs(graph: Array<out List<Edge>>, ptr: IntArray, dist: IntArray, dest: Int, u: Int, f: Int): Int { if (u == dest) return f while (ptr[u] < graph[u].size) { val e = graph[u][ptr[u]] if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { val df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)) if (df > 0) { e.f += df graph[e.t][e.rev].f -= df return df } } ++ptr[u] } return 0 } fun maxFlow(graph: Array<out List<Edge>>, src: Int, dest: Int): Int { var flow = 0 val dist = IntArray(graph.size) while (dinicBfs(graph, src, dest, dist)) { val ptr = IntArray(graph.size) while (true) { val df = dinicDfs(graph, ptr, dist, dest, src, Int.MAX_VALUE) if (df == 0) break flow += df } } return flow } // Usage example @JvmStatic fun main(args: Array<String>) { val graph = (1..3).map { arrayListOf<Edge>() }.toTypedArray() addEdge(graph, 0, 1, 3) addEdge(graph, 0, 2, 2) addEdge(graph, 1, 2, 2) val maxFlow = maxFlow(graph, 0, 2) println(4 == maxFlow) } }
[ { "class_path": "dirask__codelibrary__75f5296/MaxFlowDinic$Edge.class", "javap": "Compiled from \"MaxFlowDinic.kt\"\npublic final class MaxFlowDinic$Edge {\n private final int t;\n\n private final int rev;\n\n private final int cap;\n\n private int f;\n\n public MaxFlowDinic$Edge(int, int, int, int);\n...
dirask__codelibrary__75f5296/kotlin/Determinant.kt
// https://en.wikipedia.org/wiki/Determinant fun det(matrix: Array<DoubleArray>): Double { val EPS = 1e-10 val a = matrix.map { it.copyOf() }.toTypedArray() val n = a.size var res = 1.0 for (i in 0 until n) { val p = (i until n).maxBy { Math.abs(a[it][i]) }!! if (Math.abs(a[p][i]) < EPS) return 0.0 if (i != p) { res = -res a[i] = a[p].also { a[p] = a[i] } } res *= a[i][i] for (j in i + 1 until n) a[i][j] /= a[i][i] for (j in 0 until n) if (j != i && Math.abs(a[j][i]) > EPS /*optimizes overall complexity to O(n^2) for sparse matrices*/) for (k in i + 1 until n) a[j][k] -= a[i][k] * a[j][i] } return res } // Usage example fun main() { val d = det(arrayOf(doubleArrayOf(0.0, 1.0), doubleArrayOf(-1.0, 0.0))) println(Math.abs(d - 1) < 1e-10) }
[ { "class_path": "dirask__codelibrary__75f5296/DeterminantKt.class", "javap": "Compiled from \"Determinant.kt\"\npublic final class DeterminantKt {\n public static final double det(double[][]);\n Code:\n 0: aload_0\n 1: ldc #9 // String matrix\n 3: invokestati...
akkinoc__atcoder-workspace__e650a9c/atcoder.jp/abc264/abc264_c/Main.kt
fun main() { val (h1, w1) = readLine()!!.split(" ").map { it.toInt() } val a = List(h1) { readLine()!!.split(" ") } val (h2, w2) = readLine()!!.split(" ").map { it.toInt() } val b = List(h2) { readLine()!!.split(" ") } for (r in (0 until h1).combinations(h1 - h2)) { val w = a.filterIndexed { i, _ -> i !in r } for (c in (0 until w1).combinations(w1 - w2)) if (w.map { it.filterIndexed { i, _ -> i !in c } } == b) return print("Yes") } print("No") } fun <T> Iterable<T>.combinations(r: Int): Sequence<List<T>> = sequence { if (r < 1) yield(emptyList()) else forEachIndexed { i, e -> drop(i + 1).combinations(r - 1).forEach { yield(listOf(e) + it) } } }
[ { "class_path": "akkinoc__atcoder-workspace__e650a9c/MainKt$combinations$1.class", "javap": "Compiled from \"Main.kt\"\nfinal class MainKt$combinations$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceScope<? super java.util....
buczebar__advent-of-code__cdb6fe3/src/Day02.kt
fun main() { fun gameResult(yourMove: HandShape, opponentMove: HandShape) = when (yourMove) { opponentMove.greater() -> GameResult.WIN opponentMove.lower() -> GameResult.LOSS else -> GameResult.DRAW } fun part1(input: List<Pair<HandShape, HandShape>>): Int { return input.sumOf { (opponentMove, yourMove) -> yourMove.score + gameResult(yourMove, opponentMove).score } } fun getMoveForExpectedResult(opponentMove: HandShape, expectedResult: GameResult) = when (expectedResult) { GameResult.LOSS -> opponentMove.lower() GameResult.DRAW -> opponentMove GameResult.WIN -> opponentMove.greater() } fun part2(input: List<Pair<HandShape, GameResult>>) = input.sumOf { val (opponentMove, gameResult) = it gameResult.score + getMoveForExpectedResult(opponentMove, gameResult).score } val testInputPart1 = parseInput("Day02_test", String::toHandShape, String::toHandShape) check(part1(testInputPart1) == 15) val testInputPart2 = parseInput("Day02_test", String::toHandShape, String::toGameResult) check(part2(testInputPart2) == 12) val inputForPart1 = parseInput("Day02", String::toHandShape, String::toHandShape) println(part1(inputForPart1)) val inputForPart2 = parseInput("Day02", String::toHandShape, String::toGameResult) println(part2(inputForPart2)) } private fun <T, U> parseInput(name: String, firstArgParser: (String) -> T, secondArgParser: (String) -> U) = readInput(name).map { round -> round.split(" ").let { Pair(firstArgParser.invoke(it[0]), secondArgParser.invoke(it[1])) } } private fun String.toHandShape(): HandShape { return when (this) { "A", "X" -> HandShape.ROCK "B", "Y" -> HandShape.PAPER "C", "Z" -> HandShape.SCISSORS else -> throw IllegalArgumentException() } } private fun String.toGameResult(): GameResult { return when (this) { "X" -> GameResult.LOSS "Y" -> GameResult.DRAW "Z" -> GameResult.WIN else -> throw IllegalArgumentException() } } private enum class HandShape(val score: Int) { ROCK(1) { override fun greater() = PAPER override fun lower() = SCISSORS }, PAPER(2) { override fun greater() = SCISSORS override fun lower() = ROCK }, SCISSORS(3) { override fun greater() = ROCK override fun lower() = PAPER }; abstract fun greater(): HandShape abstract fun lower(): HandShape } private enum class GameResult(val score: Int) { LOSS(0), DRAW(3), WIN(6) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day02Kt$main$testInputPart2$2.class", "javap": "Compiled from \"Day02.kt\"\nfinal class Day02Kt$main$testInputPart2$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.String, GameResult> {\n public stati...
buczebar__advent-of-code__cdb6fe3/src/Utils.kt
import java.io.File import java.lang.IllegalArgumentException import kotlin.math.abs /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Reads input separated by empty line */ fun readGroupedInput(name: String) = File("src", "$name.txt").readText().split("\n\n") fun List<String>.splitLinesToInts() = map { it.split("\n").toListOfInts() } fun List<String>.toListOfInts() = map { it.toInt() } fun <T> List<T>.allDistinct() = distinct().size == size fun <T> List<T>.pair(): Pair<T, T> = if (size == 2) Pair(this[0], this[1]) else throw IllegalArgumentException("Input array has wrong size") fun String.remove(regex: Regex) = replace(regex, "") fun String.splitWords() = split(" ") fun <T> List<List<T>>.transpose(): List<List<T>> { val desiredSize = maxOf { it.size } val resultList = List<MutableList<T>>(desiredSize) { mutableListOf() } forEach { list -> list.forEachIndexed { index, item -> resultList[index].add(item) } } return resultList } fun <T> List<T>.head() = first() fun <T> List<T>.dropHead() = drop(1) fun String.getAllInts() = "(-?\\d+)".toRegex().findAll(this).map { it.value.toInt() }.toList() fun String.getAllByRegex(regex: Regex) = regex.findAll(this).map { it.value }.toList() fun List<Long>.factorial() = reduce { acc, it -> acc * it } fun List<Int>.factorial() = reduce { acc, it -> acc * it } typealias Position = Pair<Int, Int> operator fun Position.plus(other: Position) = Position(x + other.x, y + other.y) operator fun Position.minus(other: Position) = Position(x - other.x, y - other.y) val Position.x: Int get() = first val Position.y: Int get() = second fun Position.manhattanDistanceTo(other: Position) = abs(x - other.x) + abs(y - other.y) fun <T> MutableList<T>.popHead(): T { val head = head() removeFirst() return head } fun IntRange.limitValuesInRange(valueRange: IntRange): IntRange { return first.coerceAtLeast(valueRange.first)..last.coerceAtMost(valueRange.last) } fun List<Int>.valueRange(): IntRange { return min()..max() }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name...
buczebar__advent-of-code__cdb6fe3/src/Day14.kt
import java.lang.Integer.max import java.lang.Integer.min private typealias Path = List<Position> private typealias MutableMatrix<T> = MutableList<MutableList<T>> private val Pair<Int, Int>.depth: Int get() = second private fun List<Path>.getMaxValue(selector: (Position) -> Int) = flatten().maxOf { selector(it) } private fun List<Path>.toFieldMatrix(): MutableMatrix<FieldType> { val maxDepth = getMaxValue { it.depth } val maxWidth = getMaxValue { it.x } val matrix = MutableList(maxDepth + 1) { MutableList(maxWidth * 2) { FieldType.AIR } } forEach { path -> path.windowed(2).forEach { (start, end) -> val xRange = min(start.x, end.x)..max(start.x, end.x) val depthRange = min(start.depth, end.depth)..max(start.depth, end.depth) for (x in xRange) { for (y in depthRange) { matrix[y][x] = FieldType.ROCK } } } } return matrix } private fun MutableList<MutableList<FieldType>>.addRow(type: FieldType) { add(MutableList(first().size) { type }) } fun main() { fun parseInput(name: String) = readInput(name) .map { line -> line.split(" -> ") .map { path -> path.split(",") .toListOfInts() .pair() } } fun simulate(fieldMatrix: MutableMatrix<FieldType>): Int { fun nextPosition(position: Position): Position? { val directionsToCheck = listOf(Position(0, 1), Position(-1, 1), Position(1, 1)) for (direction in directionsToCheck) { val newPosition = position + direction if (fieldMatrix[newPosition.depth][newPosition.x] == FieldType.AIR) { return newPosition } } return null } val maxDepth = fieldMatrix.size - 1 val sandStartPosition = Position(500, 0) var position = sandStartPosition while (position.depth < maxDepth && fieldMatrix[sandStartPosition.depth][sandStartPosition.x] == FieldType.AIR) { with(nextPosition(position)) { if (this == null) { fieldMatrix[position.depth][position.x] = FieldType.SAND position = sandStartPosition } else { position = this } } } return fieldMatrix.flatten().count { it == FieldType.SAND } } fun part1(fieldMatrix: MutableMatrix<FieldType>) = simulate(fieldMatrix) fun part2(fieldMatrix: MutableMatrix<FieldType>): Int { fieldMatrix.apply { addRow(FieldType.AIR) addRow(FieldType.ROCK) } return simulate(fieldMatrix) } val testInput = parseInput("Day14_test").toFieldMatrix() check(part1(testInput) == 24) check(part2(testInput) == 93) val input = parseInput("Day14").toFieldMatrix() println(part1(input)) println(part2(input)) } private enum class FieldType { AIR, SAND, ROCK }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n private static final int getDepth(kotlin.Pair<java.lang.Integer, java.lang.Integer>);\n Code:\n 0: aload_0\n 1: invokevirtual #13 // Method ...
buczebar__advent-of-code__cdb6fe3/src/Day04.kt
typealias SectionRange = Pair<Int, Int> fun main() { infix fun SectionRange.contains(range: SectionRange): Boolean { return first <= range.first && this.second >= range.second } infix fun SectionRange.overlap(range: SectionRange): Boolean { return first <= range.second && range.first <= second } fun part1(input: List<Pair<SectionRange, SectionRange>>) = input.count { it.first contains it.second || it.second contains it.first } fun part2(input: List<Pair<SectionRange, SectionRange>>) = input.count { it.first overlap it.second || it.second overlap it.first } fun parseInput(name: String): List<Pair<SectionRange, SectionRange>> { fun parseSectionRange(input: String) = input.split("-").map { it.toInt() }.pair() return readInput(name) .map { it.split(",").pair() .let { ranges -> Pair(parseSectionRange(ranges.first), parseSectionRange(ranges.second)) } } } val testInput = parseInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = parseInput("Day04") println(part1(input)) println(part2(input)) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day04_test\n 2: invokestatic #12 // Method main$p...
buczebar__advent-of-code__cdb6fe3/src/Day07.kt
private const val TOTAL_DISK_SPACE = 70000000L private const val SPACE_NEEDED_FOR_UPDATE = 30000000L fun main() { fun part1(fileTree: TreeNode): Long { return fileTree.getAllSubdirectories().filter { it.totalSize <= 100_000 }.sumOf { it.totalSize } } fun part2(fileTree: TreeNode): Long { val spaceAvailable = TOTAL_DISK_SPACE - fileTree.totalSize val spaceToBeFreed = SPACE_NEEDED_FOR_UPDATE - spaceAvailable return fileTree.getAllSubdirectories().sortedBy { it.totalSize } .firstOrNull { it.totalSize > spaceToBeFreed }?.totalSize ?: 0L } val testInput = readInput("Day07_test") val testInputFileTree = buildFileTree(testInput) check(part1(testInputFileTree) == 95_437L) check(part2(testInputFileTree) == 24_933_642L) val input = readInput("Day07") val inputFileTree = buildFileTree(input) println(part1(inputFileTree)) println(part2(inputFileTree)) } private fun buildFileTree(consoleLog: List<String>): TreeNode { val rootNode = DirNode("/", null) var currentNode = rootNode as TreeNode consoleLog.forEach { line -> when { line.isCdCommand() -> { val (_, _, name) = line.splitWords() currentNode = when (name) { ".." -> currentNode.parent ?: return@forEach "/" -> rootNode else -> currentNode.getChildByName(name) } } line.isDir() -> { val (_, name) = line.splitWords() currentNode.addChild(DirNode(name)) } line.isFile() -> { val (size, name) = line.splitWords() currentNode.addChild(FileNode(name, size.toLong())) } } } return rootNode } private fun String.isDir() = startsWith("dir") private fun String.isFile() = "\\d+ [\\w.]+".toRegex().matches(this) private fun String.isCdCommand() = startsWith("$ cd") private abstract class TreeNode(private val name: String, var parent: TreeNode?, val children: MutableList<TreeNode>?) { open val totalSize: Long get() { return children?.sumOf { it.totalSize } ?: 0 } fun addChild(node: TreeNode) { node.parent = this children?.add(node) } fun getChildByName(name: String): TreeNode { return children?.firstOrNull { it.name == name } ?: this } fun getAllSubdirectories(): List<DirNode> { return getAllSubNodes().filterIsInstance<DirNode>() } private fun getAllSubNodes(): List<TreeNode> { val result = mutableListOf<TreeNode>() if (children != null) { for (child in children) { result.addAll(child.getAllSubNodes()) result.add(child) } } return result } } private class DirNode(name: String, parent: TreeNode? = null, children: MutableList<TreeNode> = mutableListOf()) : TreeNode(name, parent, children) private class FileNode(name: String, override val totalSize: Long, parent: DirNode? = null) : TreeNode(name, parent, null)
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day07Kt$main$part2$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class Day07Kt$main$part2$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public Day07Kt$main$part2$$inlined$sortedBy$1();\n Code:\n ...
buczebar__advent-of-code__cdb6fe3/src/Day05.kt
typealias Stack = List<Char> fun main() { fun solve(input: Pair<MutableList<Stack>, List<StackMove>>, inputModifier: (List<Char>) -> List<Char>): String { val (stacks, moves) = input moves.forEach { move -> stacks[move.to] = stacks[move.from].take(move.amount).let { inputModifier.invoke(it) } + stacks[move.to] stacks[move.from] = stacks[move.from].drop(move.amount) } return stacks.filter { it.isNotEmpty() }.map { it.first() }.joinToString("") } fun part1(input: Pair<MutableList<Stack>, List<StackMove>>) = solve(input) { it.reversed() } fun part2(input: Pair<MutableList<Stack>, List<StackMove>>) = solve(input) { it } check(part1(parseInput("Day05_test")) == "CMZ") check(part2(parseInput("Day05_test")) == "MCD") println(part1(parseInput("Day05"))) println(part2(parseInput("Day05"))) } private fun parseInput(name: String): Pair<MutableList<Stack>, List<StackMove>> { fun parseStacks(inputString: String): MutableList<Stack> { val stackValues = inputString.lines().dropLast(1) .map { line -> line.replace(" ", "[-]") .remove("[^\\w-]".toRegex()) .toList() } .transpose() .map { stack -> stack.filter { it != '-' }.toMutableList() } return stackValues.toMutableList() } fun parseMoves(inputString: String): List<StackMove> { val lineRegex = "(\\d+)".toRegex() return inputString.lines() .map { line -> lineRegex.findAll(line).map { it.value.toInt() }.toList() } .map { (amount, from, to) -> StackMove(amount, from - 1, to - 1) } } val (stacks, moves) = readGroupedInput(name) return Pair(parseStacks(stacks), parseMoves(moves)) } private data class StackMove( val amount: Int, val from: Int, val to: Int )
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day05_test\n 2: invokestatic #12 // Method parseI...
buczebar__advent-of-code__cdb6fe3/src/Day15.kt
import kotlin.math.abs private fun parseInput(name: String) = readInput(name).map { line -> line.split(":").map { it.getAllInts().pair() } }.map { (sensorXY, beaconXY) -> Sensor(sensorXY, beaconXY) } fun main() { fun Position.tuningFrequency() = 4000000L * x + y fun coverageRangesForY(y: Int, sensors: List<Sensor>, valueRange: IntRange): List<IntRange> { val ranges = mutableListOf<IntRange>() sensors.forEach { sensor -> val distanceToY = abs(sensor.y - y) val radiusForY = (sensor.distanceToClosestBeacon - distanceToY).coerceAtLeast(0) if (radiusForY > 0) { ranges.add(((sensor.x - radiusForY)..(sensor.x + radiusForY)).limitValuesInRange(valueRange)) } } return ranges } fun part1(sensors: List<Sensor>, y: Int): Int { val xPositionsWithSensorsOrBeacons = sensors .flatMap { listOf(it.position, it.closestBeacon) } .filter { it.y == y } .map { it.x } .toSet() val valueRange = sensors.map { it.closestBeacon.x }.valueRange() val xPositionsWithoutBeacon = coverageRangesForY(y, sensors, valueRange) .flatMap { it.toList() } .toSet() .minus(xPositionsWithSensorsOrBeacons) return xPositionsWithoutBeacon.size } fun part2(sensors: List<Sensor>, valueRange: IntRange): Long { valueRange.forEach { y -> val coverageRanges = coverageRangesForY(y, sensors, valueRange).sortedBy { it.first } var rightBoundary = coverageRanges.first().last for (i in 1 until coverageRanges.size) { val range = coverageRanges[i] if (rightBoundary < range.first) { return Position(rightBoundary + 1, y).tuningFrequency() } rightBoundary = range.last.coerceAtLeast(rightBoundary) } } return 0L } val testInput = parseInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 0..20) == 56000011L) val input = parseInput("Day15") println(part1(input, 2000000)) println(part2(input, 0..4000000)) } private data class Sensor(val position: Position, val closestBeacon: Position) { val x: Int get() = position.x val y: Int get() = position.y val distanceToClosestBeacon: Int get() = position.manhattanDistanceTo(closestBeacon) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day15Kt.class", "javap": "Compiled from \"Day15.kt\"\npublic final class Day15Kt {\n private static final java.util.List<Sensor> parseInput(java.lang.String);\n Code:\n 0: aload_0\n 1: invokestatic #12 // Method UtilsKt.read...
buczebar__advent-of-code__cdb6fe3/src/Day06.kt
fun main() { fun solve(input: String, distLength: Int) = input.indexOf(input.windowed(distLength).first { it.toList().allDistinct()}) + distLength fun part1(input: String) = solve(input, 4) fun part2(input: String) = solve(input, 14) val testInput = readInput("Day06_test") val testResults = listOf( 7 to 19, // mjqjpqmgbljsphdztnvjfqwrcgsmlb 5 to 23, // bvwbjplbgvbhsrlpgdmjqwftvncz 6 to 23, // nppdvjthqldpwncqszvftbrmjlhg 10 to 29, // nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg 11 to 26 // zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw ) testInput.zip(testResults).forEach { (input, results) -> check(part1(input) == results.first) check(part2(input) == results.second) } val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day06Kt.class", "javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day06_test\n 2: invokestatic #14 // Method UtilsK...
buczebar__advent-of-code__cdb6fe3/src/Day16.kt
fun main() { lateinit var flowRates: Map<String, Int> lateinit var connections: Map<String, List<String>> lateinit var workingValves: List<String> lateinit var distances: Map<Pair<String, String>, Int> fun getDistanceToValve( current: String, destination: String, visited: List<String> = emptyList(), depth: Int = 1 ): Int { val nextValves = (connections[current]!!).filter { !visited.contains(it) }.takeIf { it.isNotEmpty() } ?: return Int.MAX_VALUE return if (nextValves.contains(destination)) { depth } else { val newVisited = visited + current nextValves.minOf { getDistanceToValve(it, destination, newVisited, depth + 1) } } } fun parseInput(fileName: String) { val valves = mutableMapOf<String, Int>() val tunnels = mutableMapOf<String, List<String>>() readInput(fileName) .map { it.split(";") } .forEach { (valveRaw, tunnelsRaw) -> val label = valveRaw.getAllByRegex("[A-Z][A-Z]".toRegex()).single() val flowRate = valveRaw.getAllInts().single() val accessibleValves = tunnelsRaw.getAllByRegex("[A-Z][A-Z]".toRegex()) valves[label] = flowRate tunnels[label] = accessibleValves } flowRates = valves connections = tunnels workingValves = flowRates.keys.filter { flowRates[it]!! > 0 } } fun calculateDistancesBetweenValves(valves: List<String>): Map<Pair<String, String>, Int> { val resultDistances = mutableMapOf<Pair<String, String>, Int>() for (start in valves) { for (end in valves) { resultDistances[start to end] = getDistanceToValve(start, end) } } return resultDistances } fun maxPath(node: String, countDown: Int, opened: Set<String> = emptySet(), pressure: Int = 0): Int { val nextOpened = opened + node val openedFlowRate = nextOpened.sumOf { flowRates[it]!! } return distances .filter { (path, distance) -> path.first == node && !opened.contains(path.second) && distance <= countDown - 1 } .map { (path, distance) -> Pair(path.second, distance) } .map { (nextNode, distance) -> val nextCountDown = countDown - distance - 1 val nextPressure = pressure + (distance + 1) * openedFlowRate maxPath(nextNode, nextCountDown, nextOpened, nextPressure) }.plus(pressure + countDown * openedFlowRate) .max() } fun part1(): Int { val startingValve = "AA" distances = calculateDistancesBetweenValves(workingValves + startingValve) return maxPath(startingValve, 30) } parseInput("Day16_test") check(part1() == 1651) parseInput("Day16") println(part1()) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day16Kt.class", "javap": "Compiled from \"Day16.kt\"\npublic final class Day16Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n 4: invokespecial...
buczebar__advent-of-code__cdb6fe3/src/Day13.kt
fun main() { fun parseArray(arrayText: String): List<Any> { fun nodeToList(node: Node): List<Any> { return node.children.map { child -> if (child is Leaf) { child.value ?: emptyList<Any>() } else { nodeToList(child) } } } fun addLeaf(builder: StringBuilder, node: Node?) { if (builder.isNotEmpty()) { node?.addChild(Leaf(node, builder.toString().toInt())) builder.clear() } } var node: Node? = null val numberBuilder = StringBuilder() arrayText.forEach { when { it == '[' -> { val newNode = Node(node) node?.addChild(newNode) node = newNode } it.isDigit() -> { numberBuilder.append(it) } it == ',' -> { addLeaf(numberBuilder, node) } it == ']' -> { addLeaf(numberBuilder, node) node = node?.parent ?: node } } } return node?.let { nodeToList(it) } ?: emptyList() } fun compare(first: Any?, second: Any?): Int { if (first is Int && second is Int) { return first.compareTo(second) } else if (first is Int && second is List<*>) { return compare(listOf(first), second) } else if (first is List<*> && second is Int) { return compare(first, listOf(second)) } else if (first is List<*> && second is List<*>) { val pairs = first.zip(second) for (pair in pairs) { val result = compare(pair.first, pair.second) if (result != 0) { return result } } return first.size.compareTo(second.size) } else { return 0 } } fun part1(inputName: String) = readGroupedInput(inputName) .map { group -> group.split("\n").map { parseArray(it) }.pair() }.map { compare(it.first, it.second) }.mapIndexed { index, it -> if (it < 0) index + 1 else 0 }.sum() fun part2(inputName: String): Int { val dividerPackets = listOf(listOf(listOf(2)), listOf(listOf(6))) val packets = readInput(inputName) .filter { it.isNotBlank() } .map { parseArray(it) } .toMutableList() .also { it.addAll(dividerPackets) } val sortedPackets = packets.sortedWith { o1, o2 -> compare(o1, o2) } return dividerPackets.map { sortedPackets.indexOf(it) + 1 }.factorial() } val testInputName = "Day13_test" check(part1(testInputName) == 13) check(part2(testInputName) == 140) val inputName = "Day13" println(part1(inputName)) println(part2(inputName)) } private open class Node(parent: Node?) { var parent: Node? = parent private set private val _children: MutableList<Node> = mutableListOf() val children: List<Node> get() = _children.toList() fun addChild(child: Node) { child.parent = this _children.add(child) } } private class Leaf(parent: Node?, val value: Int?) : Node(parent)
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class Day13Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day13_test\n 2: astore_0\n 3: aload_0\n 4: invokestati...
buczebar__advent-of-code__cdb6fe3/src/Day03.kt
fun main() { fun Char.getPriority() = (('a'..'z') + ('A'..'Z')).indexOf(this) + 1 fun part1(input: List<String>) = input.map { sack -> sack.chunked(sack.length / 2).map { comp -> comp.toList() } } .map { (comp1, comp2) -> (comp1 intersect comp2.toSet()).single() } .sumOf { it.getPriority() } fun part2(input: List<String>) = input.chunked(3) .map { (a, b, c) -> (a.toSet() intersect b.toSet() intersect c.toSet()).single() } .sumOf { it.getPriority() } val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03_test\n 2: invokestatic #14 // Method UtilsK...
buczebar__advent-of-code__cdb6fe3/src/Day12.kt
private typealias MapOfHeights = List<List<Char>> private fun Char.elevation() = when (this) { 'S' -> 0 // a 'E' -> 25 // z else -> ('a'..'z').indexOf(this) } private fun MapOfHeights.getFirstPositionOf(mark: Char): Position { forEachIndexed { index, row -> if (row.contains(mark)) { return row.indexOf(mark) to index } } return -1 to -1 } private fun MapOfHeights.getAllPositionsWithElevation(elevation: Int): List<Position> { val positions = mutableListOf<Position>() forEachIndexed { colIndex, items -> items.forEachIndexed { rowIndex, item -> if (item.elevation() == elevation) { positions.add(rowIndex to colIndex) } } } return positions } private fun MapOfHeights.getPossibleMoves(position: Position): List<Position> { val currentHeight = this[position.y][position.x].elevation() val directions = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1) return directions .map { direction -> position + direction } .filter { it.x in first().indices && it.y in indices } .filter { this[it.y][it.x].elevation() - currentHeight <= 1 } } private fun MapOfHeights.findShortestPathLength( start: Position, destination: Position ): Int { val queue = mutableListOf(start) val visited = mutableSetOf(start) val predecessors = mutableMapOf<Position, Position>() while (queue.isNotEmpty()) { val currentItem = queue.popHead() val availableMoves = getPossibleMoves(currentItem) availableMoves.forEach { next -> if (!visited.contains(next)) { visited.add(next) predecessors[next] = currentItem queue.add(next) if (next == destination) { queue.clear() return@forEach } } } } var lenth = 0 var crawl: Position? = destination while (predecessors[crawl] != null) { crawl = predecessors[crawl] lenth++ } return lenth } fun main() { fun part1(mapOfHeights: MapOfHeights): Int { val (start, destination) = mapOfHeights.getFirstPositionOf('S') to mapOfHeights.getFirstPositionOf('E') return mapOfHeights.findShortestPathLength(start, destination) } fun part2(mapOfHeights: MapOfHeights): Int { val allStartingPoints = mapOfHeights.getAllPositionsWithElevation(0) val destination = mapOfHeights.getFirstPositionOf('E') val allPaths = allStartingPoints.map { startingPoint -> mapOfHeights.findShortestPathLength( startingPoint, destination ) } return allPaths.filter { it != 0 }.min() } val testInput = readInput("Day12_test").map { it.toList() } check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12").map { it.toList() } println(part1(input)) println(part2(input)) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n private static final int elevation(char);\n Code:\n 0: iload_0\n 1: lookupswitch { // 2\n 69: 32\n 83: 28\n ...
buczebar__advent-of-code__cdb6fe3/src/Day10.kt
import kotlin.math.abs fun main() { fun getValuesInEachCycle(input: List<String>): List<Int> { val valuesInCycles = mutableListOf(1) var valueAfterLastCycle = valuesInCycles.first() input.forEach { instruction -> when { instruction.startsWith("noop") -> { valuesInCycles.add(valueAfterLastCycle) } instruction.startsWith("addx") -> { val (_, value) = instruction.splitWords() repeat(2) { valuesInCycles.add((valueAfterLastCycle)) } valueAfterLastCycle += value.toInt() } } } return valuesInCycles } fun part1(input: List<String>): Int { val indexes = listOf(20, 60, 100, 140, 180, 220) val cycles = getValuesInEachCycle(input) return indexes.sumOf { if (it < cycles.size) cycles[it] * it else 0 } } fun part2(input: List<String>) { getValuesInEachCycle(input) .dropHead() .chunked(40) .map { row -> row.forEachIndexed { index, x -> print( when { abs(x - index) <= 1 -> "#" else -> "." } ) } println() } } val testInput = readInput("Day10_test") check(part1(testInput) == 13_140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day10Kt.class", "javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day10_test\n 2: invokestatic #14 // Method UtilsK...
buczebar__advent-of-code__cdb6fe3/src/Day09.kt
import java.lang.IllegalArgumentException import kotlin.math.abs typealias Point = Pair<Int, Int> private fun Point.isTouching(point: Point) = abs(first - point.first) < 2 && abs(second - point.second) < 2 fun main() { fun parseInput(name: String) = readInput(name).map { it.splitWords() } .map { (direction, steps) -> direction to steps.toInt() } fun getAllKnotsPositions(moves: List<Pair<String, Int>>, numOfKnots: Int): List<List<Point>> { fun getNextHeadPosition(position: Point, direction: String) = when (direction) { "L" -> Pair(position.first - 1, position.second) "R" -> Pair(position.first + 1, position.second) "U" -> Pair(position.first, position.second + 1) "D" -> Pair(position.first, position.second - 1) else -> throw IllegalArgumentException("Wrong direction $direction") } fun followingPosition(currentPosition: Point, leaderPosition: Point) = Point( currentPosition.first + leaderPosition.first.compareTo(currentPosition.first), currentPosition.second + leaderPosition.second.compareTo(currentPosition.second) ) val startingPoint = 0 to 0 val knotsPositions = List(numOfKnots) { mutableListOf(startingPoint) } moves.forEach { (direction, steps) -> repeat(steps) { val headPositions = knotsPositions.head() headPositions.add(getNextHeadPosition(headPositions.last(), direction)) knotsPositions.forEachIndexed { index, currentKnotPositions -> if (index == 0) return@forEachIndexed val previousKnotPosition = knotsPositions[index - 1].last() val currentKnotPosition = currentKnotPositions.last() if (!previousKnotPosition.isTouching(currentKnotPosition)) { currentKnotPositions.add(followingPosition(currentKnotPosition, previousKnotPosition)) } else { currentKnotPositions.add(currentKnotPosition) } } } } return knotsPositions } fun part1(input: List<Pair<String, Int>>): Int { return getAllKnotsPositions(input, 2).last().distinct().size } fun part2(input: List<Pair<String, Int>>): Int { return getAllKnotsPositions(input, 10).last().distinct().size } val testInput = parseInput("Day09_test") val testInputPart2 = parseInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInputPart2) == 36) val input = parseInput("Day09") println(part1(input)) println(part2(input)) }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n private static final boolean isTouching(kotlin.Pair<java.lang.Integer, java.lang.Integer>, kotlin.Pair<java.lang.Integer, java.lang.Integer>);\n Code:\n 0: aload_...
buczebar__advent-of-code__cdb6fe3/src/Day08.kt
fun main() { fun parseInput(name: String) = readInput(name).map { it.toList() }.map { row -> row.map { height -> height.digitToInt() } } fun getListOfTrees(input: List<List<Int>>): List<Tree> { val columns = input.transpose() val (width, height) = columns.size to input.size val resultList = mutableListOf<Tree>() input.forEachIndexed { rowIndex, row -> columns.forEachIndexed { colIndex, column -> resultList.add(Tree( height = input[rowIndex][colIndex], allOnLeft = row.subList(0, colIndex).reversed(), allOnRight = colIndex.takeIf { it < width - 1 }?.let { row.subList(it + 1, width) } ?: emptyList(), allOnTop = column.subList(0, rowIndex).reversed(), allOnBottom = rowIndex.takeIf { it < height - 1 }?.let { column.subList(it + 1, height) } ?: emptyList() )) } } return resultList } fun part1(input: List<Tree>) = input.count { it.isVisible } fun part2(input: List<Tree>) = input.maxOfOrNull { it.scenicScore } val testInput = getListOfTrees(parseInput("Day08_test")) check(part1((testInput)) == 21) check(part2(testInput) == 8) val input = getListOfTrees(parseInput("Day08")) println(part1(input)) println(part2(input)) } private data class Tree( val height: Int, val allOnLeft: List<Int>, val allOnRight: List<Int>, val allOnTop: List<Int>, val allOnBottom: List<Int> ) { private val maxInAllDirections: List<Int> get() = allDirections.map { it.takeIf { it.isNotEmpty() }?.max() ?: 0 } private val allDirections: List<List<Int>> get() = listOf(allOnLeft, allOnRight, allOnTop, allOnBottom) private val visibleTreesInAllDirection: List<Int> get() = allDirections.map { it.numberOfVisibleTrees() } val isVisible: Boolean get() = allDirections.any { it.isEmpty() }.or(maxInAllDirections.min() < height) val scenicScore: Int get() = visibleTreesInAllDirection.reduce { acc, numOfTrees -> acc * numOfTrees } private fun List<Int>.numberOfVisibleTrees(): Int = indexOfFirst { it >= height }.takeIf { it >= 0 }?.plus(1) ?: size }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day08_test\n 2: invokestatic #12 // Method main$p...
buczebar__advent-of-code__cdb6fe3/src/Day11.kt
import java.lang.IllegalArgumentException private fun parseMonkey(monkeyData: String): Monkey { return Monkey.build { monkeyData.lines().forEach { line -> with(line.trim()) { when { startsWith("Monkey") -> { id = getAllInts().first() } startsWith("Starting items:") -> { items = getAllInts().map { it.toLong() }.toMutableList() } startsWith("Operation") -> { operation = "\\w+ [*+-/]? \\w+".toRegex().find(this)?.value.orEmpty() } startsWith("Test:") -> { testDivisor = getAllInts().first().toLong() } startsWith("If true:") -> { idIfTrue = getAllInts().first() } startsWith("If false:") -> { idIfFalse = getAllInts().first() } } } } } } private fun parseInput(name: String) = readGroupedInput(name).map { parseMonkey(it) } fun main() { fun simulate(monkeys: List<Monkey>, rounds: Int, reduceOperation: (Long) -> Long): List<Long> { val inspectionCounters = MutableList(monkeys.size) { 0L } repeat(rounds) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newItemValue = reduceOperation(monkey.calculate(item)) monkeys[monkey.getMonkeyIdToPass(newItemValue)].items.add(newItemValue) inspectionCounters[monkey.id]++ } monkey.items.clear() } } return inspectionCounters } fun monkeyBusiness(inspections: List<Long>) = inspections .sortedDescending() .take(2) .factorial() fun part1(monkeys: List<Monkey>) = monkeyBusiness(simulate(monkeys, 20) { it / 3 }) fun part2(monkeys: List<Monkey>) = monkeyBusiness( simulate(monkeys, 10_000) { it % monkeys.map { monkey -> monkey.testDivisor }.factorial() } ) check(part1(parseInput("Day11_test")) == 10605L) check(part2(parseInput("Day11_test")) == 2713310158L) println(part1(parseInput("Day11"))) println(part2(parseInput("Day11"))) } private data class Monkey( val id: Int, val items: MutableList<Long> = mutableListOf(), private val operation: String, val testDivisor: Long, private val idIfTrue: Int, private val idIfFalse: Int ) { private constructor(builder: Builder) : this( builder.id, builder.items, builder.operation, builder.testDivisor, builder.idIfTrue, builder.idIfFalse ) fun getMonkeyIdToPass(value: Long) = idIfTrue.takeIf { value % testDivisor == 0L } ?: idIfFalse fun calculate(value: Long): Long { val (_, type, second) = operation.takeIf { it.isNotEmpty() }?.splitWords() ?: return -1L val arg = if (second == "old") value else second.toLong() return when (type) { "+" -> value + arg "-" -> value - arg "*" -> value * arg "/" -> value / arg else -> throw IllegalArgumentException("wrong operation type $operation") } } companion object { inline fun build(block: Builder.() -> Unit) = Builder().apply(block).build() } class Builder { var id = 0 var items: MutableList<Long> = mutableListOf() var operation: String = "" var testDivisor: Long = 0L var idIfTrue: Int = 0 var idIfFalse: Int = 0 fun build() = Monkey(this) } }
[ { "class_path": "buczebar__advent-of-code__cdb6fe3/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt {\n private static final Monkey parseMonkey(java.lang.String);\n Code:\n 0: getstatic #12 // Field Monkey.Companion:LMonkey$Companion;\n 3: ...
davidcurrie__advent-of-code-2021__dd37372/src/day24/result.kt
import java.io.File fun main() { val programs = File("src/day24/input.txt").readText().split("inp w\n").drop(1) .map { it.split("\n").dropLast(1).map { it.split(" ") } } val variables = programs.map { Variables(it[3][2].toInt(), it[4][2].toInt(), it[14][2].toInt()) } val solutions = solve(variables) println(solutions.maxOf { it }) println(solutions.minOf { it }) } data class Variables(val zDiv: Int, val xAdd: Int, val yAdd: Int) { fun execute(input: Int, zReg: Int): Int { val x = if (((zReg % 26) + xAdd) != input) 1 else 0 return ((zReg / zDiv) * ((25 * x) + 1)) + ((input + yAdd) * x) } } fun solve(variablesList: List<Variables>): List<String> { var validZOutputs = setOf(0) val validZsByIndex = variablesList.reversed().map { variables -> (1..9).associateWith { input -> (0..10000000).filter { z -> variables.execute(input, z) in validZOutputs }.toSet() }.also { validZs -> validZOutputs = validZs.values.flatten().toSet() } }.reversed() fun findModelNumbers(index: Int, z: Int): List<String> { val inputs = validZsByIndex[index].entries.filter { z in it.value }.map { it.key } return if (index == 13) inputs.map { it.toString() } else inputs.flatMap { input -> val nextZ = variablesList[index].execute(input, z) findModelNumbers(index + 1, nextZ).map { input.toString() + it } } } return findModelNumbers(0, 0) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day04.kt
import java.io.File fun main() { fun stringToPair(data: String) : IntRange { val nums = data.split("-") return IntRange(nums[0].toInt(), nums[1].toInt()) } fun processInput(pair: String): Pair<IntRange, IntRange> { val areas = pair.split(",") .map { stringToPair(it) } return Pair(areas.first(), areas.last()) } fun part1(input: List<String>): Int { return input.map { processInput(it) } .count { pair -> pair.first.subsumes(pair.second) || pair.second.subsumes(pair.first) } } fun part2(input: List<String>): Int { return input.map { processInput(it) } .count { pair -> pair.first.intersect(pair.second).any() } } val testInput = listOf( "2-4,6-8", "2-3,4-5", "5-7,7-9", "2-8,3-7", "6-6,4-6", "2-6,4-8" ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 2) check(part2(testInput) == 4) val input = File("./src/resources/Day04.txt").readLines() println(part1(input)) println(part2(input)) } fun IntRange.subsumes(other: IntRange): Boolean = contains(other.first) && contains(other.last)
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: bipush 6\n 2: anewarray #8 // class java/lang/String\n 5: ast...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day05.kt
import java.io.File fun main() { fun dataToParts(input: String): Pair<String, String> { val parts = input.split("\n\n") return parts[0] to parts[1] } fun initStacks(input: String): Map<Int, MutableList<Char>>{ val lines = input.split("\n").reversed() val stacks = lines[0].filter { it != ' ' }.map { c -> c.digitToInt() to mutableListOf<Char>() }.toMap() lines.drop(1).forEach { line -> line.chunked(4).forEachIndexed { i, s -> if (s[1] != ' ') stacks[i+1]?.add(s[1]) } } return stacks } fun readMoves(input: String): List<Triple<Int, Int, Int>> { return input.lines().map { line -> line.split(" ")} .map { Triple(it[1].toInt(), it[3].toInt(), it[5].toInt())} } fun part1(input: String): String { val (stackData, moveData) = dataToParts(input) val stacks = initStacks(stackData) val moves = readMoves(moveData) moves.forEach { move -> repeat (move.first) { stacks[move.third]?.add(stacks[move.second]?.removeLast() ?: ' ') } } return stacks.map { it.value.last() }.joinToString("") } fun part2(input: String): String { val (stackData, moveData) = dataToParts(input) val stacks = initStacks(stackData) val moves = readMoves(moveData) moves.forEach { move -> val crates = stacks[move.second]?.takeLast(move.first) ?: listOf() repeat(move.first) { stacks[move.second]?.removeLast() } stacks[move.third]?.addAll(crates) } return stacks.map { it.value.last() }.joinToString("") } val testInput = listOf<String>( " [D]", "[N] [C]", "[Z] [M] [P]", " 1 2 3", "", "move 1 from 2 to 1", "move 3 from 1 to 3", "move 2 from 2 to 1", "move 1 from 1 to 2" ).joinToString("\n") // test if implementation meets criteria from the description, like: val test = part1(testInput) println(test) check(test == "CMZ") // check(part2(testInput) == 42) val input = File("./src/resources/Day05.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: bipush 9\n 2: anewarray #8 // class java/lang/String\n 5: ast...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day07.kt
import java.io.File import java.util.Dictionary fun main() { fun buildFilesystem(data: List<String>): Directory { val root = Directory("/", null) var cwd = root data.forEachIndexed { i, line -> val curr = line.split(" ") when { curr[1] == "cd" -> cwd = if (curr[2] == "/") root else if (curr[2] == "..") cwd.parent ?: cwd else cwd.contents.firstOrNull { it.name == curr[2] } as? Directory ?: Directory(curr[2], cwd).also { cwd.contents.add(it) } curr[0] == "dir" -> cwd.contents.firstOrNull { it.name == curr[1] } ?: cwd.contents.add(Directory(curr[1], cwd)) curr[1] == "ls" -> {} curr[0].matches(Regex("\\d+")) -> cwd.contents.firstOrNull { it.name == curr[1] } ?: cwd.contents.add(Data(curr[1], curr[0].toInt(), cwd)) } } return root } fun part1(input: List<String>): Int { val fs = buildFilesystem(input) // fs.filetree().forEach { println(it) } val bigdirs = fs.listAll().filter { it is Directory && it.size <= 100000 } return bigdirs.sumOf { it.size } } fun part2(input: List<String>): Int { val fs = buildFilesystem(input) val dirs = fs.listAll().filterIsInstance<Directory>() val target = fs.size - 4e7 return dirs.filter { it.size >= target }.minBy { it.size }.size } val testInput = listOf<String>( "$ cd /", "$ ls", "dir a", "14848514 b.txt", "8504156 c.dat", "dir d", "$ cd a", "$ ls", "dir e", "29116 f", "2557 g", "62596 h.lst", "$ cd e", "$ ls", "584 i", "$ cd ..", "$ cd ..", "$ cd d", "$ ls", "4060174 j", "8033020 d.log", "5626152 d.ext", "7214296 k", ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 95437) // check(part2(testInput) == 42) val input = File("./src/resources/Day07.txt").readLines() println(part1(input)) println(part2(input)) } sealed class FsNode(val name: String, val parent: Directory?) { abstract val size: Int abstract fun listAll() : List<FsNode> } class Directory( name: String, parent: Directory?, val contents: MutableList<FsNode> = mutableListOf() ) : FsNode(name, parent) { override val size get() = contents.sumOf { it.size } override fun toString(): String { return "- $name (dir, size = $size)" //\n " + contents.sortedBy { it.name }.joinToString("\n ") } fun filetree() : List<String> { return listOf("$this") + contents.flatMap { (it as? Directory)?.filetree() ?: listOf("$it") }.map { " $it" } } override fun listAll() : List<FsNode> = listOf(this) + contents.flatMap { it.listAll() } } class Data(name: String, override val size: Int, parent: Directory) : FsNode(name, parent) { override fun toString(): String { return "- $name (file, size = $size)" } override fun listAll() : List<FsNode> = listOf(this) }
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: bipush 23\n 2: anewarray #8 // class java/lang/String\n 5: as...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day03.kt
import java.io.File fun main() { fun part1(input: List<String>): Int { return input.map { sack -> sack.bisect() } .map { parts -> parts.first.intersect(parts.second).first() } .sumOf { it.toScore() } } fun part2(input: List<String>): Int { return input.chunked(3) .map { sacks -> sacks[0].intersect(sacks[1]).toString().intersect(sacks[2]).firstOrNull() } .sumOf { it?.toScore() ?: 0 } } val testInput = listOf<String>( "vJrwpWtwJgWrhcsFMMfFFhFp", "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL", "PmmdzqPrVvPwwTWBwg", "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", "ttgJtRGJQctTZtZT", "CrZsJsPPZsGzwwsLwLmpwMDw" ) // test if implementation meets criteria from the description, like: println(part1(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = File("./src/resources/Day03a.txt").readLines() println(part1(input)) println(part2(input)) } fun Char.toScore() : Int = (if (this.isLowerCase()) this - 'a' else this - 'A' + 26) + 1 fun CharSequence.intersect(list2: CharSequence) : List<Char> { return this.filter { list2.contains(it) }.toList() } fun String.bisect() : Pair<String, String> = Pair(this.substring(0, this.length/2), this.substring(this.length/2, this.length))
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: bipush 6\n 2: anewarray #8 // class java/lang/String\n 5: ast...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day02.kt
import java.io.File fun main() { fun part1(input: List<String>): Int { return input.sumOf { getScore(it) } } fun part2(input: List<String>): Int { return input.sumOf { getScore(getGame(it)) } } val testInput = listOf( "A Y", "B X", "C Z" ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 15) check(part2(testInput) == 12) val input = File("./src/resources/Day02a.txt").readLines() println(part1(input)) println(part2(input)) } fun getScore(game: String) : Int = game[2] - 'W' + when { game[0] == (game[2] - 23) -> 3 wins.contains(game) -> 6 else -> 0 } fun getGame(code: String) : String = when (code[2]) { 'Y' -> ties 'X' -> losses 'Z' -> wins else -> listOf() }.first { code[0] == it[0] } val wins = listOf("A Y", "B Z", "C X") val losses = listOf("A Z", "B X", "C Y") val ties = listOf("A X", "B Y", "C Z")
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n private static final java.util.List<java.lang.String> wins;\n\n private static final java.util.List<java.lang.String> losses;\n\n private static final jav...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day12.kt
import java.io.File import kotlin.math.min fun main() { val c0 = '`' fun getNodes(input: List<String>): List<List<Node>> = input.map { row -> row.map { c -> val height = when (c) { 'S' -> 0; 'E' -> 'z' - c0; else -> c - c0 } Node(height, isStart = c == 'S', isEnd = c == 'E') } } fun buildNeighbors(nodes: List<List<Node>>) { nodes.forEachIndexed { y, row -> row.forEachIndexed { x, node -> listOf(x to y-1, x to y+1, x+1 to y, x-1 to y).forEach { if (it.first in row.indices && it.second in nodes.indices && nodes[it.second][it.first].height <= node.height + 1) node.neighbors.add(nodes[it.second][it.first]) } } } } fun dijkstra(data: MutableList<Node>) { while(data.any()) { val v = data.removeFirst() v.neighbors.forEach { if (v.distance + 1 < it.distance) { it.distance = v.distance + 1 data.add(it) } data.sortBy { n -> n.distance } } } } fun part1(input: List<String>): Int { val nodes = getNodes(input) val start = nodes.flatten().first { it.isStart } buildNeighbors(nodes) start.distance = 0 val toProcess = mutableListOf(start) dijkstra(toProcess) // nodes.forEach {row -> // row.forEach { print(if (it.distance == Int.MAX_VALUE) " . " else String.format("%3d", it.distance) + if (it.isEnd) "*" else " ")} // println() // } // println() return nodes.flatten().firstOrNull { it.isEnd }?.distance ?: 0 } fun part2(input: List<String>): Int { val nodes = getNodes(input) val start = nodes.flatten().first { it.isStart } val end = nodes.flatten().first { it.isEnd } buildNeighbors(nodes) start.distance = 0 val toProcess = mutableListOf(start) dijkstra(toProcess) val starts = nodes.flatten().filter { it.height == 'a' - c0 && it.distance < Int.MAX_VALUE }.sortedByDescending { it.distance }.toMutableList() var shortest = Int.MAX_VALUE starts.forEach { newStart -> nodes.flatten().forEach { it.distance = Int.MAX_VALUE } newStart.distance = 0 toProcess.add(newStart) dijkstra(toProcess) shortest = min(shortest, end.distance) } return shortest } val testInput = listOf( "Sabqponm", "abcryxxl", "accszExk", "acctuvwj", "abdefghi" ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 31) check(part2(testInput) == 29) val input = File("./src/resources/Day12.txt").readLines() println(part1(input)) println(part2(input)) } data class Node( val height: Int, var distance: Int = Int.MAX_VALUE, val neighbors: MutableList<Node> = mutableListOf(), val isStart: Boolean = false, val isEnd: Boolean = false)
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class Day12Kt {\n public static final void main();\n Code:\n 0: bipush 96\n 2: istore_0\n 3: iconst_5\n 4: anewarray #8 ...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day11.kt
import java.io.File import kotlin.collections.ArrayDeque fun main() { fun readMonkeys(input: List<String>) = input.map { data -> val lines = data.split("\n") Monkey( ArrayDeque(lines[1].split(": ")[1].split(", ").map { it -> it.toLong() }), lines[2].split("=")[1].toFunction(), lines[3].split(" ").last().toInt(), lines[4].split(" ").last().toInt(), lines[5].split(" ").last().toInt() ) } fun part1(input: List<String>): Int { val monkeys = readMonkeys(input) repeat(20) { monkeys.forEach { monkey -> while (monkey.hasItems()) { val (newItem, target) = monkey.inspectNextPt1() monkeys[target].catch(newItem) } } } return monkeys.sortedBy { it.inspectionCount }.takeLast(2).fold(1) { acc, m -> acc * m.inspectionCount} } fun part2(input: List<String>): Long { val monkeys = readMonkeys(input) val checkProduct = monkeys.fold(1) { acc, m -> acc * m.testDiv } repeat(10000) { monkeys.forEach { monkey -> while (monkey.hasItems()) { val (newItem, target) = monkey.inspectNextPt2() monkeys[target].catch(newItem % checkProduct) } } } val topTwo = monkeys.map { it.inspectionCount }.sorted().takeLast(2) return 1L * topTwo[0] * topTwo[1] } val testInput = """Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1 """.split("\n\n") // test if implementation meets criteria from the description, like: check(part1(testInput) == 10605) check(part2(testInput) == 2713310158L) val input = File("./src/resources/Day11.txt").readText().split("\n\n") println(part1(input)) println(part2(input)) } class Monkey(val items: ArrayDeque<Long>, val op: (Long) -> Long, val testDiv: Int, val ifTrue: Int, val ifFalse: Int) { var inspectionCount = 0 private set fun catch(item: Long) { items.add(item) } fun hasItems() = items.any() private fun inspectNext(divisor: Int): Pair<Long, Int> { inspectionCount++ val newWorry = op(items.removeFirst()) / divisor return newWorry to if (newWorry % testDiv == 0L ) ifTrue else ifFalse } fun inspectNextPt1(): Pair<Long, Int> = inspectNext(3) fun inspectNextPt2(): Pair<Long, Int> = inspectNext(1) } fun String.toFunction(): (Long) -> Long { if (this.trim() == "old * old") return { old -> old * old } val tokens = this.trim().split(" ") if (tokens[1] == "+") return { old: Long -> old + tokens[2].toInt() } if (tokens[1] == "*") return { old: Long -> old * tokens[2].toInt() } return { old: Long -> old * tokens[2].toInt() } }
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day11Kt$main$part1$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class Day11Kt$main$part1$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public Day11Kt$main$part1$$inlined$sortedBy$1();\n ...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day09.kt
import java.io.File import kotlin.math.abs import kotlin.math.round import kotlin.math.roundToInt fun main() { fun part1(input: List<String>): Int { val rope = Rope() input.forEach { moveData -> val move = moveData.split(" ") repeat(move[1].toInt()) { rope.move(Direction.valueOf(move[0])) } } return rope.tailPositions.size } fun part2(input: List<String>): Int { val rope = Rope(10) input.forEach { moveData -> val move = moveData.split(" ") repeat(move[1].toInt()) { rope.move(Direction.valueOf(move[0])) } } return rope.tailPositions.size } val testInput = listOf<String>( "R 4", "U 4", "L 3", "D 1", "R 4", "D 1", "L 5", "R 2", ) val testInput2 = listOf( "R 5", "U 8", "L 8", "D 3", "R 17", "D 10", "L 25", "U 20", ) // test if implementation meets criteria from the description, like: println(part1(testInput)) check(part1(testInput) == 13) println(part2(testInput2)) check(part2(testInput2) == 36) val input = File("./src/resources/Day09.txt").readLines() println(part1(input)) println(part2(input)) } class Rope(val length: Int = 2) { val knots = List(length) { _ -> Knot() } val tailPositions = mutableSetOf("0,0") private val head = knots[0] private fun isTouchingPrevious(index: Int) = abs(knots[index].x-knots[index-1].x) < 2 && abs(knots[index].y-knots[index-1].y) < 2 infix fun move(direction: Direction) { when (direction) { Direction.U -> head.y++ Direction.D -> head.y-- Direction.L -> head.x-- Direction.R -> head.x++ } (1 until knots.size).forEach { i -> if (!isTouchingPrevious(i)) { if (knots[i-1].x == knots[i].x || knots[i-1].y == knots[i].y) { knots[i].x = (knots[i-1].x + knots[i].x) / 2 knots[i].y = (knots[i-1].y + knots[i].y) / 2 } else { knots[i].x += if (knots[i-1].x > knots[i].x) 1 else -1 knots[i].y += if (knots[i-1].y > knots[i].y) 1 else -1 } } } tailPositions.add("${knots.last().x},${knots.last().y}") // println ("H -> ($headX, $headY), T -> ($tailX, $tailY)") // (0 .. 5).map { r -> // (0 .. 5).joinToString("") { c -> // if (headX == c && headY == r) "H" else if (tailX == c && tailY == r) "T" else "." // } // }.reversed().forEach { println(it) } // println() } } enum class Direction { U,D,L,R } data class Knot(var x: Int = 0, var y: Int = 0)
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n public static final void main();\n Code:\n 0: bipush 8\n 2: anewarray #8 // class java/lang/String\n 5: ast...
dcbertelsen__advent-of-code-2022-kotlin__9d22341/src/Day08.kt
import java.io.File fun main() { fun sightAlongAndMark(trees: List<Tree>) { var max = -1 trees.forEach { t -> if (t.height > max) { t.canSee(); max = t.height }} } fun getVisibleTrees(trees: List<Tree>): Int { var count = 0 var max = 0 for (tree in trees.subList(1, trees.size)) { count++ max = maxOf(max, tree.height) if (tree.height >= trees[0].height) { break } } return count } fun <T> getColumns(ts: List<List<T>>): List<List<T>> { return (0 until ts[0].size).map { i -> ts.map { r -> r[i] }.toList() }.toList() } fun getDirectionLists(trees: List<List<Tree>>, row: Int, col: Int): List<List<Tree>> { val directions = mutableListOf<List<Tree>>() directions.add(trees[row].subList(0, col+1).reversed()) // left directions.add(trees[row].subList(col, trees[row].size)) // right val column = getColumns(trees)[col] directions.add(column.subList(0, row+1).reversed()) // top directions.add(column.subList(row, column.size)) // bottom return directions.toList() } fun part1(input: List<String>): Int { val forest = input.map { r -> r.map { Tree(it.digitToInt()) }} forest.forEach { sightAlongAndMark(it) } forest.forEach { sightAlongAndMark(it.reversed()) } val columns = getColumns(forest) columns.forEach { sightAlongAndMark(it) } columns.forEach { sightAlongAndMark(it.reversed()) } // forest.forEach { r -> println(r.joinToString("") { t -> "${t}" }) } println() return forest.flatten().count { it.isVisible } } fun part2(input: List<String>): Int { val forest = input.map { r -> r.map { Tree(it.digitToInt()) }} forest.forEachIndexed { i, row -> row.forEachIndexed { j, tree -> val lists = getDirectionLists(forest, i, j) tree.scenicScore = lists.map { getVisibleTrees(it) }.fold(1) { acc, it -> it * acc } } } // forest.forEach { r -> println(r.joinToString(" ") { t -> "${t.scenicScore}" }) } println() return forest.flatten().maxOf { it.scenicScore } } val testInput = listOf<String>( "30373", "25512", "65332", "33549", "35390" ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 21) check(part2(testInput) == 8) val input = File("./src/resources/Day08.txt").readLines() println(part1(input)) println(part2(input)) } class Tree(val height: Int, var isVisible: Boolean = false) { fun canSee() { isVisible = true } override fun toString(): String = if (isVisible) "*" else " " var scenicScore = -1 }
[ { "class_path": "dcbertelsen__advent-of-code-2022-kotlin__9d22341/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: anewarray #8 // class java/lang/String\n 4: astore_1\n...
mrwhoknows55__advent-of-code-2022__f307e52/src/Day05.kt
import java.io.File import java.util.Stack fun main() { val inputPair = getInputPair("src/day05_input.txt") part1(inputPair) } fun part1(inputPair: Pair<List<Stack<Char>>, List<Triple<Int, Int, Int>>>) { val stacks = inputPair.first val inputs = inputPair.second inputs.forEach { for (i in 0 until it.first) { if (stacks.size >= it.second) { val selected = stacks[it.second - 1] if (stacks.size >= it.third && selected.isNotEmpty()) { stacks[it.third - 1].push(selected.peek()) selected.pop() } } } } val ans = stacks.joinToString(separator = "") { it.peek().toString() } println(ans) } fun getInputPair(fileName: String): Pair<List<Stack<Char>>, List<Triple<Int, Int, Int>>> { val fileInput = File(fileName).readText().split("\n\n") val other = fileInput[1].split("\n") val inputs = other.map { val words = it.split(" ") Triple(words[1].toInt(), words[3].toInt(), words[5].toInt()) } val matrix = fileInput.first() var str = "" matrix.forEachIndexed { i, c -> if (i % 4 == 0) { str += "[" } else if (i % 2 == 0) { str += "]" } else { str += c } } val lets = str.replace("[ ]", "-").replace("[", "").replace("]", "").replace(" ", "").split("\n").map { it.split("").filter { it.isNotBlank() } } val length = lets.last().size val letters = lets.dropLast(1) val stacks = mutableListOf<Stack<Char>>() for (i in 0 until length) { stacks.add(Stack()) for (j in 0 until length) { if (letters.size > j && letters[j].size > i) letters[j][i].let { if (it != "-") stacks[i].add(it.first()) } } stacks[i].reverse() } return Pair(stacks.toList(), inputs) }
[ { "class_path": "mrwhoknows55__advent-of-code-2022__f307e52/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day05_input.txt\n 2: invokestatic #12 ...
mrwhoknows55__advent-of-code-2022__f307e52/src/Day02.kt
import java.io.File fun main() { val input = File("src/day02_input.txt").readText().split("\n") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { var score = 0 input.forEach { val oppMove = Move.getMoveObj(it[0]) ?: return@part1 (score) val myMove = Move.getMoveObj(it[2]) ?: return@part1 (score) score += myMove.score when { myMove.winsTo == oppMove.score -> score += 6 myMove.score == oppMove.score -> score += 3 myMove.losesTo == oppMove.score -> score += 0 } } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { val oppMove = Move.getMoveObj(it[0]) ?: return@part2 (score) val myMove = Move.getMoveObj(it[2]) ?: return@part2 (score) when (myMove) { is Move.Rock -> { score += oppMove.winsTo score += 0 } is Move.Paper -> { score += oppMove.score score += 3 } is Move.Scissors -> { score += oppMove.losesTo score += 6 } } } return score } sealed class Move( val score: Int, val winsTo: Int, val losesTo: Int, ) { object Rock : Move(1, 3, 2) object Paper : Move(2, 1, 3) object Scissors : Move(3, 2, 1) companion object { fun getMoveObj(moveChar: Char): Move? { return when (moveChar) { 'A' -> Rock 'X' -> Rock 'B' -> Paper 'Y' -> Paper 'C' -> Scissors 'Z' -> Scissors else -> null } } } }
[ { "class_path": "mrwhoknows55__advent-of-code-2022__f307e52/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
BjornvdLaan__KotlinTestApproachExamples__c6d895d/src/main/kotlin/SimplifySquareRootBigDecimal.kt
import java.math.BigInteger /** * Square root with its coefficient. * * Definitions: a square root is of form 'coefficient * sqrt(radicand)'. * In other words, the coefficient is outside the square root * and the radicand in inside the square root. * * @property coefficient number in front of the radical ('root') sign. * @property radicand number inside the radical ('root') sign. */ data class SquareRootBI(val coefficient: BigInteger, val radicand: BigInteger) /** * Simplifies the square root and makes radicand as small as possible. * * * @param squareRoot the square root to simplify. * @return the simplified square root. */ fun simplifySquareRoot(squareRoot: SquareRootBI): SquareRootBI = if (squareRoot.radicand < BigInteger.ZERO) throw IllegalArgumentException("Radicand cannot be negative") else if (squareRoot.radicand == BigInteger.ZERO) SquareRootBI(BigInteger.ZERO, BigInteger.ZERO) else if (squareRoot.radicand == BigInteger.ONE) SquareRootBI(squareRoot.coefficient, BigInteger.ONE) else { val decreasingSequence = sequence { // We can start at sqrt(radicand) because radicand is // never divisible without remainder by anything greater than i = sqrt(radicand) // This optimization is applied because tests are otherwise very very slow. var bi = squareRoot.radicand.sqrt() while (bi > BigInteger.ONE) { yield(bi) bi = bi.subtract(BigInteger.ONE) } } decreasingSequence .fold(squareRoot) { simplifiedSquareRoot, i -> run { if (simplifiedSquareRoot.radicand.mod(i.pow(2)) == BigInteger.ZERO) { SquareRootBI( simplifiedSquareRoot.coefficient.times(i), simplifiedSquareRoot.radicand.div(i.pow(2)) ) } else { simplifiedSquareRoot } } } }
[ { "class_path": "BjornvdLaan__KotlinTestApproachExamples__c6d895d/SimplifySquareRootBigDecimalKt$simplifySquareRoot$decreasingSequence$1.class", "javap": "Compiled from \"SimplifySquareRootBigDecimal.kt\"\nfinal class SimplifySquareRootBigDecimalKt$simplifySquareRoot$decreasingSequence$1 extends kotlin.coro...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem7.kt
import kotlin.math.floor import kotlin.math.sqrt import kotlin.system.measureNanoTime /** * 10001st prime * * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * * What is the 10001st prime number? * * https://projecteuler.net/problem=7 */ fun main() { println(findPrime1(6)) println(findPrime(6)) val time1 = measureNanoTime { println(findPrime1(10_001)) } val time2 = measureNanoTime { println(findPrime(10_001)) } println(time1) println(time2) } private fun findPrime1(n: Int): Long { var prime = 2L val primes = mutableListOf(prime) while (primes.size != n) { prime++ if (!primes.any { prime % it == 0L }) { primes.add(prime) } } return prime } fun findPrime(n: Int): Long { if (n == 1) return 2 var count = 1 var candidate = 1L do { candidate += 2 if (isPrime(candidate)) count++ } while (count != n) return candidate } fun isPrime(n: Long): Boolean { return when { n < 2 -> false // 1 is not prime n < 4 -> true // 2 and 3 are prime n % 2 == 0L -> false // all primes except 2 are odd n < 9 -> true // we have already excluded 4. 6 and 8 n % 3 == 0L -> false else -> { // All primes greater than 3 can be written in the form 6k+/-1. val r = floor(sqrt(n.toDouble())).toLong() for (f in 5L .. r step 6) { if (n % f == 0L) return false if (n % (f + 2) == 0L) return false } true } } }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem7Kt.class", "javap": "Compiled from \"Problem7.kt\"\npublic final class Problem7Kt {\n public static final void main();\n Code:\n 0: bipush 6\n 2: invokestatic #10 // Method findPrime1:(I)J\n 5: lstore...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem21.kt
import kotlin.math.floor import kotlin.math.sqrt /** * Amicable numbers * * Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). * If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable * numbers. * * For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The * proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. * * Evaluate the sum of all the amicable numbers under 10000. * * https://projecteuler.net/problem=21 */ fun main() { println(220.sumOfProperDivisors()) println(284.sumOfProperDivisors()) println(sumOfAmicables(10_000)) } private fun sumOfAmicables(n: Int): Int { var sum = 0 val amicables = mutableSetOf<Int>() for (a in 2 until n) { if (a in amicables) continue val b = a.sumOfProperDivisors() if (b > a && a == b.sumOfProperDivisors()) { sum += a + b amicables.add(b) } } return sum } fun Int.sumOfProperDivisors(): Int { var sum = 1 var start = 2 var step = 1 var r = floor(sqrt(toDouble())).toInt() if (r * r == this) { sum += r r-- } if (this % 2 != 0) { start = 3 step = 2 } for (i in start..r step step) { if (this % i == 0) { sum += i + (this / i) } } return sum }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem21Kt.class", "javap": "Compiled from \"Problem21.kt\"\npublic final class Problem21Kt {\n public static final void main();\n Code:\n 0: sipush 220\n 3: invokestatic #10 // Method sumOfProperDivisors:(I)I\n ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem10.kt
import kotlin.math.floor import kotlin.math.sqrt import kotlin.system.measureNanoTime /** * Summation of primes * * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. * Find the sum of all the primes below two million. * * https://projecteuler.net/problem=10 */ fun main() { println(sumOfPrimes(10)) println(sumOfPrimesSieve(10)) val time1 = measureNanoTime { println(sumOfPrimes(2_000_000)) } val time2 = measureNanoTime { println(sumOfPrimesSieve(2_000_000)) } println(time1) println(time2) } private fun sumOfPrimes(n: Long): Long { if (n < 2) return 0 return (3..n step 2).asSequence() .filter(::isPrime) .sum() + 2 } private fun sumOfPrimesSieve(n: Long): Long { return primes(n).sumOf(Int::toLong) } // The sieve of Eratosthenes optimized fun primes(n: Long): List<Int> { val sieveBound = ((n - 1) / 2).toInt() val sieve = Array(sieveBound) { true } val crosslimit = (floor(sqrt(n.toDouble())).toInt() - 1) / 2 for (i in 1..crosslimit) { if (!sieve[i-1]) continue for (j in (2 * i * (i + 1)) .. sieveBound step 2 * i + 1) { sieve[j-1] = false } } return listOf(2) + sieve.mapIndexedNotNull { i, isPrime -> if (isPrime) 2 * (i + 1) + 1 else null } }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem10Kt$sumOfPrimes$1.class", "javap": "Compiled from \"Problem10.kt\"\nfinal class Problem10Kt$sumOfPrimes$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.Long, java.lang.Boolean> {\n public s...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem17.kt
import kotlin.math.floor /** * Number letter counts * * If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 * letters used in total. * * If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? * * NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one * hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British * usage. * * https://projecteuler.net/problem=17 */ fun main() { println(numberLetterCount(115)) println(numberLetterCount(342)) println(sumNumberLetterCounts(5)) println(sumNumberLetterCounts(1_000)) } private fun sumNumberLetterCounts(max: Int): Int = (1..max).sumOf(::numberLetterCount) private fun numberLetterCount(number: Int): Int { if (number < 100) return below100(number) var res = 0; val h = floor(number / 100f) % 10 val t = floor(number / 1000f).toInt() val s = number % 100 if (number > 999) { res += below100(t) + "thousand".length } if (h != 0f) { res += proper[h.toInt()] + "hundred".length } if (s != 0) { res += "and".length + below100(s) } return res } // Returns the length of the numbers between 0 and 99 private fun below100(n: Int): Int = if (n < 20) proper[n] else tenth[n / 10 - 2] + proper[n % 10] // proper nouns private val proper = arrayOf( 0, "one".length, "two".length, "three".length, "four".length, "five".length, "six".length, "seven".length, "eight".length, "nine".length, "ten".length, "eleven".length, "twelve".length, "thirteen".length, "fourteen".length, "fifteen".length, "sixteen".length, "seventeen".length, "eighteen".length, "nineteen".length, ) // tenth prefixes private val tenth = arrayOf( "twenty".length, "thirty".length, "forty".length, "fifty".length, "sixty".length, "seventy".length, "eighty".length, "ninety".length, )
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem17Kt.class", "javap": "Compiled from \"Problem17.kt\"\npublic final class Problem17Kt {\n private static final java.lang.Integer[] proper;\n\n private static final java.lang.Integer[] tenth;\n\n public static final void main();\n Code:\n ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem29.kt
import kotlin.math.pow /** * Distinct powers * * Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5: * * 2^2=4, 2^3=8, 2^4=16, 2^5=32 * 3^2=9, 3^3=27, 3^4=81, 3^5=243 * 4^2=16, 4^3=64, 4^4=256, 4^5=1024 * 5^2=25, 5^3=125, 5^4=625, 55^=3125 * If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct * terms: * * 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125 * * How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? * * https://projecteuler.net/problem=29 */ fun main() { println(distinctPowers(limit = 5)) println(distinctPowers(limit = 100)) } private fun distinctPowers(limit: Int): Int = sequence { for (a in 2..limit) { for (b in 2..limit) { yield(a.toDouble().pow(b)) } } }.distinct().count()
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem29Kt.class", "javap": "Compiled from \"Problem29.kt\"\npublic final class Problem29Kt {\n public static final void main();\n Code:\n 0: iconst_5\n 1: invokestatic #10 // Method distinctPowers:(I)I\n 4: istore...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem20.kt
import java.math.BigInteger /** * Factorial digit sum * * n! means n × (n − 1) × ... × 3 × 2 × 1 * * For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, * and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. * * Find the sum of the digits in the number 100! * * https://projecteuler.net/problem=20 */ fun main() { println(factorialDigitSum(10)) println(factorialDigitSum(100)) } private fun factorialDigitSum(n: Int): Int { val result = mutableListOf<Int>().apply { var num = n while (num != 0) { add(num % 10) num /= 10 } } for (factor in (n - 1) downTo 2) { var acc = 0 for ((i, num) in result.withIndex()) { val res = (num * factor) + acc result[i] = res % 10 acc = res / 10 } while (acc != 0) { result.add(acc % 10) acc /= 10 } } return result.sum() }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem20Kt.class", "javap": "Compiled from \"Problem20.kt\"\npublic final class Problem20Kt {\n public static final void main();\n Code:\n 0: bipush 10\n 2: invokestatic #10 // Method factorialDigitSum:(I)I\n ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem30.kt
import kotlin.math.pow /** * Digit fifth powers * * Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: * * 1634 = 1^4 + 6^4 + 3^4 + 4^4 * 8208 = 8^4 + 2^4 + 0^4 + 8^4 * 9474 = 9^4 + 4^4 + 7^4 + 4^4 * * As 1 = 14 is not a sum it is not included. * * The sum of these numbers is 1634 + 8208 + 9474 = 19316. * * Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. * * https://projecteuler.net/problem=30 */ fun main() { println(1634.isDigitPower(4)) println(8208.isDigitPower(4)) println(9474.isDigitPower(4)) println(sumOfDigitPowersOf(4)) println(sumOfDigitPowersOf(5)) } private fun sumOfDigitPowersOf(n: Int): Int { var sum = 0 val limit = 9.0.pow(n).times(n).toInt() for (i in 10..limit) { if (i.isDigitPower(n)) { sum += i } } return sum } private fun Int.isDigitPower(n: Int): Boolean { var sum = 0 var num = this while (num != 0) { val d = num % 10 sum += d.toDouble().pow(n).toInt() num /= 10 } return sum == this }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem30Kt.class", "javap": "Compiled from \"Problem30.kt\"\npublic final class Problem30Kt {\n public static final void main();\n Code:\n 0: sipush 1634\n 3: iconst_4\n 4: invokestatic #10 // Method isDigit...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem14.kt
/** * Longest Collatz sequence * * The following iterative sequence is defined for the set of positive integers: * * n → n/2 (n is even) * n → 3n + 1 (n is odd) * * Using the rule above and starting with 13, we generate the following sequence: * * 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 * It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been * proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. * * Which starting number, under one million, produces the longest chain? * * NOTE: Once the chain starts the terms are allowed to go above one million. * * https://projecteuler.net/problem=14 */ fun main() { println(longestCollatzSequence(1_000_000)) } private fun longestCollatzSequence(max: Int): Int { var longest = 0 var answer = 0 for (n in (max / 2) until max) { val count = collatzSequenceSize(n) if (count > longest) { longest = count answer = n } } max.countLeadingZeroBits() return answer } private val cache = mutableMapOf(1 to 1) private fun collatzSequenceSize(n: Int): Int { val cached = cache[n] if (cached != null) { return cached } val next = if (n % 2 == 0) { collatzSequenceSize(n / 2) + 1 } else { collatzSequenceSize((3 * n + 1) / 2) + 2 } if (cache.size <= 1 shl 30) { cache[n] = next } return next }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem14Kt.class", "javap": "Compiled from \"Problem14.kt\"\npublic final class Problem14Kt {\n private static final java.util.Map<java.lang.Integer, java.lang.Integer> cache;\n\n public static final void main();\n Code:\n 0: ldc #7...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem4.kt
/** * Largest palindrome product * * A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is * 9009 = 91 × 99. * * Find the largest palindrome made from the product of two 3-digit numbers. * * https://projecteuler.net/problem=4 */ fun main() { println(largestPalindrome()) } fun largestPalindrome(): Int { var largestPalindrome = 0 for (a in 999 downTo 100) { var b = 999 while (b >= a) { val p = a * b if (p <= largestPalindrome) { break // since p is always going to be small } if (p.isPalindrome) { largestPalindrome = p } b-- } } return largestPalindrome } val Int.isPalindrome: Boolean get() = this == reverse() fun Int.reverse(): Int { var num = this var reversed = 0 while (num > 0) { reversed = (10 * reversed) + (num % 10) num /= 10 } return reversed }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem4Kt.class", "javap": "Compiled from \"Problem4.kt\"\npublic final class Problem4Kt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method largestPalindrome:()I\n 3: istore_0\n 4: getstat...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem32.kt
@file:Suppress("MagicNumber") /** * Pandigital products * * We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, * the 5-digit number, 15234, is 1 through 5 pandigital. * * The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 * through 9 pandigital. * * Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 * pandigital. * * HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. * * https://projecteuler.net/problem=32 */ fun main() { println(isMultiplicationPandigital(multiplicand = 39, multiplier = 186, product = 7254)) println(checkPandigitalsMultiplications()) } private fun checkPandigitalsMultiplications(): Int = buildSet { for (i in 2 until 100) { for (j in (i + 1) until 2_000) { val p = i * j if (isMultiplicationPandigital(multiplicand = i, multiplier = j, product = p)) { add(p) } } } }.sum() private fun isMultiplicationPandigital(multiplicand: Int, multiplier: Int, product: Int): Boolean { check(multiplicand * multiplier == product) var digitsFlags = 0 val digits = multiplicand.digits() + multiplier.digits() + product.digits() if (digits.size != 9) { return false } digits.forEach { digitsFlags = digitsFlags or (1 shl (it - 1)) } return digitsFlags == 511 } fun Int.digits(): List<Int> = buildList { var num = this@digits while (num != 0) { add(num % 10) num /= 10 } reverse() }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem32Kt.class", "javap": "Compiled from \"Problem32.kt\"\npublic final class Problem32Kt {\n public static final void main();\n Code:\n 0: bipush 39\n 2: sipush 186\n 5: sipush 7254\n 8: invokestatic ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem5.kt
import kotlin.math.floor import kotlin.math.log10 import kotlin.math.pow import kotlin.math.sqrt /** * Smallest multiple * * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? * * https://projecteuler.net/problem=5 */ fun main() { println(smallestNumberDivisibleBy(20)) } // Initial answer /*fun smallestNumberDivisibleBy(k : Int): Long { for (n in (k..Long.MAX_VALUE)) { if ((2..k).all { n % it == 0L }) { return n } } return 0 }*/ private fun smallestNumberDivisibleBy(k: Int): Long { val p = primes(k) val a = Array(p.size) { 0 } val limit = sqrt(k.toDouble()) var n = 1L var check = true for (i in 1 until p.size) { a[i] = 1 if (check) { if (p[i] <= limit) { a[i] = floor(log10(k.toDouble())/ log10(p[i].toDouble())).toInt() } else { check = false } } n *= p[i].toDouble().pow(a[i]).toLong() } return n } // Generating a List of Primes: The Sieve of Eratosthenes fun primes(n: Int): List<Int> { val flags = Array(n) { true } var prime = 2 while (prime <= sqrt(n.toDouble())) { flags.crossOff(prime) prime = flags.indexOfFirst(from = prime + 1) { it } } return flags.mapIndexedNotNull { index, isPrime -> if (isPrime) index else null } } private fun Array<Boolean>.crossOff(prime: Int) { for (i in (prime * prime) until size step prime) { this[i] = false } } inline fun <T> Array<out T>.indexOfFirst(from: Int, predicate: (T) -> Boolean): Int { for (index in from until size) { if (predicate(this[index])) { return index } } return -1 }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem5Kt.class", "javap": "Compiled from \"Problem5.kt\"\npublic final class Problem5Kt {\n public static final void main();\n Code:\n 0: bipush 20\n 2: invokestatic #10 // Method smallestNumberDivisibleBy:(I)J\n...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem23.kt
/** * Non-abundant sums * * A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, * the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. * * A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum * exceeds n. * * As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of * two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be * written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even * though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than * this limit. * * Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. * * https://projecteuler.net/problem=23 */ fun main() { println(nonAbundantSums()) } private fun nonAbundantSums(): Int { val limit = 28123 val totalSum = (1..limit).sum() val abundants = buildList { for (n in 12..limit) { if (n.sumOfProperDivisors() > n) { add(n) } } } val abundantsSums = buildSet { for (i in abundants.indices) { for (j in i..abundants.lastIndex) { val sum = abundants[i] + abundants[j] if (sum <= limit) { add(abundants[i] + abundants[j]) } } } } return totalSum - abundantsSums.sum() }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem23Kt.class", "javap": "Compiled from \"Problem23.kt\"\npublic final class Problem23Kt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method nonAbundantSums:()I\n 3: istore_0\n 4: getsta...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem33.kt
@file:Suppress("MagicNumber") /** * Digit cancelling fractions * * The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may * incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s. * * We shall consider fractions like, 30/50 = 3/5, to be trivial examples. * * There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two * digits in the numerator and denominator. * * If the product of these four fractions is given in its lowest common terms, find the value of the denominator. * * https://projecteuler.net/problem=33 */ fun main() { println(isDigitCancellingFractions(numerator = 49, denominator = 98)) println(findDigitCancellingFractionsProductDenominator()) } private fun findDigitCancellingFractionsProductDenominator(): Int = buildList { // From 10 to 99, since we only support two digits. for (i in 11 until 100) { for (j in 10 until i) { if (isDigitCancellingFractions(numerator = j, denominator = i)) { add(j to i) } } } }.reduce { (n1, d1), (n2, d2) -> (n1 * n2) to (d1 * d2) }.let { (numerator, denominator) -> val denBI = denominator.toBigInteger() val gcd = numerator.toBigInteger().gcd(denominator.toBigInteger()) (denBI / gcd).toInt() } private fun isDigitCancellingFractions(numerator: Int, denominator: Int): Boolean { check(numerator in 10..99) check(denominator in 10..99) check(numerator < denominator) val numDigits = numerator.digits().toSet() val denDigits = denominator.digits().toSet() val repeatedDigits = numDigits intersect denDigits if (numDigits.size == 1 || denDigits.size == 1 || repeatedDigits.size != 1) { return false } val digit = repeatedDigits.first() val newNumerator = numDigits.first { it != digit }.toDouble() val newDenominator = denDigits.first { it != digit }.toDouble() // ignore trivial fractions were common digit is zero return digit != 0 && newDenominator != 0.0 && (numerator.toDouble() / denominator.toDouble()) == (newNumerator / newDenominator) }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem33Kt.class", "javap": "Compiled from \"Problem33.kt\"\npublic final class Problem33Kt {\n public static final void main();\n Code:\n 0: bipush 49\n 2: bipush 98\n 4: invokestatic #10 // Method i...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem26.kt
import java.util.Comparator /** * Reciprocal cycles * * A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to * 10 are given: * * 1/2 = 0.5 * 1/3 = 0.(3) * 1/4 = 0.25 * 1/5 = 0.2 * 1/6 = 0.1(6) * 1/7 = 0.(142857) * 1/8 = 0.125 * 1/9 = 0.(1) * 1/10 = 0.1 * * Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring * cycle. * * Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part. * * https://projecteuler.net/problem=26 */ fun main() { println(2.countRepeatingDecimalsInUnitFraction()) println(3.countRepeatingDecimalsInUnitFraction()) println(4.countRepeatingDecimalsInUnitFraction()) println(5.countRepeatingDecimalsInUnitFraction()) println(6.countRepeatingDecimalsInUnitFraction()) println(7.countRepeatingDecimalsInUnitFraction()) println(8.countRepeatingDecimalsInUnitFraction()) println(9.countRepeatingDecimalsInUnitFraction()) println(10.countRepeatingDecimalsInUnitFraction()) println(findLongestRecurringCycle(1_000)) } private fun findLongestRecurringCycle(limit: Int): Int = (2 until limit) .map { it to it.countRepeatingDecimalsInUnitFraction() } .maxWithOrNull(Comparator.comparingInt(Pair<Int, Int>::second))!! .first private fun Int.countRepeatingDecimalsInUnitFraction(): Int { var acc = 10 var rem: Int val rems = mutableMapOf<Int, Int>() var index = 0 do { rem = acc / this acc -= (this * rem) if (acc in rems) { return rems.size - rems[acc]!! } else { rems[acc] = index index++ } acc *= 10 } while (acc > 0) return 0 }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem26Kt.class", "javap": "Compiled from \"Problem26.kt\"\npublic final class Problem26Kt {\n public static final void main();\n Code:\n 0: iconst_2\n 1: invokestatic #10 // Method countRepeatingDecimalsInUnitFraction:...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem19.kt
/** * You are given the following information, but you may prefer to do some research for yourself. * - 1 Jan 1900 was a Monday. * - Thirty days has September, * April, June and November. * All the rest have thirty-one, * Saving February alone, * Which has twenty-eight, rain or shine. * And on leap years, twenty-nine. * - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. * How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? * * https://projecteuler.net/problem=19 */ fun main() { println( countMondaysFirstOfMonth( MyDate(day = 1, month = 1, year = 1901), MyDate(day = 31, month = 12, year = 2000) ) ) } fun countMondaysFirstOfMonth(from: MyDate, to: MyDate): Int { var date = MyDate(day = 31, month = 12, year = 1899) var count = 0 while (date <= to) { if (date >= from && date.day == 1) { count++ } date = date.nextSunday() } return count } private fun MyDate.nextSunday(): MyDate { var nextDay = day + 7 var nextMonth = month var nextYear = year if (nextDay > daysOfMonth[month]) { nextDay %= daysOfMonth[month] nextMonth++ if (nextMonth > 12) { nextMonth = 1 nextYear++ updateLeapYear(nextYear) } } return MyDate(nextDay, nextMonth, nextYear) } private fun updateLeapYear(year: Int) { val days = when { year % 400 == 0 -> 29 year % 100 == 0 -> 28 year % 4 == 0 -> 29 else -> 28 } daysOfMonth[2] = days } data class MyDate(val day: Int, val month: Int, val year: Int) private operator fun MyDate.compareTo(other: MyDate): Int { val y = year.compareTo(other.year) if (y != 0) { return y } val m = month.compareTo(other.month) if (m != 0) { return m } return day.compareTo(other.day) } private val daysOfMonth = arrayOf( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, )
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem19Kt.class", "javap": "Compiled from \"Problem19.kt\"\npublic final class Problem19Kt {\n private static final java.lang.Integer[] daysOfMonth;\n\n public static final void main();\n Code:\n 0: new #8 // class...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem27.kt
import kotlin.math.pow /** * Quadratic primes * * Euler discovered the remarkable quadratic formula: n^2 + n + 41 * * It turns out that the formula will produce 40 primes for the consecutive integer values 0 <= n <= 39. However, when * is n = 40, 40^2 + 40 +41 = 40(40+1) + 41 divisible by 41, and certainly when n = 41, 41^2 + 41 + 41 is clearly * divisible by 41. * * The incredible formula n^2 - 79n + 1601 was discovered, which produces 80 primes for the consecutive values * 0 <= n <= 79. The product of the coefficients, −79 and 1601, is −126479. * * Considering quadratics of the form: * * n ^2 + an + b, where |a| < 1000 and |b| <= 1000 * where |n| is the modulus/absolute value of n * e.g. |11| = 11 and |-4| = 4 * * Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of * primes for consecutive values of n, starting with n = 0. * * https://projecteuler.net/problem=27 */ fun main() { println(numOfPrimes(a = 1, b = 41)) println(numOfPrimes(a = -79, b = 1601)) println(quadraticPrimes()) } private fun quadraticPrimes(): Int { var numOfPrimes = 0 var abPair = 0 to 0 for (a in -999 until 1_000) { for (b in -1_000..1_000) { val count = numOfPrimes(a, b) if (count > numOfPrimes) { numOfPrimes = count abPair = a to b } } } return abPair.first * abPair.second } private fun numOfPrimes(a: Int, b: Int): Int { var count = -1 var n = -1 do { count++ n++ val res = n.toDouble().pow(2.0) + (a * n) + b } while (isPrime(res.toLong())) return count }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem27Kt.class", "javap": "Compiled from \"Problem27.kt\"\npublic final class Problem27Kt {\n public static final void main();\n Code:\n 0: iconst_1\n 1: bipush 41\n 3: invokestatic #10 // Method numOfPrim...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem1.kt
import kotlin.system.measureNanoTime /** * Multiples of 3 or 5 * * If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these * multiples is 23. * * Find the sum of all the multiples of 3 or 5 below 1000. * * https://projecteuler.net/problem=1 */ fun main() { val max = 999 val solution1Time = measureNanoTime { solution1(max) } val solution2Time = measureNanoTime { solution2(max) } println(solution1Time) println(solution2Time) } private fun solution1(limit: Int) { val res = (1 .. limit).asSequence() .filter { n -> n % 3 == 0 || n % 5 == 0 } .sum() println(res) } private fun solution2(limit: Int) { val res2 = sumDivisibleBy(3, limit) + sumDivisibleBy(5, limit) - sumDivisibleBy(15, limit) println(res2) } fun sumDivisibleBy(n: Int, max: Int): Int { // e.g. 3 + 6 + 9 + 12 + ... + 999 = 3 (1 + 2 + 3 + 4 + ... + 333) // 333 = 999 / 3 => p = max / n val p = max / n // 1 + 2 + 3 + 4 + ... + p = 1/2 * p * (p + 1) return (n * ( 0.5 * p * (p + 1))).toInt() }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem1Kt.class", "javap": "Compiled from \"Problem1.kt\"\npublic final class Problem1Kt {\n public static final void main();\n Code:\n 0: sipush 999\n 3: istore_0\n 4: iconst_0\n 5: istore_3\n 6: invokestatic #...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem18.kt
/** * By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from * top to bottom is 23. * * 3 * 7 4 * 2 4 6 * 8 5 9 3 * * That is, 3 + 7 + 4 + 9 = 23. * * Find the maximum total from top to bottom of the triangle below: * * 75 * 95 64 * 17 47 82 * 18 35 87 10 * 20 04 82 47 65 * 19 01 23 75 03 34 * 88 02 77 73 07 63 67 * 99 65 04 28 06 16 70 92 * 41 41 26 56 83 40 80 70 33 * 41 48 72 33 47 32 37 16 94 29 * 53 71 44 65 25 43 91 52 97 51 14 * 70 11 33 28 77 73 17 78 39 68 17 57 * 91 71 52 38 17 14 91 43 58 50 27 29 48 * 63 66 04 68 89 53 67 30 73 16 69 87 40 31 * 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 * * NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. * However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute * force, and requires a clever method! ;o) * * https://projecteuler.net/problem=18 */ fun main() { println(maxSum(smallTriangle, level = 0, pos = 0)) cache.clear() println(maxSum(triangle, level = 0, pos = 0)) } private val cache = mutableMapOf<Pair<Int, Int>, Long>() fun maxSum(triangle: List<List<Int>>, level: Int, pos: Int): Long { if (level == triangle.size || pos == triangle[level].size) { return 0 } if (cache.containsKey(level to pos)) { return cache[level to pos]!! } val sum = maxOf( maxSum(triangle, level = level + 1, pos), maxSum(triangle, level = level + 1, pos + 1) ) + triangle[level][pos] cache[level to pos] = sum return sum } private val smallTriangle = listOf( listOf(3), listOf(7, 4), listOf(2, 4, 6), listOf(8, 5, 9, 3), ) private val triangle = listOf( listOf(75), listOf(95, 64), listOf(17, 47, 82), listOf(18, 35, 87, 10), listOf(20, 4, 82, 47, 65), listOf(19, 1, 23, 75, 3, 34), listOf(88, 2, 77, 73, 7, 63, 67), listOf(99, 65, 4, 28, 6, 16, 70, 92), listOf(41, 41, 26, 56, 83, 40, 80, 70, 33), listOf(41, 48, 72, 33, 47, 32, 37, 16, 94, 29), listOf(53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14), listOf(70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57), listOf(91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48), listOf(63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31), listOf(4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23), )
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem18Kt.class", "javap": "Compiled from \"Problem18.kt\"\npublic final class Problem18Kt {\n private static final java.util.Map<kotlin.Pair<java.lang.Integer, java.lang.Integer>, java.lang.Long> cache;\n\n private static final java.util.List<java.u...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem11.kt
/** * Largest product in a grid * * In the 20×20 grid below, four numbers along a diagonal line have been marked in red. * * 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 * 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 * 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 * 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 * 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 * 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 * 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 * 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 * 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 * 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 * 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 * 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 * 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 * 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 * 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 * 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 * 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 * 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 * 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 * 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 * * The product of these numbers is 26 × 63 × 78 × 14 = 1788696. * * What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in * the 20×20 grid? */ fun main() { println(largestProduct(grid, 4)) } fun largestProduct(matrix: Array<Array<Int>>, n: Int): Long { var maxP = 0L for (i in matrix.indices) { for (j in matrix[i].indices) { if (matrix[i][j] == 0) continue if (matrix.size - i >= n) { val pv = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j] } if (pv > maxP) { maxP = pv } } if (matrix[i].size - j >= n) { val ph = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i][j + offset] } if (ph > maxP) { maxP = ph } } if (matrix.size - i >= n && matrix[i].size - j >= n) { val pdr = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j + offset] } if (pdr > maxP) { maxP = pdr } } if (matrix.size - i >= n && j >= n - 1) { val pdl = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j - offset] } if (pdl > maxP) { maxP = pdl } } } } return maxP } private val grid = arrayOf( arrayOf(8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8), arrayOf(49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0), arrayOf(81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65), arrayOf(52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91), arrayOf(22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80), arrayOf(24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50), arrayOf(32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70), arrayOf(67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21), arrayOf(24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72), arrayOf(21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95), arrayOf(78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92), arrayOf(16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57), arrayOf(86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58), arrayOf(19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40), arrayOf(4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66), arrayOf(88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69), arrayOf(4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36), arrayOf(20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16), arrayOf(20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54), arrayOf(1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48), )
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem11Kt.class", "javap": "Compiled from \"Problem11.kt\"\npublic final class Problem11Kt {\n private static final java.lang.Integer[][] grid;\n\n public static final void main();\n Code:\n 0: getstatic #10 // Field grid...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem35.kt
/** * Circular primes * * The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves * prime. * * There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. * * How many circular primes are there below one million? * * https://projecteuler.net/problem=35 */ fun main() { println(197.isCircularPrime()) println(countCircularPrimes(limit = 100)) println(countCircularPrimes(limit = 1_000_000)) } private fun countCircularPrimes(limit: Long): Int { return primes(limit).count(Int::isCircularPrime) } private fun Int.isCircularPrime(): Boolean { val digits = digits() for (i in digits.indices) { val nextDigits = digits.subList(fromIndex = i, digits.size) + digits.subList(fromIndex = 0, toIndex = i) if (!isPrime(nextDigits.joinToString(separator = "").toLong())) { return false } } return true }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem35Kt.class", "javap": "Compiled from \"Problem35.kt\"\npublic final class Problem35Kt {\n public static final void main();\n Code:\n 0: sipush 197\n 3: invokestatic #10 // Method isCircularPrime:(I)Z\n ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem25.kt
import kotlin.math.max /** * 1000-digit Fibonacci number * * The Fibonacci sequence is defined by the recurrence relation: * Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. * Hence the first 12 terms will be: * F1 = 1 * F2 = 1 * F3 = 2 * F4 = 3 * F5 = 5 * F6 = 8 * F7 = 13 * F8 = 21 * F9 = 34 * F10 = 55 * F11 = 89 * F12 = 144 * * The 12th term, F12, is the first term to contain three digits. * What is the index of the first term in the Fibonacci sequence to contain 1000 digits? * * https://projecteuler.net/problem=25 */ fun main() { println(fibIndexOfDigitsCount(digitsCount = 3)) println(fibIndexOfDigitsCount(digitsCount = 1_000)) } private fun fibIndexOfDigitsCount(digitsCount: Int): Int { if (digitsCount == 1) return 1 val f1 = mutableListOf(1) val f2 = mutableListOf(1) var index = 2 var turn = true // true for f1, false for f2 while (f1.size != digitsCount && f2.size != digitsCount) { if (turn) { sum(f1, f2) } else { sum(f2, f1) } turn = !turn index++ } return index } private fun sum(list1: MutableList<Int>, list2: MutableList<Int>) { var acc = 0 for (i in 0 until max(list1.size, list2.size)) { val sum = list1.getOrElse(i) { 0 } + list2.getOrElse(i) { 0 } + acc if (i < list1.size) { list1[i] = sum % 10 } else { list1.add(sum % 10) } acc = sum / 10 } while (acc != 0) { list1.add(acc % 10) acc /= 10 } }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem25Kt.class", "javap": "Compiled from \"Problem25.kt\"\npublic final class Problem25Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: invokestatic #10 // Method fibIndexOfDigitsCount:(I)I\n 4:...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem3.kt
import kotlin.math.sqrt /** * Largest prime factor * * The prime factors of 13195 are 5, 7, 13 and 29. * What is the largest prime factor of the number 600851475143 ? * * https://projecteuler.net/problem=3 */ fun main() { println(solution3(600851475143L)) } private fun solution3(n: Long): Long { var num = n var lastFactor = if (n % 2 == 0L) { num /= 2 while (num % 2 == 0L) { num /= 2 } 2L } else { 1L } var factor = 3L var maxFactor = sqrt(num.toDouble()).toLong() while (num > 1 && factor <= maxFactor) { if (num % factor == 0L) { num /= factor lastFactor = factor while (num % factor == 0L) { num /= factor } maxFactor = sqrt(num.toDouble()).toLong() } factor += 2 } return if (num == 1L) lastFactor else num }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem3Kt.class", "javap": "Compiled from \"Problem3.kt\"\npublic final class Problem3Kt {\n public static final void main();\n Code:\n 0: ldc2_w #7 // long 600851475143l\n 3: invokestatic #12 // ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem12.kt
/** * Highly divisible triangular number * * The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be * 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: * * 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... * * Let us list the factors of the first seven triangle numbers: * * 1: 1 * 3: 1,3 * 6: 1,2,3,6 * 10: 1,2,5,10 * 15: 1,3,5,15 * 21: 1,3,7,21 * 28: 1,2,4,7,14,28 * We can see that 28 is the first triangle number to have over five divisors. * * What is the value of the first triangle number to have over five hundred divisors? * * https://projecteuler.net/problem=12 */ fun main() { println(highlyDivisibleTriangularNumber(5)) println(highlyDivisibleTriangularNumber(500)) } private fun highlyDivisibleTriangularNumber(n: Int): Int { var num = 1 while (true) { val triangular = (num * (num + 1)) / 2 val numberOfFactors = primeFactorizationOf(triangular) .map { it.value + 1 } .fold(1L) { acc, i -> acc * i } if (numberOfFactors > n) { return triangular } num++ } } fun primeFactorizationOf(n: Int): Map<Int, Int> = buildMap { var num = n while (num != 1) { primeLoop@ for (i in 1..n) { if (primes[i] == 0) { primes[i] = findPrime(i).toInt() } val prime = primes[i] if (num % prime == 0) { num /= prime set(prime, getOrDefault(prime, 0) + 1) break@primeLoop } } } } private val primes = IntArray(65500) { 0 }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem12Kt.class", "javap": "Compiled from \"Problem12.kt\"\npublic final class Problem12Kt {\n private static final int[] primes;\n\n public static final void main();\n Code:\n 0: iconst_5\n 1: invokestatic #10 // Meth...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem24.kt
/** * Lexicographic permutations * * A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, * 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The * lexicographic permutations of 0, 1 and 2 are: * * 012 021 102 120 201 210 * * What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? * * https://projecteuler.net/problem=24 */ fun main() { println(lexicographicPermutations(listOf('0', '1', '2'))) println(lexicographicPermutationsAt(listOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), 1_000_000)) } private fun lexicographicPermutations(digits: List<Char>): List<String> = buildList { val arr = digits.toCharArray() while (true) { add(String(arr)) if (!arr.nextPermutation()) break } } private fun lexicographicPermutationsAt(digits: List<Char>, n: Int): String { val arr = digits.toCharArray() var count = 0 while (true) { count++ if (count == n) { return String(arr) } if (!arr.nextPermutation()) break } return "" } private fun CharArray.nextPermutation(): Boolean { // Find the rightmost character which is smaller than its next character. val i = ((lastIndex - 1) downTo 0).firstOrNull { this[it] < this[it + 1] } ?: return false // Find the ceil of 'first char' in right of first character. Ceil of a character is the smallest character // greater than it. val ceilIndex = findCeil(this[i], i + 1, lastIndex) // Swap first and second characters swap(i, ceilIndex) // reverse the string on right of 'first char' reverse(i + 1, lastIndex) return true } // This function finds the index of the smallest // character which is greater than 'first' and is // present in str[l..h] private fun CharArray.findCeil(first: Char, l: Int, h: Int): Int { // initialize index of ceiling element var ceilIndex = l // Now iterate through rest of the elements and find // the smallest character greater than 'first' for (i in l + 1..h) { if (this[i] > first && this[i] < this[ceilIndex]) { ceilIndex = i } } return ceilIndex } // A utility function two swap two characters a and b private fun CharArray.swap(i: Int, j: Int) { val t = this[i] this[i] = this[j] this[j] = t } // A utility function to reverse a string str[l..h] private fun CharArray.reverse(l: Int, h: Int) { var low = l var high = h while (low < high) { swap(low, high) low++ high-- } }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem24Kt.class", "javap": "Compiled from \"Problem24.kt\"\npublic final class Problem24Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class java/lang/Character\n 4: astore_...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem34.kt
/** * Digit factorials * * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. * * Find the sum of all numbers which are equal to the sum of the factorial of their digits. * * Note: As 1! = 1 and 2! = 2 are not sums they are not included. * * https://projecteuler.net/problem=34 */ fun main() { check(145.isDigitFactorial()) println(sumOfDigitFactorials()) } private fun sumOfDigitFactorials(from: Int = 10, to: Int = 99999): Int = (from..to).filter(Int::isDigitFactorial).sum() private fun Int.isDigitFactorial(): Boolean = digits().sumOf(Int::factorial) == this private fun Int.factorial(): Int = (1..this).fold(1) { x, y -> x * y }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem34Kt.class", "javap": "Compiled from \"Problem34.kt\"\npublic final class Problem34Kt {\n public static final void main();\n Code:\n 0: sipush 145\n 3: invokestatic #10 // Method isDigitFactorial:(I)Z\n ...
jimmymorales__project-euler__e881cad/src/main/kotlin/Problem2.kt
import kotlin.system.measureNanoTime /** * Even Fibonacci numbers * * Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the * first 10 terms will be: * * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... * * By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the * even-valued terms. * * https://projecteuler.net/problem=2 */ fun main() { val limit = 4_000_000 val solution1Time = measureNanoTime { solution1(limit) } val solution2Time = measureNanoTime { solution2(limit) } println(solution1Time) println(solution2Time) } private fun solution1(limit: Int) { var n1 = 1 var n2 = 1 var sum = 0 while (n2 < limit) { if (n2 % 2 == 0) { sum += n2 } val fib = n1 + n2 n1 = n2 n2 = fib } println(sum) } private fun solution2(limit: Int) { // 1 1 2 3 5 8 13 21 34 55 89 144 // a b c a b c a b c a b c var a = 1 var b = 1 var c = a + b var sum = 0 while (c < limit) { sum += c a = b + c b = c + a c = a + b } println(sum) }
[ { "class_path": "jimmymorales__project-euler__e881cad/Problem2Kt.class", "javap": "Compiled from \"Problem2.kt\"\npublic final class Problem2Kt {\n public static final void main();\n Code:\n 0: ldc #7 // int 4000000\n 2: istore_0\n 3: iconst_0\n 4: isto...
margalis__Kotlin_Koans_mg__faf2034/Generics/Generic functions/src/Task.kt
import java.util.* public fun <T, C : MutableCollection<in T>> Collection<T>.partitionTo(col1: C, col2: C, predicate: (T)-> Boolean): Pair<C,C> { //T-n itemi tesak, C-n` Collectioni mejini //greladzevy` toCollectioni pes for( item in this){ if(predicate(item)){ col1.add(item) } else{ col2.add(item) } } return Pair(col1,col2) // qanzi partition()-y sl-um pair er veradardznum } fun partitionWordsAndLines() { val (words, lines) = listOf("a", "a b", "c", "d e") .partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } check(words == listOf("a", "c")) check(lines == listOf("a b", "d e")) } fun partitionLettersAndOtherSymbols() { val (letters, other) = setOf('a', '%', 'r', '}') .partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } check(letters == setOf('a', 'r')) check(other == setOf('%', '}')) }
[ { "class_path": "margalis__Kotlin_Koans_mg__faf2034/TaskKt.class", "javap": "Compiled from \"Task.kt\"\npublic final class TaskKt {\n public static final <T, C extends java.util.Collection<? super T>> kotlin.Pair<C, C> partitionTo(java.util.Collection<? extends T>, C, C, kotlin.jvm.functions.Function1<? su...
aragos__aoc2023__7bca0a8/aoc/src/Calibration.kt
import java.io.File fun main() { println(Calibration.readCalibrationDigitsAndWords("aoc/inputs/calibration.txt").sum()) } object Calibration { fun readCalibrationDigits(): List<Int> = buildList { File("aoc/inputs/calibration.txt").forEachLine { line -> val allDigits = Regex("[1-9]").findAll(line).map { it.value } val twoDigits = (allDigits.first() + allDigits.last()).toInt() add(twoDigits) } } fun readCalibrationDigitsAndWords(fileLocation: String): List<Int> = buildList { File(fileLocation).forEachLine { line -> add(digitAndWordLineToNumber(line)) } } fun digitAndWordLineToNumber(line: String): Int { val allDigits = Regex("(?=([1-9]|one|two|three|four|five|six|seven|eight|nine)).") .findAll(line) .mapNotNull { it.groups[1]?.value } .map(::numberToDigit) .toList() return (allDigits.first() + allDigits.last()).toInt() } private fun numberToDigit(number: String) = when (number) { // No zeros here! "one" -> "1" "two" -> "2" "three" -> "3" "four" -> "4" "five" -> "5" "six" -> "6" "seven" -> "7" "eight" -> "8" "nine" -> "9" else -> number } }
[ { "class_path": "aragos__aoc2023__7bca0a8/CalibrationKt.class", "javap": "Compiled from \"Calibration.kt\"\npublic final class CalibrationKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field Calibration.INSTANCE:LCalibration;\n 3: ldc #14 ...
aragos__aoc2023__7bca0a8/aoc/src/Soil.kt
import java.io.File import java.lang.IllegalArgumentException data class Range(val sourceStart: Long, val destinationStart: Long, val rangeLength: Long) { val sources = LongRange(sourceStart, sourceStart + rangeLength - 1) override fun toString(): String { return "$sources -> ${LongRange(destinationStart, destinationStart + rangeLength - 1)}" } fun mapId(id: Long) = destinationStart + id - sourceStart fun invert() = Range(destinationStart, sourceStart, rangeLength) } class Mapping(val name: String, ranges: Set<Range>) { val sortedRanges = ranges.sortedBy { it.sources.start } fun map(sourceId: Long): Long { for (range in sortedRanges) { if (sourceId < range.sources.start) { return sourceId } else if (sourceId in range.sources) { return range.mapId(sourceId) } } return sourceId } override fun toString(): String { return "Mapping:\n" + sortedRanges.joinToString(separator = "\n") { " $it" } } } fun main() { val lines = File("inputs/soil.txt").readLines() val rawSeeds = Regex("\\d+").findAll(lines[0].split(":")[1]).map { it.value.toLong() } val mappings = lines.parseMappings() // println(calculateMinLocationSimpleSeeds(rawSeeds, mappings)) println(calculateMinLocationSeedRanges(rawSeeds, mappings)) } fun calculateMinLocationSeedRanges(rawSeeds: Sequence<Long>, forwardMappings: List<Mapping>): Long { val seedRanges = rawSeeds .chunked(2) .map { pair -> LongRange(start = pair[0], endInclusive = pair[0] + pair[1] - 1) } .sortedBy { range -> range.start } .toList() val reverseMappings = forwardMappings.map { mapping -> Mapping("~${mapping.name}", mapping.sortedRanges.map { it.invert() }.toSet()) }.reversed() val locations2Humidity = reverseMappings.first() locations2Humidity.sortedRanges.forEach { range -> range.sources.forEach { location -> val seed = reverseMappings.fold(location) seedRanges.forEach { seedRange -> if (seed in seedRange) { return location } } } } throw IllegalArgumentException() } private fun calculateMinLocationSimpleSeeds( rawSeeds: Sequence<Long>, mappings: List<Mapping>, ): Long = rawSeeds.map { value -> mappings.fold(value) }.min() private fun List<Mapping>.fold(value: Long) = this.fold(value) { acc, mapping -> mapping.map(acc) } private fun List<String>.parseMappings(): List<Mapping> { val seed2Soil = parseMapping("seed2Soil", startInclusive = 3, endExclusive = 32) val soil2Fertilizer = parseMapping("soil2Fertilizer", startInclusive = 34, endExclusive = 53) val fertilizer2Water = parseMapping("fertilizer2Water", startInclusive = 55, endExclusive = 97) val water2Light = parseMapping("water2Light", startInclusive = 99, endExclusive = 117) val light2Temperature = parseMapping("light2Temperature", startInclusive = 119, endExclusive = 132) val temperature2Humidity = parseMapping("temperature2Humidity", startInclusive = 135, endExclusive = 144) val humidity2Location = parseMapping("humidity2Location", startInclusive = 146, endExclusive = 190) return listOf( seed2Soil, soil2Fertilizer, fertilizer2Water, water2Light, light2Temperature, temperature2Humidity, humidity2Location ) } private fun List<String>.parseMapping( name: String, startInclusive: Int, endExclusive: Int, ): Mapping = Mapping(name, subList(startInclusive, endExclusive).map { line -> val numbers = Regex("\\d+").findAll(line).map { it.value.toLong() }.toList() Range(sourceStart = numbers[1], destinationStart = numbers[0], rangeLength = numbers[2]) }.toSet())
[ { "class_path": "aragos__aoc2023__7bca0a8/SoilKt.class", "javap": "Compiled from \"Soil.kt\"\npublic final class SoilKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // String in...
aragos__aoc2023__7bca0a8/aoc/src/Parts.kt
import java.io.File fun main() { // countPartNumbers() countGearRatios() } private data class PartNumber(val value: Int, val location: IntRange) { fun isAdjacentTo(i: Int) = i in (location.first-1)..(location.last+1) } private fun countGearRatios() { var line1: Set<PartNumber> var line2 = setOf<PartNumber>() var line3 = setOf<PartNumber>() var previousLine = "" val allRatios = File("inputs/parts.txt").readLines().map { line -> line1 = line2 line2 = line3 line3 = Regex("\\d+").findAll(line).map { PartNumber(it.value.toInt(), it.range) }.toSet() val ratioSum = scanRatios(previousLine, line1 + line2 + line3) previousLine = line ratioSum }.sum() println(allRatios + scanRatios(previousLine, line2 + line3)) } private fun scanRatios( previousLine: String, partNumbers1: Set<PartNumber>, ): Int { val ratioSum = previousLine.mapIndexedNotNull { ix, char -> if (char != '*') { null } else { val partNumbers = partNumbers1.filter { it.isAdjacentTo(ix) } if (partNumbers.size == 2) { partNumbers[0].value * partNumbers[1].value } else { null } } }.sum() return ratioSum } private fun countPartNumbers() { var line1: Set<Int> var line2 = setOf<Int>() var line3 = setOf<Int>() var previousLine = "" val allNumbers = File("inputs/parts.txt").readLines().map { line -> line1 = line2 line2 = line3 line3 = line.mapIndexedNotNull { ix, char -> if (char != '.' && char.isNotANumber()) ix else null } .toSet() val line2PartNumberSum = scanPartNumbers(previousLine, line1 + line2 + line3) previousLine = line line2PartNumberSum }.sum() println(allNumbers + scanPartNumbers(previousLine, line2 + line3)) } private fun scanPartNumbers( partNumberLine: String, partLocations: Set<Int>, ): Int { return Regex("\\d+").findAll(partNumberLine).mapNotNull { val number = it.value.toInt() for (i in (it.range.first - 1)..(it.range.last + 1)) { if (i in partLocations) { return@mapNotNull number } } null }.sum() } private fun Char.isNotANumber() = digitToIntOrNull() == null
[ { "class_path": "aragos__aoc2023__7bca0a8/PartsKt.class", "javap": "Compiled from \"Parts.kt\"\npublic final class PartsKt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method countGearRatios:()V\n 3: return\n\n private static final void countGearRat...
aragos__aoc2023__7bca0a8/aoc/src/Hands.kt
import Card.Companion.toCard import java.io.File fun main() { val lines = File("aoc/inputs/hands.txt").readLines() println(linesToWinnings(lines)) } internal fun linesToWinnings(lines: List<String>): Int { return lines .map { line -> HandWinnings( Hand(line.substring(0, 5).map { it.toCard() }), line.substring(6).toInt() ) } .sortedByDescending(HandWinnings::hand) .mapIndexed { ix, handWinnings -> (ix + 1) * handWinnings.winnings } .sum() } data class HandWinnings(val hand: Hand, val winnings: Int) enum class Card(val representation: Char) { Ace('A'), King('K'), Queen('Q'), // Jack('J'), Ten('T'), Nine('9'), Eight('8'), Seven('7'), Six('6'), Five('5'), Four('4'), Three('3'), Two('2'), Joker('J'); companion object { fun Char.toCard(): Card { for (card in entries) { if (this == card.representation) { return card } } throw IllegalArgumentException("Non-card character '$this'") } } } enum class Type { Five, Four, FullHouse, Three, TwoPair, OnePair, High } class Hand(private val cards: List<Card>) : Comparable<Hand> { private val distribution: Map<Card, Int> = cards.fold(mutableMapOf()) { dist, card -> dist[card] = dist.getOrDefault(card, 0) + 1 dist } private val type: Type get() { return when (distribution.size) { 1 -> Type.Five 2 -> if (distribution.values.any { it == 4 }) Type.Four else Type.FullHouse 3 -> if (distribution.values.any { it == 3 }) Type.Three else Type.TwoPair 4 -> Type.OnePair 5 -> Type.High else -> throw IllegalStateException("Wrong number of cards") } } private val complexType: Type get() { var nonJokers = 0 val distribution = cards.fold(mutableMapOf<Card, Int>()) { dist, card -> if (card != Card.Joker) { dist[card] = dist.getOrDefault(card, 0) + 1 nonJokers++ } dist } val jokers = 5 - nonJokers return when (distribution.size) { 0 -> Type.Five // All jokers 1 -> Type.Five // Jokers become the one other card type 2 -> if (distribution.values.any { it == nonJokers - 1 }) Type.Four else Type.FullHouse 3 -> if (distribution.values.any { it == 3-jokers }) Type.Three else Type.TwoPair 4 -> Type.OnePair 5 -> Type.High else -> throw IllegalStateException("Wrong number of cards") } } override operator fun compareTo(other: Hand): Int { if (this.complexType != other.complexType) { return this.complexType.compareTo(other.complexType) } for (i in 0..4) { if (this.cards[i] != other.cards[i]) { return this.cards[i].compareTo(other.cards[i]) } } return 0 } }
[ { "class_path": "aragos__aoc2023__7bca0a8/HandsKt$linesToWinnings$$inlined$sortedByDescending$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class HandsKt$linesToWinnings$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public HandsKt$linesToWinnings$$inlined$sortedB...
aragos__aoc2023__7bca0a8/aoc/src/ColorGame.kt
import java.io.File fun main() { // problem1() problem2() } private fun problem2() { var powerSum = 0 val colors = listOf("red", "green", "blue") File("inputs/colorGame.txt").forEachLine { line -> val split = line.split(":") val maxes = colors.associateWith { 0 }.toMutableMap() split[1].split(";").forEach { it.split(",").forEach { color -> for ((name, max) in maxes) { if (color.contains(name)) { val count = Regex("\\d+").find(color)?.value?.toInt() ?: 0 if (count > max) { maxes[name] = count } } } } } powerSum += maxes.values.reduce { acc, value -> acc * value } } println(powerSum) } private fun problem1() { val colors = mapOf("red" to 12, "green" to 13, "blue" to 14) var validGamesSum = 0 File("inputs/colorGame.txt").forEachLine { line -> val split = line.split(":") val gameId = split[0].substring(5).toInt() split[1].split(";").forEach { it.split(",").forEach { color -> for ((name, max) in colors) { if (color.contains(name)) { if ((Regex("\\d+").find(color)?.value?.toInt() ?: 0) > max) { return@forEachLine } } } } } validGamesSum += gameId } println(validGamesSum) }
[ { "class_path": "aragos__aoc2023__7bca0a8/ColorGameKt.class", "javap": "Compiled from \"ColorGame.kt\"\npublic final class ColorGameKt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method problem2:()V\n 3: return\n\n private static final void problem...
aragos__aoc2023__7bca0a8/aoc/src/Scratch.kt
import java.io.File import kotlin.math.pow fun main() { println(countPoints()) println(countCards()) } private fun countCards(): Int { val cardCount = (0..211).associateWith { 1 }.toMutableMap() File("inputs/scratch.txt").readLines().mapIndexed() { ix, line -> if (line.isBlank()) return@mapIndexed val winningCount = countWinningNumbers(line) val times = cardCount[ix]!! for (j in (ix + 1)..ix + winningCount) { cardCount[j] = cardCount[j]!! + times } } return cardCount.values.sum() } private fun countPoints(): Int = File("inputs/scratch.txt").readLines().map { line -> val winningCount = countWinningNumbers(line) if (winningCount == 0) 0 else 2.0.pow(winningCount - 1).toInt() }.sum() private fun countWinningNumbers(line: String): Int { val (winning, actual) = line.split(":")[1].split("|") val winningNumbers = winning.toNumbers().toSet() return actual.toNumbers().count { winningNumbers.contains(it) } } private fun String.toNumbers() = Regex("\\d+").findAll(this).map { it.value.toInt() }.toList()
[ { "class_path": "aragos__aoc2023__7bca0a8/ScratchKt.class", "javap": "Compiled from \"Scratch.kt\"\npublic final class ScratchKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method countPoints:()I\n 3: istore_0\n 4: getstatic #16 ...
shyoutarou__desafios-DIO__b312f8f/Desafios/Kotlin/Primeiros passos em Kotlin/Carrefour Android Developer/Figurinhas/figurinhas.kt
/* Ricardo e Vicente são aficionados por figurinhas. Nas horas vagas, eles arrumam um jeito de jogar um “bafo” ou algum outro jogo que envolva tais figurinhas. Ambos também têm o hábito de trocarem as figuras repetidas com seus amigos e certo dia pensaram em uma brincadeira diferente. Chamaram todos os amigos e propuseram o seguinte: com as figurinhas em mãos, cada um tentava fazer uma troca com o amigo que estava mais perto seguindo a seguinte regra: cada um contava quantas figurinhas tinha. Em seguida, eles tinham que dividir as figurinhas de cada um em pilhas do mesmo tamanho, no maior tamanho que fosse possível para ambos. Então, cada um escolhia uma das pilhas de figurinhas do amigo para receber. Por exemplo, se Ricardo e Vicente fossem trocar as figurinhas e tivessem respectivamente 8 e 12 figuras, ambos dividiam todas as suas figuras em pilhas de 4 figuras (Ricardo teria 2 pilhas e Vicente teria 3 pilhas) e ambos escolhiam uma pilha do amigo para receber. Entrada A primeira linha da entrada contém um único inteiro N (1 ≤ N ≤ 3000), indicando o número de casos de teste. Cada caso de teste contém 2 inteiros F1 (1 ≤ F1 ≤ 1000) e F2 (1 ≤ F2 ≤ 1000) indicando, respectivamente, a quantidade de figurinhas que Ricardo e Vicente têm para trocar. Saída Para cada caso de teste de entrada haverá um valor na saída, representando o tamanho máximo da pilha de figurinhas que poderia ser trocada entre dois jogadores. */ fun main(args: Array<String>) { val lista = mutableListOf<Int>() for (i in 1..readLine()!!.toInt()) { val input = readLine()!!.split(" ").map { it.toInt() } input.forEach { number -> lista.add(number) } println(mdc(lista[0], lista[1])) lista.clear() } } fun mdc(n1: Int, n2: Int): Int { return if (n2 == 0) { n1 } else { mdc(n2, (n1 % n2)) } }
[ { "class_path": "shyoutarou__desafios-DIO__b312f8f/FigurinhasKt.class", "javap": "Compiled from \"figurinhas.kt\"\npublic final class FigurinhasKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invo...
LaraEstudillo__coins_challenge_1__b710f68/coins.kt
import kotlin.collections.listOf var amount = 11 var result: ArrayList<CoinsAndQuantity> = ArrayList() fun main() { println(minCoins()) } fun minCoins() { val coins = listOf(1,2,5).sorted() val suma = coins.sum(); if(suma == amount) { println(suma); return; } calculation(coins.size, coins) println(result) println(sumItems()) if(sumItems() != amount) println(-1) else println(result) } private fun sumItems(): Int { var data = 0 result.forEach { item -> data += item.coin * item.quantity } return data } private fun calculation(index: Int, coins: List<Int>) { if(index > 0) { val divisor = (amount / coins[index-1]).toInt() val restante = (amount % coins[index-1]).toInt() amount = restante divisor.takeIf { it > 0 }?.also { result.add(CoinsAndQuantity(coins[index-1], divisor)) } calculation(index - 1, coins) } } data class CoinsAndQuantity ( var coin: Int = 0, var quantity: Int = 0 )
[ { "class_path": "LaraEstudillo__coins_challenge_1__b710f68/CoinsKt.class", "javap": "Compiled from \"coins.kt\"\npublic final class CoinsKt {\n private static int amount;\n\n private static java.util.ArrayList<CoinsAndQuantity> result;\n\n public static final int getAmount();\n Code:\n 0: getsta...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day04.kt
fun main() { fun part1(input: List<String>): Int = input .contains(::fullyContains) fun part2(input: List<String>): Int = input .contains(::partiallyContains) // test if implementation meets criteria from the description, like: // val testInput = readInput("Day04_test") // check(part1(testInput) == 2) // // check(part2(testInput) == 4) // // val input = readInput("Day04") // println(part1(input)) // println(part2(input)) } fun List<String>.contains(fullyOrPartialContains: (List<Int>, List<Int>) -> Boolean) = map { it .split(",") } .foldRight(0) { cleaningAreas, containedAreas -> val (cleaningAreaOne, cleaningAreaTwo) = cleaningAreas .map { cleaningArea -> cleaningArea .split("-") .map { it.toInt() } } containedAreas + if (fullyOrPartialContains(cleaningAreaOne, cleaningAreaTwo)) 1 else 0 } fun fullyContains(areaOne: List<Int>, areaTwo: List<Int>): Boolean = when { areaOne.first() >= areaTwo.first() && areaOne.last() <= areaTwo.last() || areaTwo.first() >= areaOne.first() && areaTwo.last() <= areaOne.last() -> true else -> false } fun partiallyContains(areaOne: List<Int>, areaTwo: List<Int>): Boolean = (areaOne.first() .. areaOne.last()).toSet().intersect((areaTwo.first() .. areaTwo.last()).toSet()).size >= 1
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: return\n\n public static final int contains(java.util.List<java.lang.String>, kotlin.jvm.functions.Function...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day05.kt
import java.io.File import java.util.Stack typealias Stacks<E> = List<Stack<E>> typealias StacksOfChar = Stacks<Char> fun main() { fun part1(input: String) = findCratesOnTopOfAllStacks( input, StacksOfChar::moveOneStackAtTime ) fun part2(input: String) = findCratesOnTopOfAllStacks( input, StacksOfChar::moveAllStacksOnce ) // test if implementation meets criteria from the description, like: // val testInput = readInputAsString("Day05_test") // check(part1(testInput) == "CMZ") // check(part2(testInput) == "MCD") // // val input = readInputAsString("Day05") // println(part1(input)) // println(part2(input)) } fun findCratesOnTopOfAllStacks( input: String, moveOneOrAllAtATime: StacksOfChar.(Int, Int, Int) -> StacksOfChar ): String { val (stackData, proceduresData) = input .split("\n\r\n") // separate the information of stacks from that of procedures val stackSize = stackData .toIntStackSize() // get the last number of the stacks which is in turn the size of stacks val listOfStacks = buildList { repeat(stackSize) { add(Stack<Char>()) } } stackData .lines() // get the cranes at each level of the stacks from the top .dropLast(2) // the line with the numbering of the stacks .map { it .chunked(4) .map { it[1] } } // remove the clutter such as the space and the brackets, take only the character content of the cranes .foldRight(listOfStacks) { cranes, stacks -> cranes.forEachIndexed { craneStackNum, crane -> if (crane.toString().isNotBlank()) { stacks[craneStackNum].push(crane) // push the crates into the list of stacks } } // build the initial state of the states stacks } proceduresData .lines() // get the lines of the procedures .map { it.split(" ") } .fold(listOfStacks) { stacks, procedure -> stacks .moveOneOrAllAtATime( procedure[1].toInt(), // the number of cranes to move procedure[3].toInt() - 1, // the stack to move the cranes from procedure[5].toInt() - 1 // the stack to move the cranes to ) } return buildString { listOfStacks.forEach { if (it.isEmpty()) append(" ") else append(it.pop()) } } } private fun <E> Stacks<E>.moveOneStackAtTime(crates: Int, fromStack: Int, toStack: Int): Stacks<E> = apply { repeat(crates) { if (this[fromStack].isNotEmpty()) { this[toStack].push(this[fromStack].pop()) } else this.map { println(it) } } } private fun <E> Stacks<E>.moveAllStacksOnce(crates: Int, fromStack: Int, toStack: Int): Stacks<E> = apply { val tempStack = Stack<E>() repeat(crates) { if (this[fromStack].isNotEmpty()) { tempStack.push(this[fromStack].pop()) } else this.map { println(it) } } repeat(crates) { if (tempStack.isNotEmpty()) { this[toStack].push(tempStack.pop()) } } } private fun String.toIntStackSize() = split("\n") .last()// get the labels of all the stack .split(" ")// get the list of each stack's label .last() // get the last stack's label .trim() // remove any characters around the label .toInt() // return the label as an Int
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: return\n\n public static final java.lang.String findCratesOnTopOfAllStacks(java.lang.String, kotlin.jvm.fun...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day07.kt
const val TOTALDISKSPACE = 70000000 const val NEEDEDUNUSEDSPACE = 30000000 fun main() { fun part1(input: String): Int = FileSystem().run { parseInstructions(input) getListOfDirNSizes() .map { it.second } .filter { it < 100000 } .sum() } fun part2(input: String): Pair<String, Int> = FileSystem().run { parseInstructions(input) val listOfDirNSizes = getListOfDirNSizes() val totalUsedSize = getListOfDirNSizes().maxOf { it.second } val totalUnUsedSpace = TOTALDISKSPACE - totalUsedSize listOfDirNSizes .filter { dirNSize -> val (_, size) = dirNSize size >= NEEDEDUNUSEDSPACE - totalUnUsedSpace } .minBy { it.second } } // test if implementation meets criteria from the description, like: // table test of part1 // val testInput = readInputAsString("Day07_test") // check(part1(testInput) == 95437) // check(part2(testInput) == Pair("d", 24933642)) // // val input = readInputAsString("Day07") // println(part1(input)) // println(part2(input)) } sealed class FileType (val name: String, val parent: FileType.Dir?) { class Dir(name: String, parent: FileType.Dir?, val children: HashMap<String, FileType> = hashMapOf()) : FileType(name, parent) { override fun getTheSize(): Int = children .map { it.value } .fold(0) { sizes, children -> sizes + children.getTheSize() } } class MyFile(name: String, parent: FileType.Dir, val size: Int) : FileType(name, parent) { override fun getTheSize(): Int = size } abstract fun getTheSize(): Int } fun FileType.Dir.getDirNSize(list: MutableList<Pair<String, Int>>) { children.map { it.value } .forEach { if (it is FileType.Dir) it.getDirNSize(list) } val size = getTheSize() list.add( Pair(name, size) ) } class FileSystem { private val rootDir = FileType.Dir("/", null) private var current = rootDir fun changeDirectory(param: String) { current = when(param) { ".." -> current.parent ?: rootDir "/" -> rootDir else -> current .children .getOrElse(param){ val newChild = FileType.Dir(param, current) current.children.put(param, newChild) newChild } as FileType.Dir } } fun listing(files: List<String>) { files .map { it.split(" ") } .fold(current) { cur, file -> when { file.first() == "dir" -> cur.children.put(file.last(), FileType.Dir(file.last(), cur)) else -> cur.children.put(file.last(), FileType.MyFile(file.last(), cur, file.first().toInt())) } cur } } fun parseInstructions(instructions: String) { instructions .split("$") .map { it.trim() } .forEach { val commandNParamsData = it .lines() val command = commandNParamsData .first() .split(" ") when (command.first()) { "cd" -> changeDirectory(command.last()) "ls" -> listing(commandNParamsData .drop(1) // remove any string that follows the command ls, which is blank in this case ) else -> {} } } } fun getListOfDirNSizes(): MutableList<Pair<String, Int>> = mutableListOf<Pair<String, Int>>().apply { rootDir.getDirNSize(this) } }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final int TOTALDISKSPACE;\n\n public static final int NEEDEDUNUSEDSPACE;\n\n public static final void main();\n Code:\n 0: return\n\n pub...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day06.kt
fun main() { fun part1(signal: String, n: Int = 4): Int = firstNUniqueCharacters(signal = signal, n = n) fun part2(signal: String, n: Int = 14): Int = firstNUniqueCharacters(signal = signal, n = n) // test if implementation meets criteria from the description, like: // table test of part1 // val testInput01 = readInput("Day06_test_part01") // val testInput01Solutions = listOf<Int>(7, 5, 6, 10, 11) // testInput01 // .zip(testInput01Solutions) // .map { // check(part1(it.first) == it.second) // } // // // table test of part2 // val testInput02 = readInput("Day06_test_part02") // val testInput02Solutions = listOf<Int>(19, 23, 23, 29, 26) // testInput02 // .zip(testInput02Solutions) // .map { // check(part2(it.first) == it.second) // } // // val input = readInputAsString("Day06") // println(part1(input)) // println(part2(input)) } fun firstNUniqueCharacters(signal: String, n: Int): Int { val possiblePacketMarkers = signal.windowed(n) .map { it.toSet() } var lastPositionOfMarker = n for (possiblePacketMarker in possiblePacketMarkers) { if (possiblePacketMarker.size == n) { break } lastPositionOfMarker++ } return lastPositionOfMarker }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day06Kt.class", "javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: return\n\n public static final int firstNUniqueCharacters(java.lang.String, int);\n Code:\n 0: alo...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day03.kt
fun main() { fun itemPriority(c: Char): Int = when { c.isLowerCase() -> c.code - 96 c.isUpperCase() -> c.code - 64 + 26 else -> 0 } fun part1(input: List<String>): Int = input.foldRight(0) { rucksack, prioritySum -> rucksack .chunked(rucksack.length / 2) .map { it.toSet() } .intersection() .map(::itemPriority) .sum() + prioritySum } fun part2(input: List<String>): Int = input .windowed(3, 3) .foldRight(0) { threeRucksacks, prioritySum -> threeRucksacks .map { it.toSet() } .intersection() .map(::itemPriority) .sum() + prioritySum } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day03_test") // check(part1(testInput) == 157) // check(part2(testInput) == 70) // // val input = readInput("Day03") // println(part1(input)) // println(part2(input)) } // //fun List<Set<Char>>.intersection() = reduce { element, acc -> // element.intersect(acc) //} private fun <A> List<Set<A>>.intersection(): Set<A> = reduce { element, acc -> element.intersect(acc) }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: return\n\n private static final <A> java.util.Set<A> intersection(java.util.List<? extends java.util.Set<? ...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day02.kt
/*enum class RockPaperScissorsPermutation(val result: Int) { `A X`(3 + 1), `A Y`(6 + 2), `A Z`(0 + 3), `B X`(0 + 1), `B Y`(3 + 2), `B Z`(6 + 3), `C X`(6 + 1), `C Y`(0 + 2), `C Z`(3 + 3) }*/ val RoPaScPermutations = mapOf<String, Int>( "A X" to 3 + 1, "A Y" to 6 + 2, "A Z" to 0 + 3, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 6 + 1, "C Y" to 0 + 2, "C Z" to 3 + 3 ) val RoPaScPermElfStrategy = mapOf<String, Int>( "A X" to 0 + 3, "A Y" to 3 + 1, "A Z" to 6 + 2, "B X" to 0 + 1, "B Y" to 3 + 2, "B Z" to 6 + 3, "C X" to 0 + 2, "C Y" to 3 + 3, "C Z" to 6 + 1 ) fun main() { fun part1(input: List<String>): Int = input.foldRight(0) { singlePlayResult, acc -> acc + RoPaScPermutations.getOrDefault(singlePlayResult, 0) } fun part2(input: List<String>): Int = input.foldRight(0) { singlePlayResult, acc -> acc + RoPaScPermElfStrategy.getOrDefault(singlePlayResult, 0) } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // check(part1(testInput) == 15) // check(part2(testInput) == 12) // // val input = readInput("Day02") // println(part1(input)) // println(part2(input)) }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> RoPaScPermutations;\n\n private static final java.util.Map<java.lang.String, java.lang.Int...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day10.kt
fun main() { fun part1(input: List<String>): Int { val cycleForSignalStrength = mutableListOf<Int>(20, 60, 100, 140, 180, 220) val register = Register() val clock = Clock().apply { addProcessors(register) } val signalStrength = buildList { input .forEach { instruction -> register .parseInstruction(instruction) while (!register.isInstructionDone) { clock.incrementCycle() if (cycleForSignalStrength.isNotEmpty() && clock.cycle == cycleForSignalStrength.first()) { add(Pair(cycleForSignalStrength.removeFirst(), register.value)) } } register.executeInstruction() } } clock.removeProcessor(register) return signalStrength .sumOf { it.first * it.second } } fun part2(input: List<String>): Int { val register = Register() val clock = Clock().apply { addProcessors(register) } val crtAllPixels = buildList { input .forEach { instruction -> register .parseInstruction(instruction) while (!register.isInstructionDone) { val crtCurrentPosition = (clock.cycle) % 40 val sprite = register.value - 1 .. register.value + 1 if (crtCurrentPosition in sprite) add("#") else add(".") clock.incrementCycle() } register.executeInstruction() } } clock.removeProcessor(register) return crtAllPixels .also { drawCrtAllPixels(it) } .also { println() } .filter { it == "#" } .size } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day10_test") // check(part1(testInput) == 13140) // check(part2(testInput) == 124) // // val input = readInput("Day10") // println(part1(input)) // println(part2(input)) } interface Processor { fun process() } data class Clock(var cycle: Int = 0) { val processors = mutableListOf<Processor>() fun incrementCycle() { cycle++ processors.forEach { processor -> processor.process() } } fun addProcessors(processor: Processor) { if (!processors.contains(processor)) processors.add(processor) } fun removeProcessor(processor: Processor) { if (!processors.contains(processor)) processors.remove(processor) } } class Register(var value: Int = 1) : Processor { sealed class Instruction(var cyclesLeft: Int, val valueToAdd: Int) { data class Noop(val value: Int = 0): Instruction(1, value) data class AddX(val value: Int): Instruction(2, value) } val isInstructionDone: Boolean get() = currentInstruction.cyclesLeft == 0 lateinit var currentInstruction: Instruction override fun process() { currentInstruction.cyclesLeft-- } fun executeInstruction() { value += currentInstruction.valueToAdd } } fun Register.parseInstruction(instruction: String) { val noopOrAddX = instruction.split(" ") when (noopOrAddX.first()) { "noop" -> currentInstruction = Register.Instruction.Noop() "addx" -> currentInstruction = Register.Instruction.AddX(noopOrAddX.last().toInt()) } } fun drawCrtAllPixels(crtAllPixels: List<String>) { crtAllPixels.forEachIndexed { index, pixel -> if ((index) % 40 == 0) println() print(pixel) } }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day10Kt.class", "javap": "Compiled from \"Day10.kt\"\npublic final class Day10Kt {\n public static final void main();\n Code:\n 0: return\n\n public static final void parseInstruction(Register, java.lang.String);\n Code:\n 0: alo...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day08.kt
import java.lang.StrictMath.max fun main() { fun part1(input: List<String>): Int { val treesGraph = AdjacencyList<Int>() val verticesOfTreeHeight = treesGraph.parseVertices(input) return verticesOfTreeHeight .fold(0) { acc, vertex -> if (vertex `is max in all directions of` treesGraph) acc + 1 else acc } } fun part2(input: List<String>): Int { val treesGraph = AdjacencyList<Int>() val verticesOfTreeHeight = treesGraph.parseVertices(input) return verticesOfTreeHeight .fold(Int.MIN_VALUE) { maxScenicScoreSoFar, vertex -> max( maxScenicScoreSoFar, vertex `scenic score` treesGraph ) } } // test if implementation meets criteria from the description, like: /* val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input))*/ } data class Vertex<T>( val index: Int, val data: T ) data class Edge<T>( val source: Vertex<T>, val destination: Vertex<T>, val direction: Graph.EdgeType, val weight: Double? ) interface Graph<T> { fun createVertex(data: T): Vertex<T> fun addDirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: EdgeType, weight: Double?, ) fun addUndirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: EdgeType, weight: Double? ) fun add( edge: EdgeType, source: Vertex<T>, destination: Vertex<T>, weight: Double? ) fun edges(source: Vertex<T>): Map<EdgeType,Edge<T>> fun weight( source: Vertex<T>, destination: Vertex<T> ) : Double? enum class EdgeType { RIGHT, LEFT, ABOVE, BELOW } } fun Graph.EdgeType.opposite(): Graph.EdgeType = when(this) { Graph.EdgeType.RIGHT -> Graph.EdgeType.LEFT Graph.EdgeType.LEFT -> Graph.EdgeType.RIGHT Graph.EdgeType.ABOVE -> Graph.EdgeType.BELOW Graph.EdgeType.BELOW -> Graph.EdgeType.ABOVE } class AdjacencyList <T> : Graph<T> { private val adjacencies: HashMap<Vertex<T>, MutableMap<Graph.EdgeType,Edge<T>>> = HashMap() override fun createVertex(data: T): Vertex<T> { val vertex = Vertex(adjacencies.count(), data) adjacencies[vertex] = mutableMapOf() return vertex } override fun addDirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: Graph.EdgeType, weight: Double? ) { val edge = Edge(source, destination, direction, weight) adjacencies[source]?.put(edge.direction, edge) } override fun addUndirectedEdge( source: Vertex<T>, destination: Vertex<T>, direction: Graph.EdgeType, weight: Double? ) { addDirectedEdge(source, destination, direction, weight) addDirectedEdge(destination, source, direction.opposite(), weight) } override fun add(edge: Graph.EdgeType, source: Vertex<T>, destination: Vertex<T>, weight: Double?) = addUndirectedEdge(source, destination, edge, weight) override fun edges(source: Vertex<T>): Map<Graph.EdgeType, Edge<T>> = adjacencies[source] ?: mutableMapOf<Graph.EdgeType, Edge<T>>() override fun weight(source: Vertex<T>, destination: Vertex<T>): Double? { return edges(source).map { it.value }.firstOrNull { it.destination == destination }?.weight } override fun toString(): String { return buildString { // 1 adjacencies.forEach { (vertex, edges) -> // 2 val edgeString = edges .map {Pair(it.key,it.value)}.joinToString { it.second.destination.data.toString() + " " + it.first.toString()} // 3 append("${vertex.data} ---> [ $edgeString ]\n") // 4 } } } } fun AdjacencyList<Int>.parseVertices(verticesData: List<String>): List<Vertex<Int>> { val verticesDataMatrix = verticesData.map { verticesDataRow -> verticesDataRow .chunked(1) .map { treeHeight -> treeHeight.toInt() } } val verticesDataRow = verticesDataMatrix.first().size val verticesDataColumn = verticesDataMatrix.size val verticesLastRow = verticesDataRow * verticesDataColumn + 1 - verticesDataRow .. verticesDataRow * verticesDataColumn val verticesList = verticesDataMatrix .flatten() .map { createVertex(it) } for (vertex in verticesList) { val vertexPosition = vertex.index + 1 if (vertexPosition % verticesDataRow != 0) { add(Graph.EdgeType.RIGHT, vertex, verticesList[vertex.index + 1], null) } if (vertexPosition !in verticesLastRow) { add(Graph.EdgeType.BELOW, vertex, verticesList[vertex.index + verticesDataRow], null) } } return verticesList } fun Vertex<Int>.isMax(graph: Graph<Int>, direction: Graph.EdgeType): Boolean { tailrec fun go(direction: Graph.EdgeType, vert: Vertex< Int>, maxSoFar: Int): Int { val destinationVertex = graph.edges(vert)[direction]?.destination return if (destinationVertex == null) maxSoFar else go(direction, destinationVertex, max(maxSoFar, destinationVertex.data)) } val isMaximum by lazy { this.data > go(direction, this, Integer.MIN_VALUE) } return isMaximum } infix fun Vertex<Int>.`is max in all directions of`(graph: Graph<Int>): Boolean = isMax(graph, Graph.EdgeType.RIGHT) || isMax(graph, Graph.EdgeType.LEFT) || isMax(graph, Graph.EdgeType.ABOVE) || isMax(graph, Graph.EdgeType.BELOW) fun Vertex<Int>.countToImmediateMax(graph: Graph<Int>, direction: Graph.EdgeType): Int { fun Int.go(direction: Graph.EdgeType, vert: Vertex<Int>, smallerImmediateVerticesCount: Int): Int { val destinationVertex = graph.edges(vert)[direction]?.destination return when { destinationVertex == null -> smallerImmediateVerticesCount destinationVertex.data >= this -> smallerImmediateVerticesCount + 1 else -> go(direction, destinationVertex, smallerImmediateVerticesCount + 1) } } return data.go(direction, this, 0) } infix fun Vertex<Int>.`scenic score`(graph: Graph<Int>): Int = countToImmediateMax(graph, Graph.EdgeType.RIGHT) * countToImmediateMax(graph, Graph.EdgeType.LEFT) * countToImmediateMax(graph, Graph.EdgeType.ABOVE) * countToImmediateMax(graph, Graph.EdgeType.BELOW)
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day08Kt$WhenMappings.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method Graph$E...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day09.kt
import java.lang.Math.abs fun main() { fun part1(headKnotMotionsData: List<String>): Int { val tail = Knot("tail") val head = Knot("head") tail `join to follow` head headKnotMotionsData .map { it.split(" ") } .forEach { val direction = it.first() val magnitude = it.last().toInt() head .appendMove(direction, magnitude) head.execute() } tail `unjoin so as not to follow` head return tail .positions .distinct() .also { it.map(::println) } .size } fun part2(headKnotMotionsData: List<String>): Int { val head = Knot("head") val tailOne = Knot("tailOne") val tailTwo = Knot("tailTwo") val tailThree = Knot("tailThree") val tailFour = Knot("tailFour") val tailFive = Knot("tailFive") val tailSix = Knot("tailSix") val tailSeven = Knot("tailSeven") val tailEight = Knot("tailEight") val tailNine = Knot("tailNine") tailOne `join to follow` head tailTwo `join to follow` tailOne tailThree `join to follow` tailTwo tailFour `join to follow` tailThree tailFive `join to follow` tailFour tailSix `join to follow` tailFive tailSeven `join to follow` tailSix tailEight `join to follow` tailSeven tailNine `join to follow` tailEight headKnotMotionsData .map { it.split(" ") } .forEach { val direction = it.first() val magnitude = it.last().toInt() head .appendMove(direction, magnitude) } head.execute() tailOne `unjoin so as not to follow` head tailTwo `unjoin so as not to follow` tailOne tailThree `unjoin so as not to follow` tailTwo tailFour `unjoin so as not to follow` tailThree tailFive `unjoin so as not to follow` tailFour tailSix `unjoin so as not to follow` tailFive tailSeven `unjoin so as not to follow` tailSix tailEight `unjoin so as not to follow` tailSeven tailNine `unjoin so as not to follow` tailEight return tailNine .positions .distinct() .also { it.map(::println) } .size } // test if implementation meets criteria from the description, like: /* val testInput = readInput("Day09_test") check(part1(testInput) == 13) // testInputTwo is the larger example on the AOC website day 09 challenge of 2022 val testInputTwo = readInput("Day09_test_two") check(part2(testInputTwo) == 36) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input))*/ } typealias Command = () -> Unit data class Position(val x: Int, val y: Int) class Knot( val name: String, var _xPosition: Int = 0, var _yPosition: Int = 0 ) { private val orders = mutableListOf<Command>() private val _positions = mutableListOf<Position>() val positions get() = _positions.toList() val followers: HashMap<String, Knot> = HashMap() val moveGenerator = fun( knot: Knot, direction: String, qnty: Int ): Command { return fun() { when (direction) { "R" -> repeat(qnty) { knot.toRight() } "L" -> repeat(qnty) { knot.toLeft() } "U" -> repeat(qnty) { knot.toUp() } "D" -> repeat(qnty) { knot.toDown() } else -> {} } } } init { appendOrigin() } fun xPosition(xPosition: Int) { _xPosition = xPosition } fun yPosition(yPosition: Int) { _yPosition = yPosition } fun appendMove(direction: String, qnty: Int) = apply { orders.add(moveGenerator(this, direction, qnty)) } fun appendOrigin() { _positions.add(Position(0, 0)) } private fun toLeft() { _xPosition-- moved() } private fun toRight() { _xPosition++ moved() } private fun toDown() { _yPosition-- moved() } private fun toUp() { _yPosition++ moved() } fun moved() { _positions.add(Position(_xPosition, _yPosition)) for ((_, follower) in followers) { follower.follow(this) } } fun execute() { while (!orders.isEmpty()) { val order = orders.removeAt(0) order.invoke() println("$name x -> $_xPosition y -> $_yPosition") } } fun follow(leader: Knot) { val deltaX = abs(leader._xPosition - this._xPosition) val deltaY = abs(leader._yPosition - this._yPosition) val xDirection = if (leader._xPosition - _xPosition > 0) "R" else "L" val yDirection = if (leader._yPosition - _yPosition > 0) "U" else "D" when { deltaX > 1 && deltaY > 0 || deltaY > 1 && deltaX > 0 -> { moveDiagonally(xDirection, yDirection) moved() } deltaX > 1 -> appendMove(xDirection, deltaX - 1).execute() deltaY > 1 -> appendMove(yDirection, deltaY - 1).execute() } } fun moveDiagonally(xDirection: String, yDirection: String) { when { xDirection == "L" -> _xPosition-- xDirection == "R" -> _xPosition++ } when { yDirection == "U" -> _yPosition++ yDirection == "D" -> _yPosition-- } /* appendMove(xDirection, 1) .appendMove(yDirection, 1) .execute()*/ } } infix fun Knot.`join to follow`(head: Knot) { head.followers.put(this.name, this) println("${head.name} has a new follower $name") } infix fun Knot.`unjoin so as not to follow`(head: Knot) { head.followers.remove(name) println("${head.name} has been unfollowed by $name") }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n public static final void main();\n Code:\n 0: return\n\n public static final void join to follow(Knot, Knot);\n Code:\n 0: aload_0\n 1: ld...
GreyWolf2020__aoc-2022-in-kotlin__498da88/src/Day01.kt
import java.lang.Integer.max fun main() { fun part1(input: List<String>): Int { val sumIndex = 0 val maxSumIndex = 1 val zeroCalorie = 0 return input.map { it.toIntOrNull() }.foldRight(intArrayOf(0, 0)) { calorieOrNull, acc -> calorieOrNull ?.let { calorie -> intArrayOf(acc[sumIndex] + calorie, acc[maxSumIndex]) } ?: run { intArrayOf(zeroCalorie, max(acc[maxSumIndex], acc[sumIndex])) } }[maxSumIndex] } fun part2(input: List<String>): Int { val sumIndex = 0 val highSumIndex = 1 val highHighSumIndex = 2 val highHighHighSumIndex = 3 val zeroCalorie = 0 return input.map { it.toIntOrNull() }.foldRight(intArrayOf(0, 0, 0, 0)) { calorieOrNull, acc -> calorieOrNull?.let { calorie -> intArrayOf(acc[sumIndex] + calorie, acc[highSumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex]) } ?: run { when { acc[sumIndex] > acc[highSumIndex] && acc[sumIndex] < acc[highHighSumIndex] -> intArrayOf(zeroCalorie, acc[sumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex]) acc[sumIndex] > acc[highHighSumIndex] && acc[sumIndex] < acc[highHighHighSumIndex] -> intArrayOf(zeroCalorie, acc[highHighSumIndex], acc[sumIndex], acc[highHighHighSumIndex]) acc[sumIndex] > acc[3] -> intArrayOf(zeroCalorie, acc[highHighSumIndex], acc[highHighHighSumIndex], acc[sumIndex]) else -> intArrayOf(zeroCalorie, acc[highSumIndex], acc[highHighSumIndex], acc[highHighHighSumIndex]) } } } .drop(1) .sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // check(part1(testInput) == 24000) // check(part2(testInput) == 45000) // // val input = readInput("Day01") // println(part1(input)) // println(part2(input)) }
[ { "class_path": "GreyWolf2020__aoc-2022-in-kotlin__498da88/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: return\n\n public static void main(java.lang.String[]);\n Code:\n 0: invokestatic #9 ...
holukent__aoc-2022-in-kotlin__6993a6f/src/Day04.kt
import java.io.File fun main() { fun part1(input: String): Int { val data = input.split("\r\n") var result = 0 for (d in data) { val temp = d.split(",").map { it.split("-") } val first = temp[0] val second = temp[1] if ( (first[0].toInt() <= second[0].toInt() && first[1].toInt() >= second[1].toInt()) || (first[0].toInt() >= second[0].toInt() && first[1].toInt() <= second[1].toInt()) ) { result++ } } return result } fun part2(input: String): Int { val data = input.split("\r\n") var result = 0 for (d in data) { val temp = d.split(",").map { it.split("-") } val first = temp[0].map { it.toInt() } val second = temp[1].map { it.toInt() } if ( (first[0] in second[0]..second[1]) || (first[1] in second[0]..second[1]) || (second[0] in first[0]..first[1]) || (second[0] in first[0]..first[1]) ) { result++ } } return result } val testInput = File("src/Day04_test.txt").readText() check(part2(testInput) == 4) val input = File("src/Day04.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "holukent__aoc-2022-in-kotlin__6993a6f/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
TheRenegadeCoder__sample-programs__bd5f385/archive/k/kotlin/JobSequencing.kt
fun main(args: Array<String>) { val jobs = buildJobs(args) if (jobs.isNullOrEmpty()) { println("Usage: please provide a list of profits and a list of deadlines") } else { println(maxProfit(jobs)) } } /** * Calculates the maximum profit of a list of jobs */ private fun maxProfit(jobs: List<Job>): Int { val scheduled = hashSetOf<Int>() var profit = 0 jobs.sortedByDescending { it.profit }.forEach { for (i in it.deadline downTo 1) { if (scheduled.add(i)) { profit += it.profit break } } } return profit } /** * Builds job list with input arguments */ private fun buildJobs(args: Array<String>): List<Job>? { if (args.run { isNullOrEmpty() || size < 2 || any { it.isBlank() } }) return null val profits = args[0].toIntArray() val deadlines = args[1].toIntArray() if (profits.size != deadlines.size) return null return profits.mapIndexed { index, profit -> Job(profit, deadlines[index]) } } /** * Represents the information of a job */ class Job(val profit: Int, val deadline: Int) /** * Extracts an array of integers from the string */ fun String.toIntArray() = split(",").mapNotNull { it.trim().toIntOrNull() }
[ { "class_path": "TheRenegadeCoder__sample-programs__bd5f385/JobSequencingKt.class", "javap": "Compiled from \"JobSequencing.kt\"\npublic final class JobSequencingKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String ar...
TheRenegadeCoder__sample-programs__bd5f385/archive/k/kotlin/Rot13.kt
data class EncodingBounds(val lowerBound: Int, val upperBound: Int) fun encodingBoundsForCharValue(c: Char): EncodingBounds? { val lowerCaseBounds = EncodingBounds('a'.toInt(), 'z'.toInt()) val upperCaseBounds = EncodingBounds('A'.toInt(), 'Z'.toInt()) return when (c) { in 'a'..'z' -> lowerCaseBounds in 'A'..'Z' -> upperCaseBounds else -> null } } fun calculateRotatedChar(char: Char, rotation: Int, bounds: EncodingBounds): Char { val rotatedCharVal = char.toInt() + rotation val remainder = rotatedCharVal - (bounds.upperBound + 1) return (if (rotatedCharVal > bounds.upperBound) bounds.lowerBound + remainder else rotatedCharVal).toChar() } fun parseInput(args: Array<String>): String? { if (args.isEmpty()) { return null } val text = args[0] if (text.isEmpty()) { return null } return text } fun rot13Encode(text: String): String { val rotation = 13 return text.map { c -> val bounds = encodingBoundsForCharValue(c) if (bounds == null) { c.toString() } else { calculateRotatedChar(c, rotation, bounds).toString() } }.reduce { encodedText, encodedChar -> encodedText + encodedChar } } fun main(args: Array<String>) { val strToEncode = parseInput(args) if (strToEncode == null) { println("Usage: please provide a string to encrypt") } else { println(rot13Encode(strToEncode)) } }
[ { "class_path": "TheRenegadeCoder__sample-programs__bd5f385/Rot13Kt.class", "javap": "Compiled from \"Rot13.kt\"\npublic final class Rot13Kt {\n public static final EncodingBounds encodingBoundsForCharValue(char);\n Code:\n 0: new #9 // class EncodingBounds\n 3: du...
Ad0lphus__AOC2021__02f219e/day15/Kotlin/day15.kt
import java.io.* import java.util.* fun print_day_15() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 15" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Chiton -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_15() Day15().part_1() Day15().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day15 { data class Node(val x:Int = 0, val y:Int = 0, val dist: Int = 0) fun part_1() { val grid = File("../Input/day15.txt").readLines().map { it.toCharArray().map{ it.digitToInt() } } print("Puzzle 1: ") findShortestPath(grid) } private fun findShortestPath(grid: List<List<Int>>) { val pathways = Array(grid.size) { Array(grid[0].size) { Int.MAX_VALUE } } val queue = PriorityQueue<Node> { nodeA, nodeB -> nodeA.dist - nodeB.dist } pathways[0][0] = 0 queue.add(Node(0,0, 0)) while(queue.isNotEmpty()) { val (x, y, dist) = queue.poll() listOf(x to y + 1, x to y - 1, x + 1 to y, x - 1 to y).forEach { (X, Y) -> if (X in grid.indices && Y in grid[0].indices && pathways[X][Y] > dist + grid[X][Y]) { pathways[X][Y] = dist + grid[X][Y] queue.add(Node(X, Y, pathways[X][Y])) } } } println(pathways.last().last()) } fun part_2() { val input = File("../Input/day15.txt").readLines() val totalY = input.size val totalX = input.first().length val grid = (0 until totalY * 5).map { y -> (0 until totalX * 5).map { x -> val baseNum = input[y % totalY][x % totalX].digitToInt() val tileDistance = (x/totalX) + (y/totalY) if (baseNum + tileDistance < 10) baseNum + tileDistance else (baseNum + tileDistance) - 9 } } print("Puzzle 2: ") findShortestPath(grid) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day15.class", "javap": "Compiled from \"day15.kt\"\npublic final class Day15 {\n public Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n public final void part_1()...
Ad0lphus__AOC2021__02f219e/day21/Kotlin/day21.kt
import java.io.* import java.util.concurrent.atomic.AtomicInteger fun print_day_21() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 21" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Dirac Dice -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_21() Day21().part1() Day21().part2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day21 { fun part1() { val startPos = File("../Input/day21.txt").readLines().map { it.last().digitToInt() } val scores = intArrayOf(0, 0) val space = startPos.toIntArray() val dice = AtomicInteger() var diceRolls = 0 fun nextRoll(): Int { if (dice.get() >= 100) dice.set(0) diceRolls++ return dice.incrementAndGet() } while (true) { repeat(2) { val roll = nextRoll() + nextRoll() + nextRoll() space[it] = (space[it] + roll) % 10 scores[it] += if (space[it] != 0) space[it] else 10 if (scores[it] >= 1000) { println("Puzzle 1: " + scores[(it + 1) % 2] * diceRolls) return } } } } fun part2() { data class Universe(val p1: Int, val p2: Int, val s1: Int, val s2: Int) val startPos = File("../Input/day21.txt").readLines().map { it.last().digitToInt() } val dp = mutableMapOf<Universe, Pair<Long, Long>>() fun solve(u: Universe): Pair<Long, Long> { dp[u]?.let { return it } if (u.s1 >= 21) return 1L to 0L if (u.s2 >= 21) return 0L to 1L var ans = 0L to 0L for (d1 in 1..3) for (d2 in 1..3) for (d3 in 1..3) { val newP1 = (u.p1 + d1 + d2 + d3 - 1) % 10 + 1 val newS1 = u.s1 + newP1 val (x, y) = solve(Universe(u.p2, newP1, u.s2, newS1)) ans = ans.first + y to ans.second + x } return ans.also { dp[u] = it } } println( "Puzzle 2: " + solve(Universe(startPos[0], startPos[1], 0, 0)).let { maxOf(it.first, it.second) } ) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day21$part2$Universe.class", "javap": "Compiled from \"day21.kt\"\npublic final class Day21$part2$Universe {\n private final int p1;\n\n private final int p2;\n\n private final int s1;\n\n private final int s2;\n\n public Day21$part2$Universe(int, int, int, i...
Ad0lphus__AOC2021__02f219e/day14/Kotlin/day14.kt
import java.io.* fun print_day_14() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 14" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Extended Polymerization -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_14() Day14().part_1() Day14().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day14 { val lines = File("../Input/day14.txt").readLines() val polyTemplate = lines.first() fun part_1() { val pairInsertions = lines.drop(2).map { val (pair, insertion) = it.split(" -> ") pair to insertion } var polyIteration = polyTemplate for (step in 1..10) { polyIteration = polyIteration.fold("") { str, curr -> val pairCheck = "" + (str.lastOrNull() ?: "") + curr val insert = pairInsertions.find { it.first == pairCheck } ?.second ?: "" str + insert + curr } } val elementCounts = polyIteration.groupBy { it }.map { it.key to it.value.size }.sortedBy { it.second } val ans = elementCounts.last().second - elementCounts.first().second println("Puzzle 1: $ans") } fun part_2() { val insertPattern = lines.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] } var pairFrequency = mutableMapOf<String, Long>() polyTemplate.windowed(2).forEach{ pairFrequency.put(it, pairFrequency.getOrDefault(it, 0) + 1) } for (step in 1..40) { val updatedFrequencies = mutableMapOf<String, Long>() pairFrequency.forEach { val key1 = it.key[0] + insertPattern[it.key]!! val key2 = insertPattern[it.key]!! + it.key[1] updatedFrequencies.put(key1, updatedFrequencies.getOrDefault(key1, 0) + it.value) updatedFrequencies.put(key2, updatedFrequencies.getOrDefault(key2, 0) + it.value) } pairFrequency = updatedFrequencies } val charFrequency = pairFrequency.toList().fold(mutableMapOf<Char, Long>()) { acc, pair -> acc.put(pair.first[0], acc.getOrDefault(pair.first[0], 0) + pair.second) acc } charFrequency.put(polyTemplate.last(), charFrequency.getOrDefault(polyTemplate.last(), 0) + 1) val sorted = charFrequency.values.sorted() val ans = sorted.last() - sorted.first() println("Puzzle 2: $ans") } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day14Kt.class", "javap": "Compiled from \"day14.kt\"\npublic final class Day14Kt {\n public static final void print_day_14();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day04/Kotlin/day04.kt
import java.io.* fun print_day_4() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 4" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Giant Squid -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_4() print("Puzzle 1: ") Day4().part_1() print("Puzzle 2: ") Day4().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day4 { private val lines = File("../Input/day4.txt").readLines() private val drawOrder = lines[0].split(",").map { it.toInt() } private val boards = lines.drop(1).windowed(6, 6) { it.drop(1).map { line -> line.trim().split(" ", " ").map { numStr -> numStr.toInt() } } } fun checkLine(line: List<Int>, drawn: List<Int>) = drawn.containsAll(line) fun checkBoard(board: List<List<Int>>, drawn: List<Int>): Boolean { val hasHorizontalLine = board.any { checkLine(it, drawn) } val flippedBoard = (board[0].indices).map { outer -> (board.indices).map { inner -> board[inner][outer] } } val hasVerticalLine = flippedBoard.any { checkLine(it, drawn) } return hasHorizontalLine || hasVerticalLine } fun part_1() { for (i in 5..drawOrder.size) { val currentDraw = drawOrder.take(i) boards.forEach() { if (checkBoard(it, currentDraw)) { return calculateWinner(it, currentDraw) } } } } private fun calculateWinner(board: List<List<Int>>, currentDraw: List<Int>) { println(board.flatten().filter { !currentDraw.contains(it) }.sum() * currentDraw.last()) } fun part_2() { val winners = mutableListOf<Int>() for (i in 5..drawOrder.size) { val currentDraw = drawOrder.take(i) boards.forEachIndexed() { index, board -> if (!winners.contains(index) && checkBoard(board, currentDraw)) { winners.add(index) if (winners.size == boards.size) { return calculateWinner(board, currentDraw) } } } } } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day04Kt.class", "javap": "Compiled from \"day04.kt\"\npublic final class Day04Kt {\n public static final void print_day_4();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day22/Kotlin/day22.kt
import java.io.* fun print_day_22() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 22" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Reactor Reboot -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_22() Day22().part1() Day22().part2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } fun String.toRange(): IntRange = this.split("..").let { IntRange(it[0].toInt(), it[1].toInt()) } class Day22 { fun String.toRange(): IntRange = this.split("..").let { IntRange(it[0].toInt(), it[1].toInt()) } data class Point3D(val x: Int, val y: Int, val z: Int) data class Cube(val xAxis: IntRange, val yAxis: IntRange, val zAxis: IntRange) { fun cubicVolume() = 1L * this.xAxis.count() * this.yAxis.count() * this.zAxis.count() fun overlaps(that: Cube) = (this.xAxis.first <= that.xAxis.last && this.xAxis.last >= that.xAxis.first) && (this.yAxis.first <= that.yAxis.last && this.yAxis.last >= that.yAxis.first) && (this.zAxis.first <= that.zAxis.last && this.zAxis.last >= that.zAxis.first) fun intersect(that: Cube) = if (!overlaps(that)) null else Cube( maxOf(this.xAxis.first, that.xAxis.first)..minOf( this.xAxis.last, that.xAxis.last ), maxOf(this.yAxis.first, that.yAxis.first)..minOf( this.yAxis.last, that.yAxis.last ), maxOf(this.zAxis.first, that.zAxis.first)..minOf( this.zAxis.last, that.zAxis.last ) ) } data class Cuboid(val cube: Cube, val on: Boolean) { fun intersect(other: Cuboid) = if (this.cube.overlaps(other.cube)) Cuboid(this.cube.intersect(other.cube)!!, !on) else null } private val cubes = File("../Input/day22.txt").readLines().map { val on = it.split(" ").first() == "on" val cube = it.split(" ").last().split(",").let { Cube( it[0].drop(2).toRange(), it[1].drop(2).toRange(), it[2].drop(2).toRange() ) } Cuboid(cube, on) } fun part1() { val region = Cube(-50..50, -50..50, -50..50) val onCubes = mutableSetOf<Point3D>() cubes.forEach { val (cube, on) = it if (cube.overlaps(region)) { cube.xAxis.forEach { x -> cube.yAxis.forEach { y -> cube.zAxis.forEach { z -> if (on) onCubes.add(Point3D(x, y, z)) else onCubes.remove(Point3D(x, y, z)) } } } } } println("Puzzle 1: " + onCubes.size) } fun part2() { fun findIntersections(a: Cube, b: Cube): Cube? = if (a.overlaps(b)) a.intersect(b) else null val volumes = mutableListOf<Cuboid>() cubes.forEach { cube -> volumes.addAll( volumes.mapNotNull { other -> findIntersections(cube.cube, other.cube)?.let { Cuboid(it, !other.on) } } ) if (cube.on) volumes.add(cube) } println("Puzzle 2: " + volumes.sumOf { it.cube.cubicVolume() * (if (it.on) 1 else -1) }) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day22Kt.class", "javap": "Compiled from \"day22.kt\"\npublic final class Day22Kt {\n public static final void print_day_22();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day17/Kotlin/day17.kt
import java.io.* fun print_day_17() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 17" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Trick Shot -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_17() println("Puzzle 1: ${Day17().part_1()}") println("Puzzle 2: ${Day17().part_2()}") println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day17 { data class BoundingBox(val xRange: IntRange, val yRange: IntRange) private val target = File("../Input/day17.txt").readLines().first().drop(13) .split(", ").map { it.drop(2).split("..").let { (a, b) -> a.toInt()..b.toInt() }} .let { BoundingBox(it[0], it[1]) } fun part_1() = (1..400).flatMap { x -> (1..400).map { y -> checkStep(x, y, target) } }.fold(0) { max, step -> if (step.first) maxOf(max, step.second) else max } fun part_2() = (1..400).flatMap { x -> (-400..400).map { y -> checkStep(x, y, target).first } }.count { it } data class Coord(var x:Int, var y:Int) data class Velocity(var x:Int, var y:Int) private fun checkStep(xVelocity: Int, yVelocity: Int, target: BoundingBox): Pair<Boolean, Int> { val p = Coord(0, 0) val v = Velocity(xVelocity, yVelocity) var maxHeight = 0 var hitTarget = false while (p.x <= target.xRange.last && p.y >= target.yRange.first) { p.x += v.x p.y += v.y maxHeight = maxOf(p.y, maxHeight) if (p.x in target.xRange && p.y in target.yRange) { hitTarget = true break } if (v.x > 0) v.x-- v.y-- } return Pair(hitTarget, maxHeight) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day17.class", "javap": "Compiled from \"day17.kt\"\npublic final class Day17 {\n private final Day17$BoundingBox target;\n\n public Day17();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
Ad0lphus__AOC2021__02f219e/day13/Kotlin/day13.kt
import java.io.* fun print_day_13() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 13" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Transparent Origami -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_13() Day13().part_1() Day13().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day13 { private val lines = File("../Input/day13.txt").readLines() private val coords = lines.takeWhile { it.trim() != "" }.map { val (x, y) = it.split(",") x.toInt() to y.toInt() } private val folds = lines.drop(coords.size + 1) fun part_1() { val maxX = coords.maxOf { it.first } val maxY = coords.maxOf { it.second } val yFold = folds.first().startsWith("fold along y") val foldAmount = folds.first().split("=")[1].toInt() val afterFold = if (yFold) { val newCoords = coords.filter { it.second < foldAmount }.toMutableList() for (pair in coords.filter {it.second > foldAmount} ) { newCoords.add(pair.first to maxY - pair.second) } newCoords } else { val newCoords = coords.filter { it.first < foldAmount }.toMutableList() for (pair in coords.filter {it.first > foldAmount} ) { newCoords.add(maxX - pair.first to pair.second) } newCoords } println("Puzzle 1: " + afterFold.distinct().size) } fun part_2() { var foldedCoords = coords folds.forEach { fold -> val maxX = foldedCoords.maxOf { it.first } val maxY = foldedCoords.maxOf { it.second } val yFold = fold.startsWith("fold along y") val foldAmount = fold.split("=")[1].toInt() val afterFold = if (yFold) { val newCoords = foldedCoords.filter { it.second < foldAmount }.toMutableList() for (pair in foldedCoords.filter {it.second > foldAmount} ) { newCoords.add(pair.first to maxY - pair.second) } newCoords } else { val newCoords = foldedCoords.filter { it.first < foldAmount }.toMutableList() for (pair in foldedCoords.filter {it.first > foldAmount} ) { newCoords.add(maxX - pair.first to pair.second) } newCoords } foldedCoords = afterFold } val maxX = foldedCoords.maxOf { it.first } val maxY = foldedCoords.maxOf { it.second } println("Puzzle 2: ") for (y in 0..maxY) { for (x in 0..maxX) { print( if ((x to y) in foldedCoords) "#" else " ") } println() } } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day13.class", "javap": "Compiled from \"day13.kt\"\npublic final class Day13 {\n private final java.util.List<java.lang.String> lines;\n\n private final java.util.List<kotlin.Pair<java.lang.Integer, java.lang.Integer>> coords;\n\n private final java.util.List<j...
Ad0lphus__AOC2021__02f219e/day05/Kotlin/day05.kt
import java.io.* import kotlin.math.abs fun print_day_5() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 5" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Hydrothermal Venture -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_5() Day5().puzzle1() Day5().puzzle2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day5 { data class Point(val x:Int, val y: Int) private val lines = File("../Input/day5.txt").readLines() private val points = lines.map { line -> line.split(" -> ").map { point -> val pairs = point.split(",") Point(pairs[0].toInt(), pairs[1].toInt()) } } fun puzzle1() { val map2d = Array(1000) { Array(1000) { 0 } } points.forEach() { if (it[0].x == it[1].x) { val min = Math.min(it[0].y, it[1].y) val max = Math.max(it[0].y, it[1].y) for(i in min..max) { map2d[i][it[0].x]++ } } else if (it[0].y == it[1].y) { val min = Math.min(it[0].x, it[1].x) val max = Math.max(it[0].x, it[1].x) for(i in min..max) { map2d[it[0].y][i]++ } } } val overlaps = map2d.sumOf { it.count { point -> point >= 2 } } println("Puzzle 1: " + overlaps) } fun puzzle2() { val map2d = Array(1000) { Array(1000) { 0 } } points.forEach() { if (it[0].x == it[1].x) { val min = Math.min(it[0].y, it[1].y) val max = Math.max(it[0].y, it[1].y) for(i in min..max) { map2d[i][it[0].x]++ } } else if (it[0].y == it[1].y) { val min = Math.min(it[0].x, it[1].x) val max = Math.max(it[0].x, it[1].x) for(i in min..max) { map2d[it[0].y][i]++ } } else if ( isDiagonal(it[0], it[1]) ) { val len = abs(it[0].x - it[1].x) val xStep = if (it[1].x - it[0].x > 0) 1 else -1 val yStep = if (it[1].y - it[0].y > 0) 1 else -1 for(i in 0..len) { val y = it[0].y + (i*yStep) val x = it[0].x + (i*xStep) map2d[y][x]++ } } } val overlaps = map2d.sumOf { it.count { point -> point >= 2 } } println("Puzzle 2: " + overlaps) } private fun isDiagonal(p1: Point, p2: Point): Boolean = abs(p1.x - p2.x) == abs(p1.y - p2.y) }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day05Kt.class", "javap": "Compiled from \"day05.kt\"\npublic final class Day05Kt {\n public static final void print_day_5();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day11/Kotlin/day11.kt
import java.io.* fun print_day_11() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 11" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Dumbo Octopus -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_11() Day11().part_1() Day11().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day11 { private val octogrid = File("../Input/day11.txt").readLines().map { it.toCharArray().map { c -> c.digitToInt() }.toMutableList() }.toMutableList() data class GridPoint(val x:Int, val y:Int) { fun neighbours(xBoundary: Int, yBoundary: Int): List<GridPoint> = (-1 .. 1).map { yOffset -> (-1 .. 1).map { xOffset -> GridPoint(x+xOffset, y+yOffset) } }.flatten() .filter { it.x in 0 until xBoundary && it.y in 0 until yBoundary && !(it.x == x && it.y == y) } } fun part_1() { var totalFlashes = 0 for(step in 1..100) { val flashed = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { octogrid[y][x]++ } } do { val newFlashes = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { val gp = GridPoint(x, y) if (octogrid[y][x] > 9 && gp !in flashed) { newFlashes.add(gp) gp.neighbours(octogrid[y].size, octogrid.size).forEach { octogrid[it.y][it.x]++ } } } } flashed.addAll(newFlashes) } while(newFlashes.isNotEmpty()) totalFlashes += flashed.size flashed.forEach { octogrid[it.y][it.x] = 0 } } println("Puzzle 1: " + totalFlashes) } fun part_2() { val totalOctos = octogrid.flatten().size var step = 0 do { step++ val flashed = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { octogrid[y][x]++ } } do { val newFlashes = mutableListOf<GridPoint>() for (y in octogrid.indices) { for (x in octogrid[y].indices) { val gp = GridPoint(x, y) if (octogrid[y][x] > 9 && gp !in flashed) { newFlashes.add(gp) gp.neighbours(octogrid[y].size, octogrid.size).forEach { octogrid[it.y][it.x]++ } } } } flashed.addAll(newFlashes) } while(newFlashes.isNotEmpty()) flashed.forEach { octogrid[it.y][it.x] = 0 } } while(flashed.size != totalOctos) println("Puzzle 2: " + step) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day11.class", "javap": "Compiled from \"day11.kt\"\npublic final class Day11 {\n private final java.util.List<java.util.List<java.lang.Integer>> octogrid;\n\n public Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method ja...
Ad0lphus__AOC2021__02f219e/day12/Kotlin/day12.kt
import java.io.* fun print_day_12() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 12" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Passage Pathing -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_12() Day12().part_1() Day12().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day12 { data class Node(val name: String, val isLarge: Boolean = false, var connections: List<Node> = mutableListOf()) fun part_1() { val nodes = mutableMapOf<String, Node>() fun followPaths(node: Node, path: List<Node>): List<List<Node>> { val newPath = path+node return if (node.name == "end" || (path.contains(node) && !node.isLarge)) { listOf(newPath) } else { node.connections.flatMap { followPaths(it, newPath) } } } File("../Input/day12.txt").readLines().forEach { val pathway = it.split("-").map { node -> if (!nodes.containsKey(node)) { nodes[node] = Node(node, node.isUpperCase()) } nodes[node]!! } pathway[0].connections += pathway[1] pathway[1].connections += pathway[0] } val start = nodes["start"]!! val paths = followPaths(start, listOf()).filter { it.last().name == "end" } // only keep nodes that actually end println("Puzzle 1: ${paths.size}") } fun part_2() { val nodes = HashMap<String, HashSet<String>>() File("../Input/day12.txt").readLines().forEach { val (a,b) = it.split("-") nodes.getOrPut(a) { HashSet() }.add(b) nodes.getOrPut(b) { HashSet() }.add(a) } fun canVisit(name: String, path: List<String>): Boolean = when { name.isUpperCase() -> true name == "start" -> false name !in path -> true else -> path.filterNot { it.isUpperCase() }.groupBy { it }.none { it.value.size == 2 } } fun followPaths(path: List<String> = listOf("start")): List<List<String>> = if (path.last() == "end") listOf(path) else nodes.getValue(path.last()) .filter { canVisit(it, path) } .flatMap { followPaths( path + it) } println("Puzzle 2: ${followPaths().size}") } } private fun String.isUpperCase(): Boolean = this == this.uppercase()
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day12$Node.class", "javap": "Compiled from \"day12.kt\"\npublic final class Day12$Node {\n private final java.lang.String name;\n\n private final boolean isLarge;\n\n private java.util.List<Day12$Node> connections;\n\n public Day12$Node(java.lang.String, boole...
Ad0lphus__AOC2021__02f219e/day07/Kotlin/day07.kt
import java.io.* import kotlin.math.abs fun print_day_7() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 7" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet The Treachery of Whales -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_7() Day7().part_1() Day7().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day7 { val crabs = File("../Input/day7.txt").readLines().first().split(",").map{it.toInt()} fun part_1() { val min = crabs.minOrNull()!! val max = crabs.maxOrNull()!! var lowest = Int.MAX_VALUE for(i in min .. max) { var fuelUsed = 0 for(crab in crabs) { fuelUsed += abs(crab - i) } if (fuelUsed < lowest) { lowest = fuelUsed } } println("Puzzle 1: $lowest") } fun part_2() { val min = crabs.minOrNull()!! val max = crabs.maxOrNull()!! var lowest = Int.MAX_VALUE for(i in min .. max) { var fuelUsed = 0 for(crab in crabs) { fuelUsed += calcFibIncrement(abs(crab - i)) } if (fuelUsed < lowest) { lowest = fuelUsed } } println("Puzzle 2: $lowest") } fun calcFibIncrement(increment: Int, incrementBy: Int = 0): Int { return if (increment == 0) incrementBy else calcFibIncrement(increment - 1, incrementBy + 1) + incrementBy } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day07Kt.class", "javap": "Compiled from \"day07.kt\"\npublic final class Day07Kt {\n public static final void print_day_7();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day10/Kotlin/day10.kt
import java.io.* import java.util.* fun print_day_10() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 10" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Syntax Scoring -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_10() Day10().part_1() Day10().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day10 { private val lines = File("../Input/day10.txt").readLines() private val opening = arrayOf('{', '[', '(', '<') private val bracketPairs = mapOf('{' to '}', '[' to ']', '(' to ')', '<' to '>') private fun checkMatchingBrackets(stack: Stack<Char>, remainingChars: String): Int { if (remainingChars.isEmpty()) return 0 val c = remainingChars.first() if (c in opening) { stack.push(c) } else { val matchTo = stack.pop() if (bracketPairs[matchTo] != c) { return when(c) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> 0 } } } return checkMatchingBrackets(stack, remainingChars.substring(1)) } fun part_1() { val total = lines.sumOf { checkMatchingBrackets(Stack<Char>(), it) } println("Puzzle 1: " + total) } fun part_2() { val total = lines.map { val stack = Stack<Char>() if (checkMatchingBrackets(stack, it) == 0) { stack.foldRight(0L) { c, acc -> acc * 5 + when(bracketPairs[c]) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> 0 } } } else 0 } .filterNot { it == 0L } .sorted() println("Puzzle 2: " + total[(total.size / 2)]) } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day10.class", "javap": "Compiled from \"day10.kt\"\npublic final class Day10 {\n private final java.util.List<java.lang.String> lines;\n\n private final java.lang.Character[] opening;\n\n private final java.util.Map<java.lang.Character, java.lang.Character> bra...
Ad0lphus__AOC2021__02f219e/day03/Kotlin/day03.kt
import java.io.* fun print_day_3() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 3" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Binary Diagnostic -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_3() Day3().part_1() Day3().part_2() println("\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day3 { val lines = File("../Input/day3.txt").readLines() fun part_1() { val matrix = lines.map { s -> s.toCharArray().map { c -> c.digitToInt() } } var gamma = "" var epsilon = "" for(idx in matrix[0].indices) { val res = matrix.partition { it[idx] == 1 } gamma += if (res.first.count() > res.second.count()) "1" else "0" epsilon += if (res.first.count() > res.second.count()) "0" else "1" } val answer = gamma.toInt(2) * epsilon.toInt(2) println("Puzzle 1: " + answer) } fun part_2() { fun splitAndRecurse(list: List<List<Int>>, index: Int, max: Boolean) : List<Int> { if (list.size == 1) return list[0] val res = list.partition { it[index] == 1 } val keep = if (res.first.count() >= res.second.count()) if (max) res.first else res.second else if (max) res.second else res.first return splitAndRecurse(keep, index+1, max) } val matrix = lines.map { s -> s.toCharArray().map { c -> c.digitToInt() } } val oxygen = splitAndRecurse(matrix, 0, true) val co2 = splitAndRecurse(matrix, 0, false) val oxygenDecimal = oxygen.joinToString("").toInt(2) val co2Decimal = co2.joinToString("").toInt(2) println("Puzzle 2: " + oxygenDecimal * co2Decimal +"\n") } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day03Kt.class", "javap": "Compiled from \"day03.kt\"\npublic final class Day03Kt {\n public static final void print_day_3();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day18/Kotlin/day18.kt
import java.io.* fun print_day_18() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 18" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Snailfish -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_18() println("Puzzle 1: " + Day18().part_1()) println("Puzzle 2: " + Day18().part_2()) println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day18 { private val input = File("../Input/day18.txt").readLines() fun part_1() = input.map { parse(it) }.reduce { a, b -> a + b }.magnitude() fun part_2() = input.indices.flatMap { i -> input.indices.map { j -> i to j}}.filter {(i,j) -> i != j }.maxOf { (i,j) -> (parse(input[i]) + parse(input[j])).magnitude() } private fun parse(input: String): Num { var cur = 0 fun _parse(): Num = if (input[cur] == '[') { cur++ val left = _parse() cur++ val right = _parse() cur++ Num.NumPair(left, right) } else Num.NumValue(input[cur].digitToInt()).also { cur++ } return _parse() } sealed class Num { var parent: NumPair? = null class NumValue(var value: Int) : Num() { override fun toString(): String = value.toString() fun canSplit(): Boolean = value >= 10 fun split() { val num = NumPair(NumValue(value / 2), NumValue((value + 1) / 2)) parent?.replaceWith(this, num) } } class NumPair(var left: Num, var right: Num) : Num() { init { left.parent = this right.parent = this } override fun toString(): String = "[$left,$right]" fun explode() { val x = if (left is NumValue) (left as NumValue).value else null val y = if (right is NumValue) (right as NumValue).value else null findValueToLeft()?.let { it.value += x!! } findValueToRight()?.let { it.value += y!! } parent?.replaceWith(this, NumValue(0)) } fun replaceWith(child: Num, newValue: Num) { if (left == child) { left = newValue } else if (right == child){ right = newValue } newValue.parent = this } } fun magnitude(): Int = when(this) { is NumValue -> value is NumPair -> left.magnitude() * 3 + right.magnitude() * 2 } operator fun plus(other: Num): Num = NumPair(this, other).apply { left.parent = this right.parent = this reduce() } fun reduce() { do { var exploded = false var split = false findNextExplode()?.apply { explode() exploded = true } if (!exploded) findNextToSplit()?.apply { split() split = true } } while (exploded || split) } fun findValueToRight(): NumValue? { if (this is NumValue) return this if (this == parent?.left) return parent!!.right.findValueFurthestLeft() if (this == parent?.right) return parent!!.findValueToRight() return null } fun findValueToLeft(): NumValue? { if (this is NumValue) return this if (this == parent?.left) return parent!!.findValueToLeft() if (this == parent?.right) return parent!!.left.findValueFurthestRight() return null } private fun findValueFurthestLeft(): NumValue? = when(this) { is NumValue -> this is NumPair -> this.left.findValueFurthestLeft() } private fun findValueFurthestRight(): NumValue? = when(this) { is NumValue -> this is NumPair -> this.right.findValueFurthestRight() } private fun findNextToSplit(): NumValue? = if (this is NumValue && canSplit()) this else if (this is NumPair) left.findNextToSplit() ?: right.findNextToSplit() else null private fun findNextExplode(depth: Int = 0): NumPair? = if (this is NumPair) { if (depth >= 4) this else left.findNextExplode(depth + 1) ?: right.findNextExplode(depth + 1) } else null } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day18$Num.class", "javap": "Compiled from \"day18.kt\"\npublic abstract class Day18$Num {\n private Day18$Num$NumPair parent;\n\n private Day18$Num();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\...
Ad0lphus__AOC2021__02f219e/day09/Kotlin/day09.kt
import java.io.* fun print_day_9() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 9" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Smoke Basin -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_9() Day9().part_1() Day9().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day9 { data class Point(val x:Int, val y:Int) { fun neighbours(xBoundary: Int, yBoundary: Int): List<Point> = listOf(Point(x-1, y), Point(x+1, y), Point(x, y-1), Point(x, y+1) ).filter { it.x in 0 until xBoundary && it.y in 0 until yBoundary } } val heightmap = File("../Input/day9.txt").readLines().map { it.toCharArray().map { c -> c.digitToInt() } } fun part_1() { val total = heightmap.foldIndexed(0) { yIndex, acc, list -> list.foldIndexed(acc) { xIndex, sum, height -> if (Point(xIndex, yIndex).neighbours(heightmap[0].size, heightmap.size).count { heightmap[it.y][it.x] <= height } == 0) sum + heightmap[yIndex][xIndex] + 1 else sum } } println("Puzzle 1: $total") } fun part_2() { fun getLowPoints() = heightmap.flatMapIndexed { yIndex, list -> list.mapIndexed { xIndex, height -> val smallerNeighbours = Point(xIndex, yIndex).neighbours(heightmap[0].size, heightmap.size).count { heightmap[it.y][it.x] <= height } if (smallerNeighbours == 0) Point(xIndex, yIndex) else null }.filterNotNull() } fun getBasinSize(p: Point): Int { val visited = mutableSetOf(p) val queue = mutableListOf(p) while (queue.isNotEmpty()) { val newNeighbors = queue.removeFirst() .neighbours(heightmap[0].size, heightmap.size) .filter { it !in visited } .filter { heightmap[it.y][it.x] != 9 } visited.addAll(newNeighbors) queue.addAll(newNeighbors) } return visited.size } val answer = getLowPoints().map { getBasinSize(it) } .sortedDescending() .take(3) .reduce { total, next -> total * next } println("Puzzle 2: $answer") } }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day09Kt.class", "javap": "Compiled from \"day09.kt\"\npublic final class Day09Kt {\n public static final void print_day_9();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...
Ad0lphus__AOC2021__02f219e/day08/Kotlin/day08.kt
import java.io.* fun print_day_8() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 8" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Seven Segment Search -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_8() Day8().part_1() Day8().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day8 { private val lines = File("../Input/day8.txt").readLines().map { it.split("|")[0].trim() to it.split("|")[1].trim() } fun part_1() { val uniqueLengths = listOf(2, 3, 4, 7) var totalUnique = 0 for((_, output) in lines) { output.split(" ").forEach { if(it.length in uniqueLengths) totalUnique++ } } println("Puzzle 1: " + totalUnique) } fun part_2() { var total = 0 for((input, output) in lines) { val displays = mutableMapOf<String, Int>() val inputs = input.split(" ").map{ it.sortChars() } val one = inputs.first { it.length == 2 } val four = inputs.first { it.length == 4 } val seven = inputs.first { it.length == 3 } val eight = inputs.first { it.length == 7 } val nine = inputs.first { it.length == 6 && it.containsAll(four) } displays[one] = 1 displays[four] = 4 displays[seven] = 7 displays[eight] = 8 displays[nine] = 9 displays[inputs.first { it.length == 6 && it.containsAll(seven) && !it.containsAll(four) }] = 0 displays[inputs.first { it.length == 6 && !it.containsAll(one) }] = 6 displays[inputs.first { it.length == 5 && it.containsAll(one) }] = 3 displays[inputs.first { it.length == 5 && !it.containsAll(one) && nine.containsAll(it) }] = 5 displays[inputs.first { it.length == 5 && !it.containsAll(one) && !nine.containsAll(it) }] = 2 total += output.split(" ").fold("") { number, outputVal -> number + displays[outputVal.sortChars()].toString() }.toInt() } println("Puzzle 2: " + total) } private fun String.sortChars() = this.toCharArray().sorted().joinToString("") private fun String.containsAll(chars: String) = this.toList().containsAll(chars.toList()) }
[ { "class_path": "Ad0lphus__AOC2021__02f219e/Day08Kt.class", "javap": "Compiled from \"day08.kt\"\npublic final class Day08Kt {\n public static final void print_day_8();\n Code:\n 0: ldc #8 // String \\u001b[33m\n 2: astore_0\n 3: ldc #10 ...