kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
reactivedevelopment__aoc-2022-5__f9f78bc/src/main/kotlin/com/adventofcode/Day.kt
package com.adventofcode import com.adventofcode.Day.process import com.adventofcode.Day.solution import java.util.* object Day { private var script = false private val scheme = mutableListOf<String>() private val stackedColumns = mutableListOf<LinkedList<Char>>() fun process(line: String) { if (script) { return processCode(line) } if (line.isBlank()) { processScheme() script = true return } scheme.add(line) } private fun processScheme() { val columns = scheme.last().split(" ").last().trim().toInt() for (x in 0 until columns) { stackedColumns.add(LinkedList()) } for (line in scheme.dropLast(1).asReversed()) { line.windowed(3, 4).forEachIndexed { idx, crateEncoded -> if (crateEncoded.isNotBlank()) { check(crateEncoded.length == 3 && crateEncoded.first() == '[' && crateEncoded.last() == ']') val crate = crateEncoded[1] stackedColumns[idx].push(crate) } } } } private fun processCode(line: String) { val (crates, from, to) = line.split("move ", " from ", " to ").filterNot(String::isBlank).map(String::toInt) val fromColumn = stackedColumns[from - 1] val toColumn = stackedColumns[to - 1] if(crates == 1) { fromColumn.pop().let(toColumn::push) } else { val buffered = fromColumn.take(crates) for(x in buffered.asReversed()) { fromColumn.removeFirst() toColumn.push(x) } } } fun solution(): String { return stackedColumns.map(LinkedList<Char>::getFirst).joinToString("") } } fun main() { ::main.javaClass .getResourceAsStream("/input")!! .bufferedReader() .forEachLine(::process) println(solution()) }
[ { "class_path": "reactivedevelopment__aoc-2022-5__f9f78bc/com/adventofcode/DayKt$main$2.class", "javap": "Compiled from \"Day.kt\"\nfinal class com.adventofcode.DayKt$main$2 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<java.lang.String, kotlin.Unit> {\n com.ad...
rainer-gepardec__aoc2022__c920692/src/main/kotlin/aoc10/Solution10.kt
package aoc10 import java.nio.file.Paths fun main() { val lines = Paths.get("src/main/resources/aoc_10.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return solve(lines) .filter { it.first == 20 || ((it.first - 20) % 40) == 0 } .sumOf { it.first * it.second } } fun solution2(lines: List<String>): Int { val crt = Array(6) { CharArray(40) } for (row in 0 until 6) { for (column in 0 until 40) { crt[row][column] = '.' } } solve(lines) .forEach { val row = (it.first - 1) / 40 val column = (it.first - 1) % 40 if (IntRange(it.second - 1, it.second + 1).contains(column)) { crt[row][column] = '#' } } crt.forEach { println(it) } return 0 } fun solve(lines: List<String>): List<Pair<Int, Int>> { val cycles = mutableListOf<Pair<Int, Int>>() lines .map { if (it.startsWith("addx")) listOf("noop", it) else listOf(it) } .flatten() .map { it.split(" ").getOrElse(1) { "0" }.toInt() } .foldIndexed(1) { index, result, add -> cycles.add(Pair(index + 1, result)); result.plus(add) } return cycles }
[ { "class_path": "rainer-gepardec__aoc2022__c920692/aoc10/Solution10Kt.class", "javap": "Compiled from \"Solution10.kt\"\npublic final class aoc10.Solution10Kt {\n public static final void main();\n Code:\n 0: ldc #10 // String src/main/resources/aoc_10.txt\n 2: icon...
rainer-gepardec__aoc2022__c920692/src/main/kotlin/aoc03/Solution03.kt
package aoc03 import java.nio.file.Paths val valueMap = calculateValueMap(); fun calculateValueMap(): Map<Char, Int> { val tmpMap = mutableMapOf<Char, Int>() var c = 'a'; while (c <= 'z') { tmpMap[c] = c.code - 96; c++ } c = 'A' while (c <= 'Z') { tmpMap[c] = c.code - 38; c++ } return tmpMap; } fun main() { val lines = Paths.get("src/main/resources/aoc_03.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return lines.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2)) }.map { pair -> pair.first.toCharArray().first { pair.second.contains(it) } }.sumOf { valueMap[it]!! } } fun solution2(lines: List<String>): Int { return lines .windowed(3, 3) .map { group -> val charMap = mutableMapOf<Char, Int>() group.forEach { line -> line.toCharArray() .distinct() .forEach { charMap.computeIfPresent(it) { _, v -> v + 1 } charMap.putIfAbsent(it, 1) } } charMap.maxBy { it.value }.key }.sumOf { valueMap[it]!! } }
[ { "class_path": "rainer-gepardec__aoc2022__c920692/aoc03/Solution03Kt.class", "javap": "Compiled from \"Solution03.kt\"\npublic final class aoc03.Solution03Kt {\n private static final java.util.Map<java.lang.Character, java.lang.Integer> valueMap;\n\n public static final java.util.Map<java.lang.Character,...
rainer-gepardec__aoc2022__c920692/src/main/kotlin/aoc05/Solution05.kt
package aoc05 import java.nio.file.Paths /* [D] [N] [C] [Z] [M] [P] 1 2 3 [J] [Z] [G] [Z] [T] [S] [P] [R] [R] [Q] [V] [B] [G] [J] [W] [W] [N] [L] [V] [W] [C] [F] [Q] [T] [G] [C] [T] [T] [W] [H] [D] [W] [W] [H] [T] [R] [M] [B] [T] [G] [T] [R] [B] [P] [B] [G] [G] [S] [S] [B] [D] [F] [L] [Z] [N] [L] 1 2 3 4 5 6 7 8 9 */ fun createStorage(): Map<Int, ArrayDeque<String>> { val storage = mutableMapOf<Int, ArrayDeque<String>>() storage[1] = ArrayDeque(listOf("S", "T","H","F","W","R")) storage[2] = ArrayDeque(listOf("S", "G", "D","Q","W")) storage[3] = ArrayDeque(listOf("B","T","W")) storage[4] = ArrayDeque(listOf("D","R","W","T","N","Q","Z","J")) storage[5] = ArrayDeque(listOf("F","B","H","G","L","V","T","Z")) storage[6] = ArrayDeque(listOf("L","P","T","C","V","B","S","G")) storage[7] = ArrayDeque(listOf("Z","B","R","T","W","G","P")) storage[8] = ArrayDeque(listOf("N","G","M","T","C","J","R")) storage[9] = ArrayDeque(listOf("L","G","B","W")) return storage } fun main() { val lines = Paths.get("src/main/resources/aoc_05.txt").toFile().useLines { it.toList() } val operations = lines.map { it.split(" ") } .map { tokens -> tokens.map { token -> token.toIntOrNull() }.mapNotNull { it } } .map { Triple(it[0], it[1], it[2]) } println(solution1(createStorage(), operations)) println(solution2(createStorage(), operations)) } fun solution1(storage: Map<Int, ArrayDeque<String>>, operations: List<Triple<Int, Int, Int>>): String { operations.forEach { for (i in 0 until it.first) storage[it.third]!!.addLast(storage[it.second]!!.removeLast()) } return storage.map {it.value.removeLast() }.joinToString(separator = "") } fun solution2(storage: Map<Int, ArrayDeque<String>>, operations: List<Triple<Int, Int, Int>>): String { operations.forEach { movement -> val tmpDeque = ArrayDeque<String>(); for (i in 0 until movement.first) { tmpDeque.addFirst(storage[movement.second]!!.removeLast()); } tmpDeque.forEach { storage[movement.third]!!.addLast(it) } } return storage.map {it.value.removeLast() }.joinToString(separator = "") }
[ { "class_path": "rainer-gepardec__aoc2022__c920692/aoc05/Solution05Kt.class", "javap": "Compiled from \"Solution05.kt\"\npublic final class aoc05.Solution05Kt {\n public static final java.util.Map<java.lang.Integer, kotlin.collections.ArrayDeque<java.lang.String>> createStorage();\n Code:\n 0: new...
rainer-gepardec__aoc2022__c920692/src/main/kotlin/aoc07/Solution07.kt
package aoc07 import java.nio.file.Paths import kotlin.math.abs class Node(val parent: Node?, val name: String, val type: String, val size: Int = 0) { val children = mutableListOf<Node>() override fun toString(): String { return "$name ($type)" } } fun main() { val lines = Paths.get("src/main/resources/aoc_07.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return solve(lines).filter { it <= 100000 }.sum() } fun solution2(lines: List<String>): Int { val fileList = solve(lines) val maxSpace = 70000000 val installSpace = 30000000 val usedSpace = fileList.max() val freeSpace = maxSpace - usedSpace val requiredSpace = installSpace - freeSpace return fileList.filter { requiredSpace - it < 0 }.maxBy { requiredSpace - it } } fun solve(lines: List<String>): List<Int> { val shellLines = lines .filterNot { it.contains("$ ls") } .map { it.split(" ") } .map { if (it.size == 2) Pair(it[0], it[1]) else Pair(it[1], it[2]) } val rootNode = Node(null, "/", "dir") var currentNode: Node? = null for (shellLine in shellLines) { if (shellLine.first == "cd") { currentNode = if (shellLine.second == "..") { currentNode?.parent } else { if (currentNode == null) { rootNode } else { currentNode.children.add(Node(currentNode, currentNode.name + "/" + shellLine.second, "dir")) currentNode.children.last() } } } else if (shellLine.first.toIntOrNull() !== null) { currentNode?.children?.add(Node(currentNode, shellLine.second, "file", shellLine.first.toInt())) } } val sizeMap = mutableMapOf<String, Int>() calculate(rootNode, sizeMap) return sizeMap.toList().map { it.second }.sortedDescending() } fun calculate(node: Node, sizeMap: MutableMap<String, Int>): Int { return if (node.type == "dir") { val size = node.children.filter { it.type == "dir" }.sumOf { calculate(it, sizeMap) } + calcFileSize(node) sizeMap[node.name] = size; size } else { calcFileSize(node) } } fun calcFileSize(node: Node): Int { return node.children.filter { it.type == "file" }.sumOf { it.size } }
[ { "class_path": "rainer-gepardec__aoc2022__c920692/aoc07/Solution07Kt.class", "javap": "Compiled from \"Solution07.kt\"\npublic final class aoc07.Solution07Kt {\n public static final void main();\n Code:\n 0: ldc #10 // String src/main/resources/aoc_07.txt\n 2: icon...
rainer-gepardec__aoc2022__c920692/src/main/kotlin/aoc08/Solution08.kt
package aoc08 import java.nio.file.Paths inline fun <T> Iterable<T>.takeWhileInclusive( predicate: (T) -> Boolean ): List<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = predicate(it) result } } fun main() { val lines = Paths.get("src/main/resources/aoc_08.txt").toFile().useLines { it.toList() } val map = lines .map { line -> line.toCharArray().map { it.digitToInt() } } .map { it.toIntArray() } .toTypedArray() val width = map.first().size val height = map.size println(solution1(map, width, height)) println(solution2(map, width, height)) } fun solution1(map: Array<IntArray>, width: Int, height: Int): Int { val treeMap = solve(map, width, height) return treeMap.asSequence().filter { tree -> tree.value.any { edge -> edge.all { it < map[tree.key.second][tree.key.first] } } }.count() + (width * 2) + (height * 2) - 4 } fun solution2(map: Array<IntArray>, width: Int, height: Int): Int { val treeMap = solve(map, width, height) return treeMap.asSequence().map { tree -> tree.value.map { edge -> edge.takeWhileInclusive { map[tree.key.second][tree.key.first] > it }.toList() }.map { it.size } }.maxOf { it.reduce { result, value -> result.times(value) } } } fun solve(map: Array<IntArray>, width: Int, height: Int): Map<Pair<Int, Int>, List<List<Int>>> { val treeMap = mutableMapOf<Pair<Int, Int>, List<List<Int>>>() // create map of path to edge for all trees except the outer circle for (y in 1 until height - 1) { for (x in 1 until width - 1) { val leftEdgeValues = mutableListOf<Int>() val rightEdgeValues = mutableListOf<Int>() val topEdgeValues = mutableListOf<Int>() val bottomEdgeValues = mutableListOf<Int>() for (l in 0 until x) leftEdgeValues.add(map[y][l]) for (r in x + 1 until width) rightEdgeValues.add(map[y][r]) for (t in 0 until y) topEdgeValues.add(map[t][x]) for (b in y + 1 until height) bottomEdgeValues.add(map[b][x]) treeMap[Pair(x, y)] = listOf(leftEdgeValues.reversed(), rightEdgeValues, topEdgeValues.reversed(), bottomEdgeValues) } } return treeMap }
[ { "class_path": "rainer-gepardec__aoc2022__c920692/aoc08/Solution08Kt.class", "javap": "Compiled from \"Solution08.kt\"\npublic final class aoc08.Solution08Kt {\n public static final <T> java.util.List<T> takeWhileInclusive(java.lang.Iterable<? extends T>, kotlin.jvm.functions.Function1<? super T, java.lan...
chskela__adventofcode-2022-kotlin__951d38a/src/day01/Day01.kt
package day01 import java.io.File import java.util.PriorityQueue fun main() { fun parseInput(input: String) = input.split("\n\n").map { str -> str.lines().map { it.toInt() } } fun List<List<Int>>.topNElves(n: Int): Int { val best = PriorityQueue<Int>() for (calories in map { it.sum() }) { best.add(calories) if (best.size > n) { best.poll() } } return best.sum() } fun part1(input: String): Int { val data = parseInput(input) return data.topNElves(1) } fun part2(input: String): Int { val data = parseInput(input) return data.topNElves(3) } // test if implementation meets criteria from the description, like: val testInput = File("src/day01//Day01_test.txt").readText() check(part1(testInput) == 24000) println(part1(testInput)) println(part2(testInput)) val input = File("src/day01/Day01.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "chskela__adventofcode-2022-kotlin__951d38a/day01/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class day01.Day01Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
chskela__adventofcode-2022-kotlin__951d38a/src/day04/Day04.kt
package day04 import java.io.File fun main() { fun parseInput(input: String) = input .lines() .map { it.split(",") .map { s -> s.split("-") } .map { (a, b) -> (a.toInt()..b.toInt()).toSet() } } fun part1(input: String): Int { val data = parseInput(input).fold(0) { acc: Int, (l1, l2) -> acc + if (l1.union(l2).size == l1.size || l2.union(l1).size == l2.size) 1 else 0 } return data } fun part2(input: String): Int { val data = parseInput(input).fold(0) { acc: Int, (l1, l2) -> acc + if (l1.intersect(l2).isNotEmpty()) 1 else 0 } return data } val testInput = File("src/day04/Day04_test.txt").readText() println(part1(testInput)) println(part2(testInput)) val input = File("src/day04/Day04.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "chskela__adventofcode-2022-kotlin__951d38a/day04/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
chskela__adventofcode-2022-kotlin__951d38a/src/day03/Day03.kt
package day03 import java.io.File fun main() { fun Char.getPriorities(): Int = when { isLowerCase() -> code - 96 isUpperCase() -> code - 38 else -> 0 } fun parseInput(input: String) = input.lines() fun part1(input: String): Int { val data = parseInput(input) .map { it.take(it.length / 2).toSet() to it.takeLast(it.length / 2).toSet() } .sumOf { (first, second) -> first.fold(0) { acc: Int, c -> acc + if (second.contains(c)) c.getPriorities() else 0 } } return data } fun part2(input: String): Int { val data = parseInput(input).chunked(3) .map { it.map { s -> s.toSet() } } .map { (a, b, c) -> Triple(a, b, c) } .sumOf { (a, b, c) -> a.fold(0) { acc: Int, char: Char -> acc + if (b.contains(char) && c.contains(char)) char.getPriorities() else 0 } } return data } val testInput = File("src/day03/Day03_test.txt").readText() println(part1(testInput)) println(part2(testInput)) val input = File("src/day03/Day03.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "chskela__adventofcode-2022-kotlin__951d38a/day03/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class day03.Day03Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
chskela__adventofcode-2022-kotlin__951d38a/src/day02/Day02.kt
package day02 import java.io.File fun main() { fun parseInput(input: String) = input.lines().map { it.split(" ") }.map { it.first() to it.last() } val points = mapOf("X" to 1, "Y" to 2, "Z" to 3) val winsPlayer = listOf("A" to "Y", "B" to "Z", "C" to "X") val drawPlayer = listOf("A" to "X", "B" to "Y", "C" to "Z") val lossPlayer = listOf("A" to "Z", "B" to "X", "C" to "Y") fun getPointPerRound(pair: Pair<String, String>): Int = when (pair) { in winsPlayer -> 6 in drawPlayer -> 3 else -> 0 } fun part1(input: String): Int { val data = parseInput(input) .fold(0) { acc, pair -> acc + getPointPerRound(pair) + points.getOrDefault(pair.second, 0) } return data } fun part2(input: String): Int { val data = parseInput(input) .map { (first, second) -> when (second) { "Z" -> winsPlayer.first { it.first == first } "Y" -> drawPlayer.first { it.first == first } else -> lossPlayer.first { it.first == first } } } .fold(0) { acc, pair -> acc + getPointPerRound(pair) + points.getOrDefault(pair.second, 0) } return data } val testInput = File("src/day02/Day02_test.txt").readText() println(part1(testInput)) println(part2(testInput)) val input = File("src/day02/Day02.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "chskela__adventofcode-2022-kotlin__951d38a/day02/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class day02.Day02Kt {\n public static final void main();\n Code:\n 0: iconst_3\n 1: anewarray #8 // class kotlin/Pair\n 4: astore_1\...
chskela__adventofcode-2022-kotlin__951d38a/src/day05/Day05.kt
package day05 import java.io.File class Stack<T> { private val mutableList = mutableListOf<T>() fun push(vararg element: T) { mutableList.addAll(element) } fun pop(): T? { return if (mutableList.isNotEmpty()) { mutableList.removeLast() } else { null } } fun pop(n: Int): List<T> { val result = mutableListOf<T>() result.addAll(mutableList.takeLast(n)) repeat(n) { mutableList.removeLast() } return result } override fun toString(): String { return mutableList.toString() } } fun main() { fun <A, B, R, T> Pair<A, B>.map(transformA: (A) -> R, transformB: (B) -> T): Pair<R, T> { return Pair( transformA(first), transformB(second) ) } fun parseMovements(s: String) = s .lines() .map { row -> row.split(" ") .filter { it.toIntOrNull() != null } .map { it.toInt() } } fun parseStore(s: String) = s.lines().reversed() .foldIndexed(mutableMapOf()) { index, acc: MutableMap<Int, Stack<Char>>, str -> str.forEachIndexed { idx, char -> if (index == 0 && char.isDigit()) { val i = char.digitToInt() acc[i] = Stack<Char>() } if (char.isLetter()) { val i = idx / 4 + 1 val stack = acc[i] stack?.let { st -> st.push(char) acc[i] = st } } } acc } fun parseInput(input: String) = input.split("\n\n") .foldIndexed("" to "") { index: Int, acc: Pair<String, String>, s: String -> if (index % 2 != 0) acc.copy(second = s) else acc.copy(first = s) }.map( transformA = ::parseStore, transformB = ::parseMovements ) fun part1(input: String): String { val (storeData, movedData) = parseInput(input) movedData.forEach { (move, from, to) -> (1..move).forEach { _ -> val el = storeData[from]?.pop() el?.let { storeData[to]?.push(it) } } } return storeData.values.map { it.pop() }.joinToString("") } fun part2(input: String): String { val (storeData, movedData) = parseInput(input) movedData.forEach { (move, from, to) -> val el = storeData[from]?.pop(move) el?.let { storeData[to]?.push(*it.toTypedArray()) } } return storeData.values.map { it.pop() }.joinToString("") } val testInput = File("src/day05/Day05_test.txt").readText() println(part1(testInput)) println(part2(testInput)) // val input = File("src/day05/Day05.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "chskela__adventofcode-2022-kotlin__951d38a/day05/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class day05.Day05Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
chriscoomber__manydice__88b4823/src/commonMain/kotlin/chriscoomber/manydice/Theory.kt
package chriscoomber.manydice /** * A probability is close enough to another one if it's within this threshold. */ const val PROBABILITY_FLOAT_THRESHOLD = 0.0000001f /** * A probability is a real number between 0 and 1 inclusive. Users of this type * should check it is within those bounds. */ typealias Probability = Float /** * Check whether a probability is "equal" to another one - or as close as is * possible with floats. */ fun Probability.equalsWithinThreshold(other: Probability): Boolean { return this > other - PROBABILITY_FLOAT_THRESHOLD || this < other + PROBABILITY_FLOAT_THRESHOLD } /** * Check that this function is a probability measure on the given space. I.e., check that * it is non-negative and sums to 1. * * Returns true if and only if it's a probability measure. */ fun <Outcome> ((Outcome) -> Probability).isProbabilityMeasure(space: Set<Outcome>): Boolean { val sum = space.fold(0f) { totalProb, outcome -> val probability = this.invoke(outcome) if (probability < 0f || probability > 1f) return false totalProb + probability } return sum.equalsWithinThreshold(1f) } fun <Outcome> ((Outcome) -> Probability).requireIsProbabilityMeasure(space: Set<Outcome>) = this.isProbabilityMeasure(space) || error("Not a probability measure.") /** * A sample space is a set of "outcomes" equipped with: * * - A sigma-algebra of "events", i.e. sets of outcomes. * This is a bit mathematically technical but in general not all * sets are necessarily "measurable". However, we will only be * dealing with finite spaces, so the sigma-algebra just contains * every possible subset of the space. We don't need to declare * this in code. * * - A probability measure which assigns an event to a * "probability", i.e. a real number between 0 and 1 inclusive. * The measure must satisfy some sensible properties such as: * - The measure of the empty event (no outcomes) is 0 * - The measure of the whole space (all outcomes) is 1 * - The measure of a disjoint union of events is equal to * the sum of the measures of the events. (Technical note: * this is only required for countable unions. However, this being * a computer and us being mortals bound by the restrictions * of time, I don't think we'll be calculating any infinite * unions anyway, countable or not.) */ interface SampleSpace<Outcome> { // TODO iterator instead of set? val space: Set<Outcome> fun measure(event: Set<Outcome>): Probability } /** * A random variable is a function from a sample space to some measurable space E */ interface RandomVariable<Outcome, E> { /** * The sample space that this random variable is defined on. */ val sampleSpace: SampleSpace<Outcome> /** * Evaluate the random variable at a particular outcome. */ fun evaluate(outcome: Outcome): E }
[ { "class_path": "chriscoomber__manydice__88b4823/chriscoomber/manydice/TheoryKt.class", "javap": "Compiled from \"Theory.kt\"\npublic final class chriscoomber.manydice.TheoryKt {\n public static final float PROBABILITY_FLOAT_THRESHOLD;\n\n public static final boolean equalsWithinThreshold(float, float);\n...
Maxwell6635__TicTacToe__62f8035/app/src/main/java/com/jackson/tictactoe/utils/MinMaxAlgorithm.kt
package com.jackson.tictactoe.utils object MinMaxAlgorithm { private var player = 'x' private var opponent = 'o' private fun isMovesLeft(board: Array<CharArray>): Boolean { for (i in 0..2) for (j in 0..2) if (board[i][j] == '_') return true return false } private fun evaluate(b: Array<CharArray>): Int { // Checking for Rows for X or O victory. for (row in 0..2) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2] ) { if (b[row][0] == player) return +10 else if (b[row][0] == opponent) return -10 } } for (col in 0..2) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col] ) { if (b[0][col] == player) return +10 else if (b[0][col] == opponent) return -10 } } if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == player) return +10 else if (b[0][0] == opponent) return -10 } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == player) return +10 else if (b[0][2] == opponent) return -10 } return 0 } private fun minimax( board: Array<CharArray>, depth: Int, isMax: Boolean ): Int { val score = evaluate(board) if (score == 10) return score if (score == -10) return score if (!isMovesLeft(board)) return 0 return if (isMax) { var best = -1000 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = player best = Math.max( best, minimax( board, depth + 1, !isMax ) ) board[i][j] = '_' } } } best } else { var best = 1000 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = opponent best = Math.min( best, minimax( board, depth + 1, !isMax ) ) // Undo the move board[i][j] = '_' } } } best } } @JvmStatic fun findBestMove(board: Array<CharArray>): Move { var bestVal = -1000 val bestMove = Move() bestMove.row = -1 bestMove.col = -1 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = player val moveVal = minimax(board, 0, false) board[i][j] = '_' if (moveVal > bestVal) { bestMove.row = i bestMove.col = j bestVal = moveVal } } } } return bestMove } class Move { @JvmField var row = 0 @JvmField var col = 0 } }
[ { "class_path": "Maxwell6635__TicTacToe__62f8035/com/jackson/tictactoe/utils/MinMaxAlgorithm.class", "javap": "Compiled from \"MinMaxAlgorithm.kt\"\npublic final class com.jackson.tictactoe.utils.MinMaxAlgorithm {\n public static final com.jackson.tictactoe.utils.MinMaxAlgorithm INSTANCE;\n\n private stat...
ljuns__Practise__365062b/app/src/main/java/com/itscoder/ljuns/practise/algorithm/InsertionSort.kt
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/5. * I am just a developer. * 插入排序 * 从第 2 个元素开始和前面的元素比较并排序 * 例如:1, 3, 2 * 1、第一次 for 循环:3 和 1 比较,不需要改变 * 2.1、第二次 for 循环:2 和 3 比较,调换位置变成 1, 2, 3,此时 j == 1 * 2.2、2 再和 1 比较,不需要改变,排序结束 */ class InsertionSort { fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) sort(arr) } private fun sort(arr: IntArray) { for (i in arr.indices) { var j = i // 判断 j > 0 有两层意义:1、第一个元素不用比较;2、后面的比较排序到第 1 个元素时停止 while (j > 0 && arr[j] < arr[j - 1]) { val temp = arr[j] arr[j] = arr[j - 1] arr[j - 1] = temp j -- } } for (i in arr) { println(i) } } }
[ { "class_path": "ljuns__Practise__365062b/com/itscoder/ljuns/practise/algorithm/InsertionSort.class", "javap": "Compiled from \"InsertionSort.kt\"\npublic final class com.itscoder.ljuns.practise.algorithm.InsertionSort {\n public com.itscoder.ljuns.practise.algorithm.InsertionSort();\n Code:\n 0: ...
ljuns__Practise__365062b/app/src/main/java/com/itscoder/ljuns/practise/algorithm/ShellSort.kt
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/9. * I am just a developer. * 希尔排序 */ fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) shellSort(arr) arr.forEach { println(it) } } /** * 3, 1, 1, 6, 2, 4, 19 * 1、gap = arr.size / 2,即分成 gap 组(偶数个元素是 gap 组,奇数个元素是 gap+1 组) * 2、每一组进行插入排序,插入排序就是后一个和前一个比较,后一个小就进入步骤 3 * 3、交换位置,交换位置后还需重新和前面的比较,因为交换位置后有可能比前面的还小 * 4、每次都是 gap /= 2 * 5、重复 1~4 */ fun shellSort(arr: IntArray) { var gap = arr.size / 2 // for(int gap = arr.size / 2; gap > 0; gap /= 2) for (i in (arr.size / 2) downTo 0 step gap) { for (i in (gap until arr.size).withIndex()) { var j = i.value while (j >= gap && arr[j] < arr[j - gap]) { // 交换位置 val temp = arr[j] arr[j] = arr[j - gap] arr[j - gap] = temp j -= gap } } // 每次都是 gap/2,叫做希尔增量 gap /= 2 } /*((arr.size / 2) downTo 0 step gap).forEach { item -> (gap until arr.size).forEachIndexed { key, index -> var j = index while (j >= gap && arr[j] < arr[j - gap]) { // 交换位置 val temp = arr[j] arr[j] = arr[j - gap] arr[j - gap] = temp j -= gap } } gap /= 2 }*/ }
[ { "class_path": "ljuns__Practise__365062b/com/itscoder/ljuns/practise/algorithm/ShellSortKt.class", "javap": "Compiled from \"ShellSort.kt\"\npublic final class com.itscoder.ljuns.practise.algorithm.ShellSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ...
ljuns__Practise__365062b/app/src/main/java/com/itscoder/ljuns/practise/algorithm/MergeSort.kt
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/8. * I am just a developer. * 归并排序 * 1、先将数组中间分割,直到无法分割 * 3, 1, 1, 6, 2, 4, 19 * 3, 1, 1, 6 * 3, 1 * 3 1 * 2、对最小的部分开始排序 1 3 1, 6 * 1 3 1 6 * 1 1 3 6 2, 4, 19 * 1 1 3 6 2, 4 19 * 1 1 3 6 2 4 * 1 1 2 3 4 6 19 * 1 1 2 3 4 6 19 * 3、合并上层的分割 */ fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) val temp = intArrayOf(0, 0, 0, 0, 0, 0, 0) mergeSort(arr, 0, arr.size - 1, temp) arr.forEach { println(it) } } fun mergeSort(arr: IntArray, left: Int, right: Int, temp: IntArray) { if (left < right) { val mid = (left + right) / 2 // 分割左边 mergeSort(arr, left, mid, temp) // 分割右边 mergeSort(arr, mid + 1, right, temp) // 合并排序 merge(arr, left, mid, right, temp) } } fun merge(arr: IntArray, left: Int, mid: Int, right: Int, temp: IntArray) { var l = left // 从右边的第一个开始 var r = mid + 1 var i = 0 while (l <= mid && r <= right) { if (arr[l] <= arr[r]) { // 将左边的元素给临时数组,并把左边指向下一个 temp[i++] = arr[l++] } else { // 将右边的元素给临时数组,并把右边指向下一个 temp[i++] = arr[r++] } } // 将左边剩余的元素放到临时数组 while (l <= mid) { temp[i++] = arr[l++] } // 将右边剩余的元素放到临时数组 while (r <= right) { temp[i++] = arr[r++] } // 此时的临时数组已经是个有序数组了 var left = left i = 0 // 将临时数组的元素复制到原数组,原数组的起始位置是合并前左半部分的第一个位置,即 left while (left <= right) { arr[left++] = temp[i++] } }
[ { "class_path": "ljuns__Practise__365062b/com/itscoder/ljuns/practise/algorithm/MergeSortKt.class", "javap": "Compiled from \"MergeSort.kt\"\npublic final class com.itscoder.ljuns.practise.algorithm.MergeSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ...
ljuns__Practise__365062b/app/src/main/java/com/itscoder/ljuns/practise/algorithm/HeadSort.kt
package com.itscoder.ljuns.practise.algorithm import java.util.Collections.swap /** * Created by ljuns at 2019/1/7. * I am just a developer. * 堆排序 * 大顶堆:根节点 >= 左子节点 && 根节点 >= 右子节点 * 小顶堆:根节点 <= 左子节点 && 根节点 <= 右子节点 * 1、升序构建大顶堆,降序构建小顶堆 * 2、交换根节点和最后一个子节点,此时的最后一个子节点不再参与排序 * 3、重复 1、2 */ fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) // val arr = intArrayOf(9,8,7,6,5,4,3,2,1) headSort(arr) for (i in arr) { println(i) } } fun headSort(arr: IntArray) { /** * 构造堆 */ // for(int i = arr.size/2 -1; i >= 0; i --) // start 是最后一个子节点不为空的节点 val start = arr.size / 2 - 1 for ((key, value) in (start downTo 0).withIndex()) { // println("key: $value, value: ${arr[value]}") headAdjust(arr, value, arr.size) } /** * 交换位置,再次调整为堆 */ for ((index, value) in (arr.size - 1 downTo 1).withIndex()) { // 交换根节点后最后一个子节点 swap(arr, 0, value) // 重新调整为大顶堆 // 为什么从 0 开始?因为交换了根节点和最后一个子节点,其他节点都不变,变得只是根节点,所以只需要看根节点 headAdjust(arr, 0, value) } } /** * 构建堆 */ fun headAdjust(arr: IntArray, i: Int, len: Int) { var temp = arr[i] var i = i // for (int j = 2 * i + 1; j < len; j = j * 2 + 1) // 2 * i + 1 表示左子节点,2 * i + 2 表示右子节点 var start = 2 * i + 1 while (start < len) { // 如果右子节点比左子节点大,用右子节点来比较 if (start + 1 < len && arr[start] < arr[start + 1]) { start++ } // 如果子节点比父节点大,调换位置 if (arr[start] > temp) { arr[i] = arr[start] i = start } else { //父节点比子节点都大,不需要调整 break } // start * 2 + 1:因为有可能子节点又不满足大顶堆了,需要再次调整 start = start * 2 + 1 arr[i] = temp } } /** * 交换根节点和最后一个子节点 */ fun swap(arr: IntArray, origin: Int, target: Int) { val temp = arr[origin] arr[origin] = arr[target] arr[target] = temp }
[ { "class_path": "ljuns__Practise__365062b/com/itscoder/ljuns/practise/algorithm/HeadSortKt.class", "javap": "Compiled from \"HeadSort.kt\"\npublic final class com.itscoder.ljuns.practise.algorithm.HeadSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc...
ljuns__Practise__365062b/app/src/main/java/com/itscoder/ljuns/practise/algorithm/QuickSort.kt
package com.itscoder.ljuns.practise.algorithm /** * Created by ljuns at 2019/1/5. * I am just a developer. * 快速排序 * 例如:3, 1, 1, 6, 2, 4, 19 * 1、定义 left 为最左边,right 为最右边; * 2、选定 left 位置的元素为 temp; * 3、用 temp 从最右边开始比较,大于等于 temp 就 right--,否则 right 位置的元素替换掉 left 的元素,并且 left++; * 4、用 temp 从 left 开始比较,小于等于 temp 就 left++,否则 left 位置的元素替换掉 right 的元素,并且 right--; * 5、此时以 temp 为中心分为两部分,左边的都比 temp 小,右边的都比 temp 大。 * 左边:left 仍为最左边,right 为 temp,右边:left 为 temp+1,right 为最右边;重复2~5,直到 left >= temp 的位置 */ //class QuickSort { fun main(args: Array<String>) { val arr = intArrayOf(3, 1, 1, 6, 2, 4, 19) quickSort(arr, 0, arr.size - 1) for (i in arr) { println(i) } } private fun quickSort(arr: IntArray, left: Int, right: Int) { if (left >= right || arr.size <= 1) return // val mid = partition(arr, left, right) val mid = partition2(arr, left, right) quickSort(arr, left, mid) quickSort(arr, mid + 1, right) } private fun partition2(arr: IntArray, left: Int, right: Int) : Int { var l = left + 1 var r = right val temp = arr[left] while (l <= r) { if (temp < arr[l] && temp > arr[r]) { val t = arr[l] arr[l] = arr[r] arr[r] = t l++ r-- } if (temp >= arr[l]) l++ if (temp <= arr[r]) r-- } arr[left] = arr[r] arr[r] = temp return r } private fun partition(arr: IntArray, left: Int, right: Int) : Int { var left = left var right = right val temp = arr[left] while (left < right) { // 比较右边 while (temp <= arr[right] && left < right) { -- right } // 右边的比 temp 小,需要把 right 放在 left 的位置,并且 left 从下一个位置开始 if (left < right) { arr[left] = arr[right] left ++ } // 比较左边 while (temp >= arr[left] && left < right) { ++ left } // 左边的比 temp 大,需要把 left 放在 right 的位置,并且 right 从前一个位置开始 if (left < right) { arr[right] = arr[left] right -- } } // 此时 left == right arr[left] = temp return left } //}
[ { "class_path": "ljuns__Practise__365062b/com/itscoder/ljuns/practise/algorithm/QuickSortKt.class", "javap": "Compiled from \"QuickSort.kt\"\npublic final class com.itscoder.ljuns.practise.algorithm.QuickSortKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ...
JakubMifek__WFC-Kotlin__2e86233/src/commonMain/kotlin/org/mifek/wfc/utils/Formatters.kt
package org.mifek.wfc.utils /** * Format waves * * @param waves * @return */ fun formatWaves(waves: Array<BooleanArray>): String { return " " + waves.indices.joinToString(" ") { idx -> val s = waves[idx].sumBy { when (it) { true -> 1 else -> 0 } } val r = when (s) { 0 -> "[XX]" 1 -> "[" + (if (waves[idx].withIndex().find { it.value }!!.index < 10) "0" + waves[idx].withIndex() .find { it.value }!!.index.toString() else waves[idx].withIndex() .find { it.value }!!.index.toString()) + "]" else -> " " + (if (s < 10) " $s" else s.toString()) + " " } if ((idx + 1) % 10 == 0) (r + "\n") else r } } /** * Format patterns * * @param patterns * @return */ fun formatPatterns(patterns: Array<IntArray>): String { return patterns.mapIndexed { index, it -> "$index:\n${it.joinToString(" ")}" }.joinToString("\n\n") } /** * Format propagator * * @param propagator * @return */ fun formatPropagator(propagator: Array<Array<IntArray>>): String { val x = " " var result = propagator[0].indices.joinToString(" ") { x.subSequence(0, x.length - it.toString().length).toString() + it.toString() } + "\n" val template = "00" for (dir in propagator.indices) { result += propagator[dir].joinToString(" ") { when { it.isEmpty() -> "[X]" it.size > 1 -> "[?]" else -> template.slice( 0 until (3 - it[0].toString().length) ) + it[0].toString() } } + "\n" } return result } /** * Format neighbours * * @param propagator * @return */ fun formatNeighbours(propagator: Array<Array<IntArray>>): String { var ret = "" for (patternIndex in propagator[0].indices) { ret += "Pattern $patternIndex:\n" for (dir in propagator.indices) { ret += "\t${propagator[dir][patternIndex].joinToString(", ")}\n" } ret += "\n" } return ret }
[ { "class_path": "JakubMifek__WFC-Kotlin__2e86233/org/mifek/wfc/utils/FormattersKt.class", "javap": "Compiled from \"Formatters.kt\"\npublic final class org.mifek.wfc.utils.FormattersKt {\n public static final java.lang.String formatWaves(boolean[][]);\n Code:\n 0: aload_0\n 1: ldc ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week1/UnionFind.kt
package com.radix2.algorithms.week1 interface UF { fun union(p: Int, q: Int) fun connected(p: Int, q: Int): Boolean } class QuickFindUF(size: Int) : UF { private val ids: IntArray = IntArray(size) { it } override fun connected(p: Int, q: Int): Boolean = ids[p] == ids[q] override fun union(p: Int, q: Int) { val pId = ids[p] val qId = ids[q] for (i in 0 until ids.size) { if (ids[i] == pId) { ids[i] = qId } } } } open class QuickUnionUF(size: Int) : UF { protected val ids: IntArray = IntArray(size) { it } override fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) ids[pRoot] = qRoot } override fun connected(p: Int, q: Int): Boolean = root(p) == root(q) protected open fun root(p: Int): Int { var i = p while (i != ids[i]) { i = ids[i] } return i } } open class WeightedQuickUnionUF(size: Int) : QuickUnionUF(size) { protected val size: IntArray = IntArray(size) { 1 } override fun union(p: Int, q: Int) { val pRoot = root(p) val qRoot = root(q) if (pRoot == qRoot) return if (size[pRoot] < size[qRoot]) { ids[pRoot] = ids[qRoot] size[qRoot] += size[pRoot] } else { ids[qRoot] = ids[pRoot] size[pRoot] += size[qRoot] } } } class WeightedQuickUnionWithPathCompressionUF(size: Int) : WeightedQuickUnionUF(size) { override fun root(p: Int): Int { var i = p while (i != ids[i]) { ids[i] = ids[ids[i]] i = ids[i] } return i } } fun main(args: Array<String>) { val uf = WeightedQuickUnionWithPathCompressionUF(10) uf.union(4, 3) uf.union(3, 8) uf.union(6, 5) uf.union(9, 4) uf.union(2, 1) uf.union(5, 0) uf.union(7, 2) uf.union(6, 1) uf.union(7, 3) //println(uf.find(3)) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week1/UnionFindKt.class", "javap": "Compiled from \"UnionFind.kt\"\npublic final class com.radix2.algorithms.week1.UnionFindKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week2/Sorting.kt
package com.radix2.algorithms.week2 fun IntArray.selectionSort() { for (i in 0 until size) { var j = i var minIndex = j while (j < size) { if (this[minIndex] > this[j]) { minIndex = j } j++ } val temp = this[i] this[i] = this[minIndex] this[minIndex] = temp } } fun IntArray.insertionSort() { for (i in 0 until this.size) { var j = i while (j > 0) { if (this[j] < this[j - 1]) { val temp = this[j - 1] this[j - 1] = this[j] this[j] = temp } else { break } j-- } } } enum class Color(val id: Int) { BLUE(0), WHITE(1), RED(2); } data class Pebble(val color: Color) fun dutchNationalFlag(array: Array<Pebble>) { var left = 0 var mid = 0 var right = array.size - 1 fun swap(i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } while (mid <= right) { when { array[mid].color == Color.BLUE -> swap(left++, mid++) array[mid].color === Color.RED -> swap(mid, right--) array[mid].color == Color.WHITE -> mid++ } } } fun main(args: Array<String>) { val array = arrayOf(Pebble(Color.WHITE), Pebble(Color.RED), Pebble(Color.BLUE), Pebble(Color.RED), Pebble(Color.WHITE), Pebble(Color.BLUE)) dutchNationalFlag(array) val str = array.joinToString { pebble -> pebble.color.toString() } println(str) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week2/SortingKt.class", "javap": "Compiled from \"Sorting.kt\"\npublic final class com.radix2.algorithms.week2.SortingKt {\n public static final void selectionSort(int[]);\n Code:\n 0: aload_0\n 1: ldc ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week5/LLRBTree.kt
package com.radix2.algorithms.week5 import com.radix2.algorithms.week4.SymbolTable import com.radix2.algorithms.week4.put import java.lang.StringBuilder import java.util.* class LLRBTree<K : Comparable<K>, V> : SymbolTable<K, V> { private var root: Node<K, V>? = null private enum class Color { RED, BLACK } private class Node<K, V>( var key: K, var value: V, var left: Node<K, V>? = null, var right: Node<K, V>? = null, var color: Color = Color.RED ) override fun put(key: K, value: V) { root = put(root, Node(key, value)) } override fun get(key: K): V? = get(root, key)?.value override fun min(): Pair<K, V>? = min(root)?.let { it.key to it.value } override fun max(): Pair<K, V>? = max(root)?.let { it.key to it.value } override fun floor(key: K): Pair<K, V>? = floor(root, key)?.let { it.key to it.value } override fun ceil(key: K): Pair<K, V>? = ceil(root, key)?.let { it.key to it.value } override fun toString(): String = levelOrder(root) private fun getNodesAtLevel(root: Node<K, V>?, level: Int, builder: StringBuilder) { if (root == null) return if (level == 1) { builder.append(root.key to root.value) } getNodesAtLevel(root.left, level - 1, builder) getNodesAtLevel(root.right, level - 1, builder) } private fun height(root: Node<K, V>?): Int { if (root == null) return 0 return 1 + kotlin.math.max(height(root.left), height(root.right)) } // M, E, R, C, L, P, X, A, H, S // M, E, R, C, L, P, X, A, H, S private fun levelOrder(root: Node<K, V>?): String { if (root == null) return "" val queue: Queue<Node<K, V>> = LinkedList() queue.add(root) return buildString { while (!queue.isEmpty()) { if (length > 0) append(", ") append(queue.peek().key) val node = queue.poll() if (node.left != null) queue.add(node.left) if (node.right != null) queue.add(node.right) } } } private fun levelOrder(root: Node<K, V>?, height: Int, builder: StringBuilder) { for (i in 1..height) { getNodesAtLevel(root, i, builder) } } private fun inOrder(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return inOrder(root.left, builder) builder.append(root.key to root.value) inOrder(root.right, builder) } private fun put(root: Node<K, V>?, node: Node<K, V>): Node<K, V>? { if (root == null) return node var trav = root val cmp = node.key.compareTo(trav.key) when { cmp < 0 -> trav.left = put(trav.left, node) cmp > 0 -> trav.right = put(trav.right, node) else -> trav.value = node.value } when { trav.right.isRed() && !trav.left.isRed() -> trav = rotateLeft(trav) trav.left.isRed() && trav.left?.left.isRed() -> trav = rotateRight(trav) trav.left.isRed() && trav.right.isRed() -> flipColors(trav) } return trav } private fun get(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp < 0 -> get(root.left, key) cmp > 0 -> get(root.right, key) else -> root } } private fun min(root: Node<K, V>?): Node<K, V>? { if (root?.left == null) return root return min(root.left) } private fun max(root: Node<K, V>?): Node<K, V>? { if (root?.right == null) return root return max(root.right) } private fun floor(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> floor(root.left, key) else -> floor(root.right, key) ?: root } } private fun ceil(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> ceil(root.left, key) ?: root else -> ceil(root.right, key) } } private fun Node<K, V>?.isRed() = (this?.color ?: Color.BLACK) == Color.RED private fun rotateLeft(node: Node<K, V>): Node<K, V>? { assert(node.isRed()) val trav = node val temp = node.right trav.right = temp?.left temp?.left = trav temp?.color = trav.color trav.color = Color.RED return temp } private fun rotateRight(node: Node<K, V>): Node<K, V>? { assert(node.isRed()) val trav = node val temp = node.left trav.left = temp?.right temp?.right = trav temp?.color = trav.color trav.color = Color.RED return temp } private fun flipColors(node: Node<K, V>) { assert(!node.isRed()) assert(node.left.isRed()) assert(node.right.isRed()) node.color = Color.RED node.left?.color = Color.BLACK node.right?.color = Color.BLACK } override fun deleteMin() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun rank(key: K): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun size(): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun deleteMax() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun delete(key: K) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } } fun main() { val rbt = LLRBTree<Char, String?>() rbt.put('S') rbt.put('E') rbt.put('A') rbt.put('R') rbt.put('C') rbt.put('H') rbt.put('X') rbt.put('M') rbt.put('P') rbt.put('L') println(rbt) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week5/LLRBTreeKt.class", "javap": "Compiled from \"LLRBTree.kt\"\npublic final class com.radix2.algorithms.week5.LLRBTreeKt {\n public static final void main();\n Code:\n 0: new #8 // ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week4/BST.kt
package com.radix2.algorithms.week4 import java.util.* interface SymbolTable<K : Comparable<K>, V> { fun put(key: K, value: V) fun get(key: K): V? fun min(): Pair<K, V>? fun max(): Pair<K, V>? fun floor(key: K): Pair<K, V>? fun ceil(key: K): Pair<K, V>? fun size(): Int fun rank(key: K): Int fun deleteMin() fun deleteMax() fun delete(key: K) override fun toString(): String } class BST<K : Comparable<K>, V> : SymbolTable<K, V> { private class Node<K : Any, V>( var key: K, var data: V, var left: Node<K, V>? = null, var right: Node<K, V>? = null, var count: Int = 1 ) { override fun toString(): String = (key to data).toString() } private var root: Node<K, V>? = null override fun put(key: K, value: V) { root = put(root, key, value) } override fun get(key: K): V? = get(root, key)?.data override fun min(): Pair<K, V>? = min(root)?.let { it.key to it.data } override fun max(): Pair<K, V>? = max(root)?.let { it.key to it.data } override fun floor(key: K): Pair<K, V>? = floor(root, key)?.let { it.key to it.data } override fun ceil(key: K): Pair<K, V>? = ceil(root, key)?.let { it.key to it.data } override fun size(): Int = root?.count ?: 0 override fun rank(key: K): Int = rank(root, key) override fun deleteMin() { deleteMin(root) } override fun deleteMax() { deleteMax(root) } override fun delete(key: K) { delete(root, key) } override fun toString(): String = buildString { levelOrder(root, this) //inOrderWithStack(root, this) //inOrderRecursive(root, this) } private fun put(root: Node<K, V>?, key: K, value: V): Node<K, V>? { if (root == null) return Node(key, value) val cmp = key.compareTo(root.key) when { cmp < 0 -> root.left = put(root.left, key, value) cmp > 0 -> root.right = put(root.right, key, value) else -> root.data = value } root.count = 1 + (root.left?.count ?: 0) + (root.right?.count ?: 0) return root } private fun get(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return root val cmp = key.compareTo(root.key) return when { cmp < 0 -> get(root.left, key) cmp > 0 -> get(root.right, key) else -> root } } private fun min(root: Node<K, V>?): Node<K, V>? { if (root?.left == null) return root return min(root.left) } private fun max(root: Node<K, V>?): Node<K, V>? { if (root?.right == null) return root return max(root.right) } private fun floor(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> floor(root.left, key) else -> floor(root.right, key) ?: root } } private fun ceil(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null val cmp = key.compareTo(root.key) return when { cmp == 0 -> root cmp < 0 -> ceil(root.left, key) ?: root else -> ceil(root.right, key) } } private fun rank(root: Node<K, V>?, key: K): Int { if (root == null) return 0 val cmp = key.compareTo(root.key) return when { cmp == 0 -> root.left?.count ?: 0 cmp < 0 -> rank(root.left, key) else -> 1 + (root.left?.count ?: 0) + rank(root.right, key) } } private fun deleteMin(root: Node<K, V>?): Node<K, V>? { if (root?.left == null) return root?.right root.left = deleteMin(root.left) root.count = 1 + (root.left?.count ?: 0) + (root.right?.count ?: 0) return root } private fun deleteMax(root: Node<K, V>?): Node<K, V>? { if (root?.right == null) return root?.left root.right = deleteMax(root.right) root.count = 1 + (root.right?.count ?: 0) + (root.left?.count ?: 0) return root } private fun delete(root: Node<K, V>?, key: K): Node<K, V>? { if (root == null) return null var trav = root val cmp = key.compareTo(trav.key) when { cmp < 0 -> trav.left = delete(trav.left, key) cmp > 0 -> trav.right = delete(trav.right, key) else -> { if (trav.left == null) return trav.right if (trav.right == null) return trav.left val temp = trav trav = min(temp.right) trav?.right = deleteMin(temp.right) trav?.left = temp.left } } trav?.count = 1 + (trav?.left?.count ?: 0) + (trav?.right?.count ?: 0) return trav } private fun inOrderRecursive(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return inOrderRecursive(root.left, builder) builder.append(root.key to root.data) inOrderRecursive(root.right, builder) } private fun inOrderWithStack(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return var trav = root val stack = Stack<Node<K, V>>() while (trav != null || !stack.isEmpty()) { while (trav != null) { stack.push(trav) trav = trav.left } val top = stack.pop() builder.append(top.key to top.data) trav = top.right } } private fun levelOrder(root: Node<K, V>?, builder: StringBuilder) { if (root == null) return val queue: Queue<Node<K, V>> = LinkedList() queue.add(root) with(queue) { while (!queue.isEmpty()) { if (builder.isNotEmpty()) { builder.append(", ") } builder.append(peek()) val front = queue.poll() if (front.left != null) { add(front.left) } if (front.right != null) { add(front.right) } } } } } fun <K : Comparable<K>, V> SymbolTable<K, V?>.put(key: K) = this.put(key, null) fun main() { val st: SymbolTable<Int, String?> = BST() st.put(6) st.put(7) st.put(4) st.put(1) println(st) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week4/BST$Node.class", "javap": "Compiled from \"BST.kt\"\nfinal class com.radix2.algorithms.week4.BST$Node<K, V> {\n private K key;\n\n private V data;\n\n private com.radix2.algorithms.week4.BST$Node<K, V> left;\n\n ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week4/MaxPQ.kt
package com.radix2.algorithms.week4 class MaxPQ<T : Comparable<T>>(capacity: Int) { private var array = Array<Comparable<Any>?>(capacity) { null } private var n = 0 companion object { @Suppress("UNCHECKED_CAST") fun <T : Comparable<T>> sort(array: Array<Comparable<T>>) { for (i in array.lastIndex / 2 downTo 0) { sink(array as Array<Comparable<Any>>, i, array.lastIndex) } var n = array.lastIndex while (n > 0) { exch(array as Array<Comparable<Any>>, 0, n) sink(array as Array<Comparable<Any>>, 0, n--) } } private fun sink(array: Array<Comparable<Any>>, k: Int, n: Int) { var trav = k while (2 * trav + 1 < n) { var j = 2 * trav + 1 if (j < n - 1 && less(array, j, j + 1)) j++ if (!less(array, trav, j)) break exch(array, trav, j) trav = j } } private fun swim(array: Array<Comparable<Any>>, k: Int) { var trav = k while (trav > 0 && less(array,trav / 2, trav)) { exch(array, trav, trav / 2) trav /= 2 } } private fun exch(array: Array<Comparable<Any>>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } private fun less(array: Array<Comparable<Any>>, lhs: Int, rhs: Int): Boolean = array[lhs] < array[rhs] } @Suppress("UNCHECKED_CAST") fun add(t: T) { array[n++] = t as Comparable<Any> swim(array as Array<Comparable<Any>>, n - 1) } @Suppress("UNCHECKED_CAST") fun deleteMax(): T { val key = array[0] exch(array as Array<Comparable<Any>>,0, --n) sink(array as Array<Comparable<Any>>,0, n) array[n] = null return key as T } fun size() = n override fun toString(): String = array.filter { it != null }.joinToString() } fun main(args: Array<String>) { val maxPQ = MaxPQ<Int>(20) val list = mutableListOf(9, 2, 3, 8, 1, 10, 6, 17, 5, 16, 18, 12, 14, 11, 15, 20, 7, 4, 19, 13) for (i in 0 until 20) { maxPQ.add(list[i]) } println(maxPQ) val array: Array<Comparable<Int>> = list.toTypedArray() MaxPQ.sort(array) println(array.joinToString()) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week4/MaxPQ$Companion.class", "javap": "Compiled from \"MaxPQ.kt\"\npublic final class com.radix2.algorithms.week4.MaxPQ$Companion {\n private com.radix2.algorithms.week4.MaxPQ$Companion();\n Code:\n 0: aload_0\...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/SortingLinkedList.kt
package com.radix2.algorithms.week3 import kotlin.random.Random class LinkedList<T : Comparable<T>> { private var head: Node<T>? = null private val toss = intArrayOf(-1, 1) fun add(data: T) { val n = Node(data) n.next = head head = n } fun reverse() { var trav = head var prev: Node<T>? = null while (trav != null) { val temp = trav trav = trav.next temp.next = prev prev = temp } head = prev } fun reverseRecurrsive() { fun reverse(head: Node<T>?, prev: Node<T>?): Node<T>? { if (head == null) return prev val temp = head.next head.next = prev return reverse(temp, head) } head = reverse(head, null) } fun sort() { head = sort(head) } fun shuffle() { head = sort(head) { _, _ -> val index = Math.abs(Random.nextInt()) % 2 toss[index] } } override fun toString() = buildString { var trav = head while (trav != null) { if (length > 0) append(", ") append(trav.data) trav = trav.next } } private fun sort( head: Node<T>?, comparator: (lhs: T, rhs: T) -> Int = { lhs, rhs -> lhs.compareTo(rhs) } ): Node<T>? { if (head?.next == null) return head val mid = getMiddleNode(head) val nextToMid = mid?.next mid?.next = null val left = sort(head) val right = sort(nextToMid) return merge(left, right, comparator) } private fun getMiddleNode(head: Node<T>?): Node<T>? { if (head == null) return null var slow = head var fast = head.next while (fast != null) { fast = fast.next if (fast != null) { fast = fast.next slow = slow?.next } } return slow } private fun merge(left: Node<T>?, right: Node<T>?, comparator: (lhs: T, rhs: T) -> Int): Node<T>? { if (left == null) return right if (right == null) return left val result: Node<T>? if (comparator(left.data, right.data) > 0) { result = right result.next = merge(left, right.next, comparator) } else { result = left result.next = merge(left.next, right, comparator) } return result } private class Node<E>(val data: E, var next: Node<E>? = null) } fun main(args: Array<String>) { val linkedList = LinkedList<Int>() for (i in 0..10) { linkedList.add(i) } linkedList.reverseRecurrsive() println(linkedList) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/SortingLinkedListKt.class", "javap": "Compiled from \"SortingLinkedList.kt\"\npublic final class com.radix2.algorithms.week3.SortingLinkedListKt {\n public static final void main(java.lang.String[]);\n Code:\n ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/CountingInversionsV1.kt
package com.radix2.algorithms.week3 fun sort(array: Array<Int>): Long { return sort(array, Array(array.size) { 0 }, 0, array.size - 1) } fun sort(array: Array<Int>, aux: Array<Int>, lo: Int, hi: Int): Long { if (lo >= hi) return 0 val mid = lo + (hi - lo) / 2 var inversions: Long inversions = sort(array, aux, lo, mid) inversions += sort(array, aux, mid + 1, hi) return inversions + merge(array, aux, lo, mid, hi) } fun merge(array: Array<Int>, aux: Array<Int>, lo: Int, mid: Int, hi: Int): Long { var i = lo var j = mid + 1 val nextToMid = j var k = lo var inversions = 0L while(i <= mid && j <= hi) { if (array[i] <= array[j]) { aux[k++] = array[i++] } else { aux[k++] = array[j++] inversions += nextToMid - i } } while(i <= mid) aux[k++] = array[i++] while(j <= hi) aux[k++] = array[j++] System.arraycopy(aux, lo, array, lo, (hi - lo) + 1) return inversions } fun main(args: Array<String>) { val array = arrayOf(7, 5, 3, 1) val inversions = sort(array) println(array.joinToString()) println(inversions) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/CountingInversionsV1Kt.class", "javap": "Compiled from \"CountingInversionsV1.kt\"\npublic final class com.radix2.algorithms.week3.CountingInversionsV1Kt {\n public static final long sort(java.lang.Integer[]);\n ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/TraditionalMergeSort.kt
package com.radix2.algorithms.week3 object TraditionalMergeSort { fun sort(array: IntArray) { val aux = IntArray(array.size) sort(array, aux, 0, array.size - 1) } fun sort(array: IntArray, aux: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val mid = lo + (hi - lo) / 2 sort(array, aux, lo, mid) sort(array, aux, mid + 1, hi) merge(array, aux, lo, mid, hi) } fun merge(array: IntArray, aux: IntArray, lo: Int, mid: Int, hi: Int) { System.arraycopy(array, lo, aux, lo, (hi - lo) + 1) var i = lo var j = mid + 1 for (k in lo..hi) { when { i > mid -> array[k] = aux[j++] j > hi -> array[k] = aux[i++] aux[i] > aux[j] -> { array[k] = aux[j++] } else -> array[k] = aux[i++] } } } } fun main(args: Array<String>) { val array = intArrayOf(6, 2, 1, 0, 13, 89, 72, 4, 22, 28) TraditionalMergeSort.sort(array) println(array.joinToString()) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/TraditionalMergeSortKt.class", "javap": "Compiled from \"TraditionalMergeSort.kt\"\npublic final class com.radix2.algorithms.week3.TraditionalMergeSortKt {\n public static final void main(java.lang.String[]);\n ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/HalfSizedAuxArray.kt
package com.radix2.algorithms.week3 // Merging with smaller auxiliary array. // Suppose that the sub array 𝚊[𝟶] to 𝚊[𝚗−𝟷] is sorted and the subarray 𝚊[𝚗] to 𝚊[𝟸 ∗ 𝚗 − 𝟷] is sorted. // How can you merge the two sub arrays so that 𝚊[𝟶] to 𝚊[𝟸 ∗ 𝚗−𝟷] is sorted using an auxiliary array of length n (instead of 2n)? fun mergeWithSmallerAux(array: IntArray, aux: IntArray = IntArray(array.size / 2), lo: Int, mid: Int, hi: Int) { System.arraycopy(array, lo, aux, lo, aux.size) var i = lo var j = mid + 1 var k = 0 while(i <= mid && j <= hi) { if (aux[i] > array[j]) { array[k++] = array[j++] } else { array[k++] = aux[i++] } } while(i <= mid) array[k++] = aux[i++] while(j <= hi) array[k++] = array[j++] } fun main(args: Array<String>) { val array = intArrayOf(1, 3, 5, 7, 9, 11, 0, 2, 4, 6, 8, 10) mergeWithSmallerAux(array, lo = 0, mid = (array.size - 1) / 2, hi = array.size - 1) println(array.joinToString()) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/HalfSizedAuxArrayKt.class", "javap": "Compiled from \"HalfSizedAuxArray.kt\"\npublic final class com.radix2.algorithms.week3.HalfSizedAuxArrayKt {\n public static final void mergeWithSmallerAux(int[], int[], int, i...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/CountingInversionsV2.kt
package com.radix2.algorithms.week3 import java.util.* // Counting inversions. An inversion in an array a[] is a pair of entries a[i] and a[j] such that i < j but a[i] > a[j]. // Given an array, design a linear arithmetic algorithm to count the number of inversions. fun sort(array: IntArray, aux: IntArray, lo: Int, hi: Int): Long { if (lo >= hi) return 0 val mid = lo + (hi - lo) / 2 var inversions: Long inversions = sort(array, aux, lo, mid) inversions += sort(array, aux, mid + 1, hi) return inversions + merge(array, aux, lo, mid, hi) } fun merge(array: IntArray, aux: IntArray, lo: Int, mid: Int, hi: Int): Long { System.arraycopy(array, lo, aux, lo, (hi - lo) + 1) var i = lo var j = mid + 1 val nextToMid = j var inversions = 0L for (k in lo..hi) { when { i > mid -> array[k] = aux[j++] j > hi -> array[k] = aux[i++] aux[i] > aux[j] -> { array[k] = aux[j++] inversions += nextToMid - i } else -> array[k] = aux[i++] } } return inversions } fun countInversions(array: IntArray): Long { return sort(array, IntArray(array.size), 0, array.size - 1) } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val t = scan.nextLine().trim().toInt() for (tItr in 1..t) { val n = scan.nextLine().trim().toInt() val arr = scan.nextLine().split(" ").map{ it.trim().toInt() }.toIntArray() val result = countInversions(arr) println(result) } }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/CountingInversionsV2Kt.class", "javap": "Compiled from \"CountingInversionsV2.kt\"\npublic final class com.radix2.algorithms.week3.CountingInversionsV2Kt {\n public static final long sort(int[], int[], int, int);\n...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/TraditionalQuickSort.kt
package com.radix2.algorithms.week3 import java.util.* fun less(lhs: Int, rhs: Int) = lhs < rhs fun exch(array: IntArray, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } fun shuffle(array: IntArray) { val rnd = Random() for (i in 1 until array.size) { val randomIndex = rnd.nextInt(i) exch(array, i, randomIndex) } } fun quickSort(array: IntArray) { shuffle(array) quickSort(array, 0, array.size - 1) } fun quickSort(array: IntArray, lo: Int, hi: Int) { if (hi <= lo) return val k = partition(array, lo, hi) quickSort(array, lo, k - 1) quickSort(array, k + 1, hi) } fun partition(array: IntArray, lo: Int, hi: Int): Int { val pivot = array[lo] var i = lo var j = hi + 1 while (true) { while (less(array[++i], pivot)) if (i == hi) break while (less(pivot, array[--j])) if (j == lo) break if (i >= j) break exch(array, i, j) } exch(array, lo, j) return j } // 0, 1, 2, 3, 4, 5, 6, 7, 9 fun main(args: Array<String>) { val array = intArrayOf(6, 10, 1, 3, 2, 6, 8, 9, 5, 15) quickSort(array) println(array.joinToString(", ")) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/TraditionalQuickSortKt.class", "javap": "Compiled from \"TraditionalQuickSort.kt\"\npublic final class com.radix2.algorithms.week3.TraditionalQuickSortKt {\n public static final boolean less(int, int);\n Code:\n...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/week3/NutsAndBolts.kt
package com.radix2.algorithms.week3 import java.util.* class NutsAndBolts { fun solve(nuts: IntArray, bolts: IntArray) { shuffle(nuts) shuffle(bolts) solve(nuts, bolts, 0, nuts.size - 1) } private fun solve(nuts: IntArray, bolts: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val pivot = partition(nuts, bolts[lo], lo, hi) partition(bolts, nuts[pivot], lo, hi) solve(nuts, bolts, lo, pivot - 1) solve(nuts, bolts, pivot + 1, hi) } private fun partition(array: IntArray, pivot: Int, lo: Int, hi: Int): Int { var i = lo var j = hi + 1 while (true) { while (array[++i] <= pivot) { if (i == hi) break if (array[i] == pivot) { exch(array, lo, i) i-- } } while (pivot <= array[--j]) { if (j == lo) break if (array[j] == pivot) { exch(array, lo, j) j++ } } if (i >= j) break exch(array, i, j) } exch(array, lo, j) return j } private fun exch(array: IntArray, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } private fun shuffle(array: IntArray) { val rnd = Random() for (i in 1 until array.size) { val randomIndex = rnd.nextInt(i) exch(array, i, randomIndex) } } } fun main(args: Array<String>) { val nuts = intArrayOf(5, 3, 7, 9, 2, 8, 4, 1, 6, 0, 10, 11, 12, 13, 14, 15, 16, 17) val bolts = intArrayOf(4, 7, 1, 6, 3, 0, 8, 9, 2, 5, 10, 11, 12, 13, 14, 15, 16, 17) NutsAndBolts().solve(nuts, bolts) println(""" Nuts : ${nuts.joinToString(separator = ", ")} Bolts : ${bolts.joinToString(separator = ", ")} """.trimIndent()) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/week3/NutsAndBoltsKt.class", "javap": "Compiled from \"NutsAndBolts.kt\"\npublic final class com.radix2.algorithms.week3.NutsAndBoltsKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/extras/MinAvg.kt
package com.radix2.algorithms.extras import java.util.* fun minimumAverage(orders: Sequence<Order>): Long { val arrivalTimes = PriorityQueue<Order> { o1, o2 -> o1.arrivalTime.compareTo(o2.arrivalTime) } val burstTimes = PriorityQueue<Order> { o1, o2 -> o1.burstTime.compareTo(o2.burstTime) } for (order in orders) { arrivalTimes.add(order) } var currentTime = 0L var totalWaitTime = 0L var numberOfOrdersServed = 0L fun processOrder(order: Order) { totalWaitTime += (currentTime - order.arrivalTime + order.burstTime) currentTime += order.burstTime numberOfOrdersServed++ } fun enqueueOrders() { while (!arrivalTimes.isEmpty() && arrivalTimes.peek().arrivalTime <= currentTime) { burstTimes.add(arrivalTimes.poll()) } } while (!arrivalTimes.isEmpty()) { var order = arrivalTimes.poll() currentTime = if (burstTimes.isEmpty()) order.arrivalTime else currentTime + order.arrivalTime processOrder(order) enqueueOrders() while (!burstTimes.isEmpty()) { order = burstTimes.poll() processOrder(order) enqueueOrders() } } return totalWaitTime / numberOfOrdersServed } data class Order(val arrivalTime: Long, val burstTime: Long) fun main(args: Array<String>) { val reader = System.`in`.bufferedReader() val n = reader.readLine().trim().toInt() val orders = Array<Order?>(n) { null } for (ordersRowItr in 0 until n) { val (arrivalTime, burstTime) = reader.readLine().split(" ").map { it.trim().toLong() } orders[ordersRowItr] = Order(arrivalTime, burstTime) } val result = minimumAverage(orders.asSequence().filterNotNull()) println(result) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/extras/MinAvgKt.class", "javap": "Compiled from \"MinAvg.kt\"\npublic final class com.radix2.algorithms.extras.MinAvgKt {\n public static final long minimumAverage(kotlin.sequences.Sequence<com.radix2.algorithms.extras.O...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/extras/Scribble.kt
package com.radix2.algorithms.extras import java.util.* fun print(array: IntArray, lo: Int, hi: Int) { if (lo == hi) { println(array[lo]) } else { println(array[lo]) print(array, lo + 1, hi) } } fun map(array: IntArray, lo: Int, hi: Int, transform: (Int) -> Int) { array[lo] = transform(lo) if (lo < hi) map(array, lo + 1, hi, transform) } fun fib(n: Int): Int { return if (n < 2) n else fib(n - 1) + fib(n - 2) } fun towerOfHanoi(num: Int, from: Char, to: Char, aux: Char) { if (num == 1) { println("$from -> $to") } else { towerOfHanoi(num - 1, from, aux, to) println("$from -> $to") towerOfHanoi(num - 1, aux, to, from) } } fun isPallindrom(str: String, lo: Int, hi: Int): Boolean { if (hi <= lo) return str[lo] == str[hi] return str[lo] == str[hi] && isPallindrom(str, lo + 1, hi - 1) } fun power(a: Int, b: Int): Int { if (b == 1) return a return a * power(a, b - 1) } fun reversePrint(str: String) { if (str.length == 1) print(str) else { print("${str.last()}") reversePrint(str.substring(0, str.lastIndex)) } } fun shiftBlankToRight(array: IntArray) { val list = array.sortedWith(kotlin.Comparator { o1, o2 -> when { o1 == ' '.toInt() -> 1 o2 == ' '.toInt() -> -1 else -> 0 } }) println(list.joinToString()) } fun main(args: Array<String>) { val array = intArrayOf('A'.toInt(), 'B'.toInt(), ' '.toInt(), 'C'.toInt(), ' '.toInt(), ' '.toInt(), 'D'.toInt()) shiftBlankToRight(array) println() }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/extras/ScribbleKt.class", "javap": "Compiled from \"Scribble.kt\"\npublic final class com.radix2.algorithms.extras.ScribbleKt {\n public static final void print(int[], int, int);\n Code:\n 0: aload_0\n 1: ...
rupeshsasne__coursera-algorithms-part1__341634c/classroom/src/main/kotlin/com/radix2/algorithms/extras/RunningMedian.kt
package com.radix2.algorithms.extras import java.util.PriorityQueue fun runningMedian(a: Array<Int>): Array<Double> { val minPQ = PriorityQueue<Int> { o1, o2 -> o2.compareTo(o1) } val maxPQ = PriorityQueue<Int>() val medians = Array(a.size) { 0.0 } for (i in 0..a.lastIndex) { add(a[i], minPQ, maxPQ) rebalance(minPQ, maxPQ) medians[i] = getMedian(minPQ, maxPQ) } return medians } fun getMedian(minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>): Double { val maxHeap = if (minPQ.size > maxPQ.size) minPQ else maxPQ val minHeap = if (minPQ.size > maxPQ.size) maxPQ else minPQ return if (maxHeap.size == minHeap.size) { (maxHeap.peek() + minHeap.peek()).toDouble() / 2 } else { maxHeap.peek().toDouble() } } fun rebalance(minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>) { val biggerHeap = if (minPQ.size > maxPQ.size) minPQ else maxPQ val smallerHeap = if (minPQ.size > maxPQ.size) maxPQ else minPQ if (biggerHeap.size - smallerHeap.size >= 2) { smallerHeap.add(biggerHeap.poll()) } } fun add(num: Int, minPQ: PriorityQueue<Int>, maxPQ: PriorityQueue<Int>) { if (minPQ.isEmpty() || num < minPQ.peek()) { minPQ.add(num) } else { maxPQ.add(num) } } fun main(args: Array<String>) { val reader = System.`in`.bufferedReader() val aCount = reader.readLine().trim().toInt() val a = Array(aCount) { 0 } for (aItr in 0 until aCount) { val aItem = reader.readLine().trim().toInt() a[aItr] = aItem } reader.close() val result = runningMedian(a) println(result.joinToString("\n")) }
[ { "class_path": "rupeshsasne__coursera-algorithms-part1__341634c/com/radix2/algorithms/extras/RunningMedianKt.class", "javap": "Compiled from \"RunningMedian.kt\"\npublic final class com.radix2.algorithms.extras.RunningMedianKt {\n public static final java.lang.Double[] runningMedian(java.lang.Integer[]);\...
Kanishk-Pandey__MyRoboticsCode__e5d6c96/src/main/kotlin/frc/kyberlib/math/Polynomial.kt
package frc.kyberlib.math import kotlin.math.pow import kotlin.math.sqrt /** * Representation and calculator of a polynomial */ class Polynomial( vararg val coeffs: Double, private val variableName: Char = 'x' ) { companion object { fun regress(args: DoubleArray, outputs: DoubleArray, order: Int = 1): Polynomial { var n = order val datasetSize = args.size val X = DoubleArray(2 * n + 1) for (i in 0 until 2 * n + 1) { X[i] = 0.0 for (j in 0 until datasetSize) X[i] = X[i] + args[j].pow(i.toDouble()) //consecutive positions of the array will store N,sigma(xi),sigma(xi^2),sigma(xi^3)....sigma(xi^2n) } val B = Array(n + 1) { DoubleArray(n + 2) } val a = DoubleArray(n + 1) //B is the Normal matrix(augmented) that will store the equations, 'a' is for value of the final coefficients for (i in 0..n) for (j in 0..n) B[i][j] = X[i + j] //Build the Normal matrix by storing the corresponding coefficients at the right positions except the last column of the matrix val Y = DoubleArray(n + 1) //Array to store the values of sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi) for (i in 0 until n + 1) { Y[i] = 0.0 for (j in 0 until datasetSize) Y[i] = Y[i] + args[j].pow(i.toDouble()) * outputs[j] //consecutive positions will store sigma(yi),sigma(xi*yi),sigma(xi^2*yi)...sigma(xi^n*yi) } for (i in 0..n) B[i][n + 1] = Y[i] //load the values of Y as the last column of B(Normal Matrix but augmented) n += 1 for (i in 0 until n) //From now Gaussian Elimination starts(can be ignored) to solve the set of linear equations (Pivotisation) for (k in i + 1 until n) if (B[i][i] < B[k][i]) for (j in 0..n) { val temp = B[i][j] B[i][j] = B[k][j] B[k][j] = temp } for (i in 0 until n - 1) //loop to perform the gauss elimination for (k in i + 1 until n) { val t = B[k][i] / B[i][i] for (j in 0..n) B[k][j] = B[k][j] - t * B[i][j] //make the elements below the pivot elements equal to zero or elimnate the variables } for (i in n - 1 downTo 0) //back-substitution { //args is an array whose values correspond to the values of args,outputs,z.. a[i] = B[i][n] //make the variable to be calculated equal to the rhs of the last equation for (j in 0 until n) if (j != i) //then subtract all the lhs values except the coefficient of the variable whose value is being calculated a[i] = a[i] - B[i][j] * a[j] a[i] = a[i] / B[i][i] //now finally divide the rhs by the coefficient of the variable to be calculated } a.reverse() return Polynomial(*a) } } val degree = coeffs.size /** * Solve the polynomial for the given value */ fun eval(x: Double): Double { var total = 0.0 for (i in coeffs.indices) { total += coeffs[i] * x.pow(coeffs.size - i - 1) } return total } operator fun get(x: Double) = eval(x) fun r(data: DoubleArray, actualResults: DoubleArray): Double { val n = data.size return (n * (data.zip(actualResults).sumOf { it.first * it.second }) - data.sum() * actualResults.sum()) / sqrt(n * (data.sumOf { it * it } - data.sum())) / n * (actualResults.sumOf { it * it } - actualResults.sum()) } override fun toString(): String { var s = "" for (i in coeffs.indices) { s += "${coeffs[i]}$variableName^${coeffs.size - i - 1}" if (i < coeffs.size - 1 && coeffs[i + 1] >= 0.0) s += "+" } return s } }
[ { "class_path": "Kanishk-Pandey__MyRoboticsCode__e5d6c96/frc/kyberlib/math/Polynomial.class", "javap": "Compiled from \"Polynomial.kt\"\npublic final class frc.kyberlib.math.Polynomial {\n public static final frc.kyberlib.math.Polynomial$Companion Companion;\n\n private final double[] coeffs;\n\n private...
DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/src/main/kotlin/structures/GraphWithWeights.kt
package structures /** * * data structure: directed graph with weights * * description: made up of vertices connected by edges that have direction and weight * */ class GraphWithWeights<T> { private val data = linkedMapOf<Vertex<T>, MutableList<VertexConnection<T>>>() /** * adds a new vertex with a value [value] */ fun addVertex(value: T) = data.putIfAbsent(Vertex(value), mutableListOf()) /** * removes a vertex by value [value] from a graph */ fun removeVertex(value: T) { val removingVertex = Vertex(value) data.values.forEach { list -> list.removeIf { it.vertex == removingVertex } } data.remove(removingVertex) } /** * adds an edge between two vertices, that have values [value1], [value2] */ fun addEdge(value1: T, value2: T, cost: Int) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.add(VertexConnection(vertex2, cost)) } /** * removes an edge between two vertices, that have values [value1], [value2] */ fun removeEdge(value1: T, value2: T) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.removeIf { it.vertex == vertex2 } } /** * returns the associated vertices and their weights with the given vertex value [value] */ fun connectedVertexesWithWeights(value: T) = data[Vertex(value)] ?: listOf() /** * implementation of Dijkstra's algorithm, returns pairs of a vertex and the minimum weight needed to get to that vertex (the starting vertex is the first added) */ fun dijkstraAlgorithm(): Map<Vertex<T>, Int> { val unvisitedVertexes = linkedMapOf<Vertex<T>, Int>() data.keys.forEach { vertex -> unvisitedVertexes[vertex] = Int.MAX_VALUE } val visitedVertexes = linkedMapOf<Vertex<T>, Int>() var minimumCost = 0 var currentVertex = unvisitedVertexes.keys.firstOrNull() ?: return visitedVertexes while(unvisitedVertexes.isNotEmpty()) { val neighbourVertexConnections = data[currentVertex] ?: emptyList() for (neighbourVertexConnection in neighbourVertexConnections) { val neighbourVertex = neighbourVertexConnection.vertex if (!unvisitedVertexes.contains(neighbourVertex)) continue val newCost = minimumCost + neighbourVertexConnection.cost val neighbourVertexCost = unvisitedVertexes[neighbourVertex] ?: Int.MAX_VALUE if (neighbourVertexCost > newCost) { unvisitedVertexes[neighbourVertex] = newCost } } visitedVertexes[currentVertex] = minimumCost unvisitedVertexes.remove(currentVertex) val nextUnvisitedEntry = unvisitedVertexes.entries .filter { it.value != Int.MAX_VALUE } .minByOrNull { it.value } ?: return visitedVertexes currentVertex = nextUnvisitedEntry.key minimumCost = nextUnvisitedEntry.value } return visitedVertexes } } /** * helper class for defining graph weights */ data class VertexConnection<T>(val vertex: Vertex<T>, val cost: Int)
[ { "class_path": "DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/structures/GraphWithWeights.class", "javap": "Compiled from \"GraphWithWeights.kt\"\npublic final class structures.GraphWithWeights<T> {\n private final java.util.LinkedHashMap<structures.Vertex<T>, java.util.List<structures.Ve...
DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/src/main/kotlin/structures/Graph.kt
package structures import java.util.LinkedList import kotlin.collections.LinkedHashSet /** * * data structure: undirected graph without weights * * description: made up of vertices connected by edges * */ class Graph<T> { private val data = mutableMapOf<Vertex<T>, MutableList<Vertex<T>>>() /** * adds a new vertex with a value [value] */ fun addVertex(value: T) = data.putIfAbsent(Vertex(value), mutableListOf()) /** * removes a vertex by value [value] from a graph */ fun removeVertex(value: T) { val removingVertex = Vertex(value) data.values.forEach { list -> list.remove(removingVertex) } data.remove(removingVertex) } /** * adds an edge between two vertices, that have values [value1], [value2] */ fun addEdge(value1: T, value2: T) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.add(vertex2) data[vertex2]?.add(vertex1) } /** * removes an edge between two vertices, that have values [value1], [value2] */ fun removeEdge(value1: T, value2: T) { val vertex1 = Vertex(value1) val vertex2 = Vertex(value2) data[vertex1]?.remove(vertex2) data[vertex2]?.remove(vertex1) } /** * returns the associated vertices with the given vertex value [value] */ fun connectedVertexes(value: T) = data[Vertex(value)] ?: listOf() /** * traversal of the graph in depth, returns all vertices of the graph */ fun depthFirstTraversal() : List<Vertex<T>> { val visited = LinkedHashSet<Vertex<T>>() val queue = LinkedList<Vertex<T>>() val firstVertex = data.keys.firstOrNull() ?: return emptyList() queue.push(firstVertex) while (queue.isNotEmpty()) { val vertex = queue.poll() if (!visited.contains(vertex)) { visited.add(vertex) queue.addAll(data[vertex] ?: listOf()) } } return visited.toList() } /** * traversal of the graph in breadth, returns all vertices of the graph */ fun breadthFirstTraversal() : List<Vertex<T>> { val visited = LinkedHashSet<Vertex<T>>() val queue = LinkedList<Vertex<T>>() val firstVertex = data.keys.firstOrNull() ?: return emptyList() queue.add(firstVertex) visited.add(firstVertex) while (queue.isNotEmpty()) { val vertex = queue.poll() data[vertex]?.forEach { v -> if (!visited.contains(v)) { visited.add(v) queue.add(v) } } } return visited.toList() } } /** * graph vertex model */ data class Vertex<T>(val value: T)
[ { "class_path": "DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/structures/Graph.class", "javap": "Compiled from \"Graph.kt\"\npublic final class structures.Graph<T> {\n private final java.util.Map<structures.Vertex<T>, java.util.List<structures.Vertex<T>>> data;\n\n public structures.Grap...
DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/src/main/kotlin/structures/BinaryTree.kt
package structures /** * * data structure: binary tree * * description: consists of nodes, each of which has a maximum of two children, * child nodes satisfy the following requirements: * - the left child is less than the parent; * - right child is larger than parent; * * average search time: log(n) * worst search time: n * because the situation is possible when the elements follow each other 1,2,3,4... and the tree takes the following form: * 1 * \ * 2 * \ * 3 * \ * 4 * the same complexity is true for adding and removing nodes * */ class BinaryTree { /** * binary tree root */ private var root: Node? = null /** * adds a new element [value] to the tree */ fun add(value: Int) { fun addRec(current: Node?, value: Int) : Node { if (current == null) { return Node(value) } if (value < current.value()) { current.changeLeft(addRec(current.leftNode(), value)) } else if (value > current.value()) { current.changeRight(addRec(current.rightNode(), value)) } return current } root = addRec(root, value) } /** * checks the tree for emptiness and returns true if the tree does not contain any nodes */ fun isEmpty() = root == null /** * removes an element [value] from the tree */ fun remove(value: Int) { fun smallestValue(root: Node) : Int { return if (root.leftNode() == null) root.value() else smallestValue(root.leftNode()!!) } fun removeRec(current: Node?, value: Int) : Node? { if (current == null) { return null } if (value == current.value()) { if (current.leftNode() == null && current.rightNode() == null) { return null } if (current.leftNode() == null) { return current.rightNode() } if (current.rightNode() == null) { return current.leftNode() } val smallestValue = smallestValue(current.rightNode()!!) current.changeValue(smallestValue) current.changeRight(removeRec(current.rightNode(), smallestValue)) return current } if (value < current.value()) { current.changeLeft(removeRec(current.leftNode(), value)) } else { current.changeRight(removeRec(current.rightNode(), value)) } return current } root = removeRec(root, value) } /** * checks for the existence of an element [value] in the tree, returns true if the element exists */ fun contains(value: Int) : Boolean { fun containsRec(current: Node?, value: Int) : Boolean { if (current == null) { return false } if (value == current.value()) { return true } return if (value < current.value()) { containsRec(current.leftNode(), value) } else { containsRec(current.rightNode(), value) } } return containsRec(root, value) } /** * traversal of the binary tree in depth * * first the left child, then the parent, then the right child * * @return returns the elements of the tree */ fun traverseInOrder() : List<Int> { fun traverseInOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { traverseInOrderRec(node.leftNode(), nodes) nodes.add(node.value()) traverseInOrderRec(node.rightNode(), nodes) } } return mutableListOf<Int>().apply { traverseInOrderRec(root, this) } } /** * traversal of the binary tree in depth * * parent first, then left and right children * * @return returns the elements of the tree */ fun traversePreOrder() : List<Int> { fun traversePreOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { nodes.add(node.value()) traversePreOrderRec(node.leftNode(), nodes) traversePreOrderRec(node.rightNode(), nodes) } } return mutableListOf<Int>().apply { traversePreOrderRec(root, this) } } /** * traversal of the binary tree in depth * * first the left and right children, then the parent * * @return returns the elements of the tree */ fun traversePostOrder() : List<Int> { fun traversePostOrderRec(node: Node?, nodes: MutableList<Int>) { if (node != null) { traversePostOrderRec(node.leftNode(), nodes) traversePostOrderRec(node.rightNode(), nodes) nodes.add(node.value()) } } return mutableListOf<Int>().apply { traversePostOrderRec(root, this) } } /** * traversal of the binary tree in breadth * * uses an additional data structure - a queue into which new tree * nodes are added until the last node is added * * @return returns the elements of the tree */ fun traverseLevelOrder() : List<Int> { val root = this.root ?: return listOf() val queue = java.util.LinkedList<Node>() queue.add(root) val items = mutableListOf<Int>() while (queue.isNotEmpty()) { val node = queue.remove() items.add(node.value()) node.leftNode()?.let(queue::add) node.rightNode()?.let(queue::add) } return items } } /** * represents a tree node * * @property value - node value * @property left - left child node * @property right - right child node */ class Node( private var value: Int, private var left: Node? = null, private var right: Node? = null ) { /** * returns the value of the node */ fun value() = value /** * changes the value of a node */ fun changeValue(value: Int) { this.value = value } /** * changes the left child node */ fun changeLeft(left: Node?) { this.left = left } /** * changes the right child node */ fun changeRight(right: Node?) { this.right = right } /** * returns the left child node */ fun leftNode() = left /** * returns the right child node */ fun rightNode() = right }
[ { "class_path": "DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/structures/BinaryTree.class", "javap": "Compiled from \"BinaryTree.kt\"\npublic final class structures.BinaryTree {\n private structures.Node root;\n\n public structures.BinaryTree();\n Code:\n 0: aload_0\n 1: i...
DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/src/main/kotlin/other/FactorialAdvanced.kt
package other import java.math.BigInteger /** * * This algorithm is taken from Google Guava library * */ class FactorialAdvanced { // precomputed factorials private val factorials = longArrayOf( 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 ) fun compute(n: Int): BigInteger { if (n <= 0) { return BigInteger.ZERO } if (n < factorials.size) { return BigInteger.valueOf(factorials[n]) } // pre-allocate space for our list of intermediate BigIntegers. val approxSize = divide(n * log2Celling(n), Long.SIZE_BITS) val bigNumbers = ArrayList<BigInteger>(approxSize) // start from the pre-computed maximum long factorial. val startingNumber = factorials.size var number = factorials[startingNumber - 1] // strip off 2s from this value. var shift = number.countTrailingZeroBits() number = number shr shift // use floor(log2(num)) + 1 to prevent overflow of multiplication. var numberBits = log2Floor(number) + 1 var bits = log2Floor(startingNumber.toLong()) + 1 // check for the next power of two boundary, to save us a CLZ operation. var nextPowerOfTwo = 1 shl bits - 1 // iteratively multiply the longs as big as they can go. for (num in startingNumber..n) { // check to see if the floor(log2(num)) + 1 has changed. if ((num and nextPowerOfTwo) != 0) { nextPowerOfTwo = nextPowerOfTwo shl 1 bits++ } // get rid of the 2s in num. val tz = num.toLong().countTrailingZeroBits() val normalizedNum = (num shr tz).toLong() shift += tz // adjust floor(log2(num)) + 1. val normalizedBits = bits - tz // if it won't fit in a long, then we store off the intermediate product. if (normalizedBits + numberBits >= Long.SIZE_BITS) { bigNumbers.add(BigInteger.valueOf(number)) number = 1 numberBits = 0 } number *= normalizedNum numberBits = log2Floor(number) + 1 } // check for leftovers. if (number > 1) { bigNumbers.add(BigInteger.valueOf(number)) } // efficiently multiply all the intermediate products together. return listNumbers(bigNumbers).shiftLeft(shift) } /** * Returns the result of dividing p by q, rounding using the celling * * @throws ArithmeticException if q == 0 */ private fun divide(number: Int, divider: Int): Int { if (divider == 0) { throw ArithmeticException("/ by zero") // for GWT } val div = number / divider val rem = number - divider * div // equal to number % divider if (rem == 0) { return div } val signedNumber = 1 or (number xor divider shr Int.SIZE_BITS - 1) val increment = signedNumber > 0 return if (increment) div + signedNumber else div } private fun listNumbers(numbers: List<BigInteger>, start: Int = 0, end: Int = numbers.size): BigInteger { return when (end - start) { 0 -> BigInteger.ONE 1 -> numbers[start] 2 -> numbers[start].multiply(numbers[start + 1]) 3 -> numbers[start].multiply(numbers[start + 1]).multiply(numbers[start + 2]) else -> { // otherwise, split the list in half and recursively do this. val m = end + start ushr 1 listNumbers(numbers, start, m).multiply(listNumbers(numbers, m, end)) } } } // returns the base-2 logarithm of number, rounded according to the celling. private fun log2Celling(number: Int): Int { return Int.SIZE_BITS - (number - 1).countLeadingZeroBits() } // returns the base-2 logarithm of number rounded according to the floor. private fun log2Floor(number: Long): Int { return Long.SIZE_BITS - 1 - number.countLeadingZeroBits() } }
[ { "class_path": "DmitryTsyvtsyn__Kotlin-Algorithms-and-Design-Patterns__7ec0bf4/other/FactorialAdvanced.class", "javap": "Compiled from \"FactorialAdvanced.kt\"\npublic final class other.FactorialAdvanced {\n private final long[] factorials;\n\n public other.FactorialAdvanced();\n Code:\n 0: aloa...
akkinoc__atcoder-workspace__e650a9c/kotlin/src/main/kotlin/dev/akkinoc/atcoder/workspace/kotlin/algo/ListAlgo.kt
package dev.akkinoc.atcoder.workspace.kotlin.algo /** * The algorithms for [List]. */ object ListAlgo { /** * Generate a sequence of permutations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of permutations. */ fun <T> List<T>.perm(r: Int): Sequence<List<T>> { val i = IntArray(size) { it } val c = IntArray(r) { size - it } return generateSequence(List(r) { get(i[it]) }) s@{ _ -> val p = (r - 1 downTo 0).find f@{ p -> if (--c[p] > 0) return@f true i[size - 1] = i[p].also { i.copyInto(i, p, p + 1) } c[p] = size - p false } ?: return@s null i[size - c[p]] = i[p].also { i[p] = i[size - c[p]] } List(r) { get(i[it]) } } } /** * Generate a sequence of repeated permutations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of repeated permutations. */ fun <T> List<T>.rperm(r: Int): Sequence<List<T>> { val i = IntArray(r) return generateSequence(i.map(::get)) s@{ _ -> val p = (r - 1 downTo 0).find { i[it] < size - 1 } ?: return@s null ++i[p] i.fill(0, p + 1) i.map(::get) } } /** * Generate a sequence of combinations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of combinations. */ fun <T> List<T>.comb(r: Int): Sequence<List<T>> { val i = IntArray(r) { it } return generateSequence(i.map(::get)) s@{ _ -> var p = (r - 1 downTo 0).find { i[it] < size - r + it } ?: return@s null var n = i[p] while (p < r) i[p++] = ++n i.map(::get) } } /** * Generate a sequence of repeated combinations. * * @receiver The source elements. * @param T The element type. * @param r The number of elements to select. * @return A sequence of repeated combinations. */ fun <T> List<T>.rcomb(r: Int): Sequence<List<T>> { val i = IntArray(r) return generateSequence(i.map(::get)) s@{ _ -> val p = (r - 1 downTo 0).find { i[it] < size - 1 } ?: return@s null i.fill(i[p] + 1, p) i.map(::get) } } }
[ { "class_path": "akkinoc__atcoder-workspace__e650a9c/dev/akkinoc/atcoder/workspace/kotlin/algo/ListAlgo.class", "javap": "Compiled from \"ListAlgo.kt\"\npublic final class dev.akkinoc.atcoder.workspace.kotlin.algo.ListAlgo {\n public static final dev.akkinoc.atcoder.workspace.kotlin.algo.ListAlgo INSTANCE;...
cdome__aoc23__459a654/src/main/kotlin/day07/cards.kt
package day07 import java.io.File fun main() { val file = File("src/main/resources/day07-cards").readLines() file .map { line -> val (cards, bid) = line.split(" ") Hand(cards.trim(), bid.trim().toInt()) } .sorted() .mapIndexed { order, hand -> (order + 1) * hand.bid } .sum() .let { println("Total: $it") } file .map { line -> val (cards, bid) = line.split(" ") HandWithJokers(cards.trim(), bid.trim().toInt()) } .sorted() .mapIndexed { order, hand -> (order + 1) * hand.bid } .sum() .let { println("Total with Js: $it") } } data class Hand(val cards: String, val bid: Int) : Comparable<Hand> { private val suits = mutableMapOf<Char, Int>() init { cards.forEach { suits[it] = suits.getOrDefault(it, 0) + 1 } } private fun handValue() = when { suits.values.contains(5) -> 10 suits.values.contains(4) -> 9 suits.values.contains(3) && suits.values.contains(2) -> 8 suits.values.contains(3) -> 7 suits.values.filter { it == 2 }.size == 2 -> 6 suits.values.contains(2) -> 5 else -> 0 } private fun suitValue(suit: Char) = when (suit) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> 11 'T' -> 10 else -> suit.digitToInt() } override fun compareTo(other: Hand) = when { this.handValue() < other.handValue() -> -1 this.handValue() > other.handValue() -> 1 else -> { cards.indices.first { index -> cards[index] != other.cards[index] }.let { suitValue(cards[it]).compareTo(suitValue(other.cards[it])) } } } } data class HandWithJokers(val cards: String, val bid: Int) : Comparable<HandWithJokers> { val suits = mutableMapOf<Char, Int>() init { cards.forEach { suits[it] = suits.getOrDefault(it, 0) + 1 } if (suits.contains('J') && !suits.values.contains(5)) { val noJokes = suits.filterKeys { it != 'J' } val bestCard = noJokes .filter { it.value == noJokes.maxOf { it.value } } .maxBy { suitValue(it.key) }.key suits[bestCard] = suits[bestCard]!! + suits['J']!! suits.remove('J') } } private fun handValue() = when { suits.values.contains(5) -> 10 suits.values.contains(4) -> 9 suits.values.contains(3) && suits.values.contains(2) -> 8 suits.values.contains(3) -> 7 suits.values.filter { it == 2 }.size == 2 -> 6 suits.values.contains(2) -> 5 else -> 0 } private fun suitValue(suit: Char) = when (suit) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> 1 'T' -> 10 else -> suit.digitToInt() } override fun compareTo(other: HandWithJokers) = when { this.handValue() < other.handValue() -> -1 this.handValue() > other.handValue() -> 1 else -> { cards.indices.first { index -> cards[index] != other.cards[index] }.let { suitValue(cards[it]).compareTo(suitValue(other.cards[it])) } } } }
[ { "class_path": "cdome__aoc23__459a654/day07/CardsKt.class", "javap": "Compiled from \"cards.kt\"\npublic final class day07.CardsKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
cdome__aoc23__459a654/src/main/kotlin/day08/map.kt
package day08 import java.io.File fun main() { val file = File("src/main/resources/day08-map").readLines() val instructions = file[0] val map = file.stream().skip(2).map { line -> val (def, dirs) = line.split(" = ") val (l, r) = dirs.split(", ") def.trim() to Pair(l.removePrefix("("), r.removeSuffix(")")) }.toList().toMap() fun step(steps: Long, current: String): String { val direction = instructions[(steps % instructions.length).toInt()] return if (direction == 'L') map[current]!!.first else map[current]!!.second } var steps = 0L var current = "AAA" while (current != "ZZZ") { current = step(steps++, current) } println("Steps: $steps") val stepsList = map.keys .filter { it.endsWith("A") } .map { steps = 0 current = it while (!current.endsWith("Z")) { current = step(steps++, current) } steps } val lcm = stepsList.reduce { acc, i -> lcm(acc, i) } println("Simultaneous Steps: $lcm") } fun lcm(a: Long, b: Long): Long = a * b / gcd(a, b) fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
[ { "class_path": "cdome__aoc23__459a654/day08/MapKt.class", "javap": "Compiled from \"map.kt\"\npublic final class day08.MapKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Str...
cdome__aoc23__459a654/src/main/kotlin/day06/boats.kt
package day06 import java.io.File import kotlin.math.ceil import kotlin.math.sqrt fun main() { races() singleRace() } private fun races() { val file = File("src/main/resources/day06-boats").readLines() val times = file[0].split(":")[1].trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() } val distances = file[1].split(":")[1].trim().split(" ").filter { it.isNotBlank() }.map { it.toLong() } times.indices .map { possibilities(times[it], distances[it]) } .reduce(Int::times) .let { println("Multiple races possibilities: $it") } } private fun singleRace() { val file = File("src/main/resources/day06-boats").readLines() val time = file[0].split(":")[1].replace(" ", "").toLong() val distance = file[1].split(":")[1].replace(" ", "").toLong() println("Single race possibilities: ${possibilities(time, distance)}") } private fun possibilities(t: Long, d: Long): Int { val base = (t - sqrt(t * t - 4 * d.toDouble())) / 2 val lowerLimit = if (base == ceil(base)) base + 1 else ceil(base) return (t - 2 * lowerLimit + 1).toInt() }
[ { "class_path": "cdome__aoc23__459a654/day06/BoatsKt.class", "javap": "Compiled from \"boats.kt\"\npublic final class day06.BoatsKt {\n public static final void main();\n Code:\n 0: invokestatic #9 // Method races:()V\n 3: invokestatic #12 // Method singleR...
cdome__aoc23__459a654/src/main/kotlin/day01/trebuchet.kt
package day01 import java.io.File val numericNumbers = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9") val wordNumbers = arrayOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val numbers = wordNumbers + numericNumbers fun main() { val instructions = File("src/main/resources/day01-trebuchet") println("Plain Numbers:" + instructions.readLines().sumOf { line -> line.first { it.isDigit() }.digitToInt() * 10 + line.last { it.isDigit() }.digitToInt() }) println("Numbers and words:" + instructions .readLines() .map { firstLastNumber(it) } .sumOf { it.first * 10 + it.second } ) } fun firstLastNumber(line: String): Pair<Int, Int> { val firstNumberIndex = numbers .mapIndexed { idx, value -> idx to line.indexOf(value) } .filter { (_, position) -> position > -1 } .minBy { (_, position) -> position } .first val lastNumberIndex = numbers .mapIndexed { idx, value -> idx to line.lastIndexOf(value) } .filter { (_, position) -> position > -1 } .maxBy { (_, position) -> position } .first fun numericValue(index: Int) = (if (index > 8) index - 9 else index) + 1 return numericValue(firstNumberIndex) to numericValue(lastNumberIndex) }
[ { "class_path": "cdome__aoc23__459a654/day01/TrebuchetKt.class", "javap": "Compiled from \"trebuchet.kt\"\npublic final class day01.TrebuchetKt {\n private static final java.lang.String[] numericNumbers;\n\n private static final java.lang.String[] wordNumbers;\n\n private static final java.lang.String[] ...
cdome__aoc23__459a654/src/main/kotlin/day03/engine.kt
package day03 import java.io.File import kotlin.text.StringBuilder fun main() { val lines = File("src/main/resources/day03-engine").readLines() println("Sum of part numbers: ${engineSum(lines)}") println("Sum of gear ratios: ${gears(lines)}") } fun gears(lines: List<String>): Int { val emptyLine = ".".repeat(lines[0].length) val extendedLines = listOf(emptyLine) + lines + emptyLine val numbers: List<List<Pair<IntRange, Int>>> = rangeNumbers(extendedLines) return extendedLines.mapIndexed { lineNo, line -> line.mapIndexed { charNo, char -> if (char == '*') { val gearedParts = getAdjacentNumbers(charNo, numbers[lineNo - 1]) + getAdjacentNumbers(charNo, numbers[lineNo + 1]) + getAdjacentNumbers(charNo, numbers[lineNo]) if (gearedParts.size == 2) gearedParts[0] * gearedParts[1] else 0 } else 0 } }.flatten().sum() } fun getAdjacentNumbers(position: Int, line: List<Pair<IntRange, Int>>) = line .filter { (range, _) -> range.contains(position) || range.contains(position + 1) || range.contains(position - 1) } .map { (_, number) -> number } private fun rangeNumbers(lines: List<String>) = lines.map { line -> var inNumber = false val rowRanges = mutableListOf<Pair<IntRange, Int>>() val actualNumber = StringBuilder() var beginning = -1 line.forEachIndexed { index, c -> if (c.isDigit()) actualNumber.append(c) if (c.isDigit() && !inNumber) { beginning = index inNumber = true } if ((!c.isDigit() || index == line.length - 1) && inNumber) { rowRanges.add(beginning..<index to actualNumber.toString().toInt()) actualNumber.clear() inNumber = false } } rowRanges } fun engineSum(lines: List<String>): Int { val emptyLine = ".".repeat(lines[0].length + 2) return lines .mapIndexed { id, line -> fun extendLine(line: String) = StringBuilder(".").append(line).append(".").toString() val above = if (id == 0) emptyLine else extendLine(lines[id - 1]) val below = if (id == lines.size - 1) emptyLine else extendLine(lines[id + 1]) processLine(extendLine(line), above, below) } .flatten() .sum() } fun processLine(line: String, above: String, below: String): List<Int> { val lineNumbers = mutableListOf<Int>() val actualNumber = StringBuilder() var wasSymbol = false line.forEachIndexed() { position, char -> val charAbove = above[position] val charBelow = below[position] fun isSymbol(char: Char) = !char.isDigit() && char != '.' fun hasSymbol() = isSymbol(char) || isSymbol(charAbove) || isSymbol(charBelow) if (!char.isDigit() && (actualNumber.isNotEmpty() && (wasSymbol || hasSymbol()))) lineNumbers.add( actualNumber.toString().toInt() ) if (char.isDigit()) actualNumber.append(char) if (!char.isDigit()) actualNumber.clear() if (hasSymbol()) wasSymbol = true if (char == '.' && !isSymbol(charAbove) && !isSymbol(charBelow)) wasSymbol = false } return lineNumbers }
[ { "class_path": "cdome__aoc23__459a654/day03/EngineKt.class", "javap": "Compiled from \"engine.kt\"\npublic final class day03.EngineKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
cdome__aoc23__459a654/src/main/kotlin/day02/cubes.kt
package day02 import java.io.File data class Game(val number: Int, val hands: List<Hand>) { fun maxRed() = hands.maxOfOrNull { it.red } ?: 0 fun maxBlue() = hands.maxOfOrNull { it.blue } ?: 0 fun maxGreen() = hands.maxOfOrNull { it.green } ?: 0 } data class Hand(val red: Int, val blue: Int, val green: Int) fun main() { val games = gamesFromFile("src/main/resources/day02-cubes") println("Playable games: " + games.filter { isPlayable(it, 12, 14, 13) }.sumOf { it.number }) println("Total power: " + games.sumOf { game -> game.hands.maxOf { it.red } * game.hands.maxOf { it.blue } * game.hands.maxOf { it.green } }) } fun isPlayable(game: Game, reds: Int, blues: Int, greens: Int) = reds >= game.maxRed() && blues >= game.maxBlue() && greens >= game.maxGreen() private fun gamesFromFile(fileName: String) = File(fileName).readLines().map { line -> val (number, hands) = line.split(":").map { it.trim() } Game( number = number.split(" ")[1].toInt(), hands = hands.split(";").map { it.trim() }.map { hand -> hand.split(", ").associate { cube -> cube.split(" ").run { this[1] to this[0].toInt() } }.let { cubesMap -> Hand(cubesMap["red"] ?: 0, cubesMap["blue"] ?: 0, cubesMap["green"] ?: 0) } } ) }
[ { "class_path": "cdome__aoc23__459a654/day02/CubesKt.class", "javap": "Compiled from \"cubes.kt\"\npublic final class day02.CubesKt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/main/resources/day02-cubes\n 2: invokestatic #12 ...
mouredev__Weekly-Challenge-2022-Kotlin__2118149/app/src/main/java/com/mouredev/weeklychallenge2022/Challenge39.kt
package com.mouredev.weeklychallenge2022 /* * Reto #39 * TOP ALGORITMOS: QUICK SORT * Fecha publicación enunciado: 27/09/22 * Fecha publicación resolución: 03/10/22 * Dificultad: MEDIA * * Enunciado: Implementa uno de los algoritmos de ordenación más famosos: el "Quick Sort", * creado por <NAME>. * - Entender el funcionamiento de los algoritmos más utilizados de la historia nos ayuda a * mejorar nuestro conocimiento sobre ingeniería de software. Dedícale tiempo a entenderlo, * no únicamente a copiar su implementación. * - Esta es una nueva serie de retos llamada "TOP ALGORITMOS", donde trabajaremos y entenderemos * los más famosos de la historia. * * Información adicional: * - Usa el canal de nuestro Discord (https://mouredev.com/discord) "🔁reto-semanal" * para preguntas, dudas o prestar ayuda a la comunidad. * - Tienes toda la información sobre los retos semanales en * https://retosdeprogramacion.com/semanales2022. * */ // Basado en https://www.genbeta.com/desarrollo/implementando-el-algoritmo-quicksort fun main() { val sortedArray = quicksort(arrayOf(3, 5, 1, 8, 9, 0)) sortedArray.forEach { println(it) } } private fun quicksort(array: Array<Int>): Array<Int> { return if (array.isEmpty()) array else quicksort(array, 0, array.size - 1) } private fun quicksort(array: Array<Int>, first: Int, last: Int): Array<Int> { var i = first var j = last var array = array val pivot = (array[i] + array[j]) / 2 while (i < j) { while (array[i] < pivot) { i += 1 } while (array[j] > pivot) { j -= 1 } if (i <= j) { val x = array[j] array[j] = array[i] array[i] = x i += 1 j -= 1 } } if (first < j) { array = quicksort(array, first, j) } if (last > i) { array = quicksort(array, i, last) } return array }
[ { "class_path": "mouredev__Weekly-Challenge-2022-Kotlin__2118149/com/mouredev/weeklychallenge2022/Challenge39Kt.class", "javap": "Compiled from \"Challenge39.kt\"\npublic final class com.mouredev.weeklychallenge2022.Challenge39Kt {\n public static final void main();\n Code:\n 0: bipush 6\n ...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/top_interview_questions/easy/merge/Main.kt
package com.leetcode.top_interview_questions.easy.merge fun main() { println("Test case 1:") val arr1 = intArrayOf(1, 2, 3, 0, 0, 0) val arr2 = intArrayOf(2, 5, 6) println(Solution().merge(arr1, 3, arr2, 3)) // [1,2,2,3,5,6] println(arr1.toList()) println() println("Test case 2:") val arr3 = intArrayOf(1) val arr4 = intArrayOf() println(Solution().merge(arr3, 1, arr4, 0)) // [1] println(arr3.toList()) println() println("Test case 3:") val arr5 = intArrayOf(0) val arr6 = intArrayOf(1) println(Solution().merge(arr5, 0, arr6, 1)) // [1] println(arr5.toList()) println() println("Test case 4:") val arr7 = intArrayOf(2, 0) val arr8 = intArrayOf(1) println(Solution().merge(arr7, 1, arr8, 1)) // [1, 2] println(arr7.toList()) println() println("Test case 5:") val arr9 = intArrayOf(4, 0, 0, 0, 0, 0) val arr10 = intArrayOf(1, 2, 3, 5, 6) println(Solution().merge(arr9, 1, arr10, 5)) // [1,2,3,4,5,6] println(arr9.toList()) println() } class Solution { fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var p1 = m - 1 var p2 = n - 1 var i = m + n - 1 while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[i--] = nums1[p1--] } else { nums1[i--] = nums2[p2--] } } } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/top_interview_questions/easy/merge/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.top_interview_questions.easy.merge.MainKt {\n public static final void main();\n Code:\n 0: ldc #8 ...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/top100LikedQuestions/easy/maxim_depth_of_binary_tree/Main.kt
package com.leetcode.top100LikedQuestions.easy.maxim_depth_of_binary_tree fun main() { println("Test case 1:") val t1 = TreeNode(1) run { val leftFirstLeaf = TreeNode(3) val rightFirstLeaf = TreeNode(2) val leftSecondLeaf = TreeNode(5) val rightSecondLeaf = null //set nodes t1.left = leftFirstLeaf t1.right = rightFirstLeaf leftFirstLeaf.left = leftSecondLeaf leftFirstLeaf.right = rightSecondLeaf } println(Solution().maxDepth(t1)) println() println("Test case 2:") println(Solution().maxDepth(null)) println() } /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun maxDepth(root: TreeNode?, currentDepth: Int = 1): Int { if (root == null) return 0 if (root.left == null && root.right == null) return currentDepth val leftSide = if (root.left != null) maxDepth(root.left, currentDepth + 1) else 0 val rightSide = if (root.right != null) maxDepth(root.right, currentDepth + 1) else 0 return Math.max(leftSide, rightSide) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/top100LikedQuestions/easy/maxim_depth_of_binary_tree/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.top100LikedQuestions.easy.maxim_depth_of_binary_tree.MainKt {\n public static final void main();\n Co...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/top100LikedQuestions/easy/symetric_binary_tree/Main.kt
package com.leetcode.top100LikedQuestions.easy.symetric_binary_tree fun main() { println("Test case 1:") val t1 = TreeNode(1) t1.left = TreeNode(2) t1.right = TreeNode(2) t1.left!!.left = TreeNode(3) t1.left!!.right = TreeNode(4) t1.right!!.left = TreeNode(4) t1.right!!.right = TreeNode(3) println(Solution().isSymmetric(t1)) println("Test case 2:") val t2 = TreeNode(1) t2.left = TreeNode(2) t2.right = TreeNode(2) t2.left!!.right = TreeNode(3) t2.right!!.right = TreeNode(3) println(Solution().isSymmetric(t2)) println() } /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun isSymmetric(root: TreeNode?): Boolean { return isSymmetric(root?.left, root?.right) } fun isSymmetric(left: TreeNode?, right: TreeNode?): Boolean { if (left != null && right == null) return false if (left == null && right != null) return false if (left == null && right == null) return true if (left?.`val` != null && left.`val` != right?.`val`) { return false } return isSymmetric(left?.left, right?.right) && isSymmetric(left?.right, right?.left) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/top100LikedQuestions/easy/symetric_binary_tree/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.top100LikedQuestions.easy.symetric_binary_tree.MainKt {\n public static final void main();\n Code:\n ...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/top100LikedQuestions/easy/mergind_two_binaries_tree/Main.kt
package com.leetcode.top100LikedQuestions.easy.mergind_two_binaries_tree /** * Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 Note: The merging process must start from the root nodes of both trees. */ fun main() { println("Test case 1:") //t1 val t1 = TreeNode(1) run { val leftFirstLeaf = TreeNode(3) val rightFirstLeaf = TreeNode(2) val leftSecondLeaf = TreeNode(5) val rightSecondLeaf = null //set nodes t1.left = leftFirstLeaf t1.right = rightFirstLeaf leftFirstLeaf.left = leftSecondLeaf leftFirstLeaf.right = rightSecondLeaf } //t2 val t2 = TreeNode(2) run { val leftFirstLeaf = TreeNode(1) val rightFirstLeaf = TreeNode(3) val leftSecondLeaf = null val rightSecondLeaf = TreeNode(4) val leftSecondLeaf2 = null val rightSecondLeaf2 = TreeNode(7) //set nodes t1.left = leftFirstLeaf t1.right = rightFirstLeaf leftFirstLeaf.left = leftSecondLeaf leftFirstLeaf.right = rightSecondLeaf rightFirstLeaf.left = leftSecondLeaf2 rightFirstLeaf.right = rightSecondLeaf2 } println(Solution().mergeTrees(t1, t2)) println() } /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun mergeTrees(t1: TreeNode?, t2: TreeNode?): TreeNode? { if (t1 == null) return t2 if (t2 == null) return t1 t1.`val` += t2.`val` t1.left = mergeTrees(t1.left, t2.left) t1.right = mergeTrees(t1.right, t2.right) return t1 } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/top100LikedQuestions/easy/mergind_two_binaries_tree/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.top100LikedQuestions.easy.mergind_two_binaries_tree.MainKt {\n public static final void main();\n Code...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/top100LikedQuestions/medium/add_two_numbers/Main.kt
package com.leetcode.top100LikedQuestions.medium.add_two_numbers fun main() { println("Test case 1:") val ll1 = ListNode(2, ListNode(4, ListNode(3, null))) val ll2 = ListNode(5, ListNode(6, ListNode(4, null))) println(Solution().addTwoNumbers(ll1, ll2)) //[7,0,8] println() println("Test case 2:") val ll12 = ListNode(9, ListNode(9, ListNode(9, null))) val ll22 = ListNode(9, ListNode(9, null)) println(Solution().addTwoNumbers(ll12, ll22)) //[8, 9, 0, 1] println() println("Test case 3:") val ll13 = ListNode(5, null) val ll23 = ListNode(5, null) println(Solution().addTwoNumbers(ll13, ll23)) //[0, 1] println() } class Solution { fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { if (l1 == null || l2 == null) return null var newLinkedList: ListNode? = null var currL1 = l1 var currL2 = l2 var rest = 0 while (currL1 != null || currL2 != null) { val f1 = if (currL1?.`val` == null) 0 else currL1.`val` val f2 = if (currL2?.`val` == null) 0 else currL2.`val` var sum = f1 + f2 if (sum > 9) { sum = sum - 10 + rest rest = 1 } else { if (sum == 10) { sum = 0 rest = 1 } else { sum = sum + rest if (sum > 9) { sum = sum - 10 rest = 1 } else { rest = 0 } } } if (newLinkedList == null) { newLinkedList = ListNode(sum, null) if (currL1?.next == null && currL2?.next == null && rest != 0) { newLinkedList.next = ListNode(rest, null) } } else { var lastElement = newLinkedList while (lastElement?.next != null) { lastElement = lastElement.next } lastElement?.next = ListNode(sum, null) if (currL1?.next == null && currL2?.next == null && rest != 0) { lastElement?.next?.next = ListNode(rest, null) } } currL1 = currL1?.next currL2 = currL2?.next } return newLinkedList } } data class ListNode(var `val`: Int, var next: ListNode? = null)
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/top100LikedQuestions/medium/add_two_numbers/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.top100LikedQuestions.medium.add_two_numbers.MainKt {\n public static final void main();\n Code:\n 0: ldc...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/random_problems/easy/maximum_product_in_array/Main.kt
package com.leetcode.random_problems.easy.maximum_product_in_array fun main() { println("Test case 1:") // Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). // The product difference is (6 * 7) - (2 * 4) = 34. println(Solution().maxProductDifference(intArrayOf(5, 6, 2, 7, 4))) // 34 println() println("Test case 2:") // Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). // The product difference is (9 * 8) - (2 * 4) = 64. println(Solution().maxProductDifference(intArrayOf(4, 2, 5, 9, 7, 4, 8))) // 64 println() } class Solution { fun maxProductDifference(nums: IntArray): Int { val pairs = nums.sortedDescending().zipWithNext() val maxProduct = pairs.first().first * pairs.first().second val minProduct = pairs.last().first * pairs.last().second return maxProduct - minProduct } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/random_problems/easy/maximum_product_in_array/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.random_problems.easy.maximum_product_in_array.MainKt {\n public static final void main();\n Code:\n 0:...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/random_problems/easy/substract_product_and_sum/Main.kt
package com.leetcode.random_problems.easy.substract_product_and_sum fun main() { println("SOLUTION 1") println("Test case 1:") println(Solution().subtractProductAndSum(234)) // 15 println() println("Test case 2:") println(Solution().subtractProductAndSum(4421)) // 21 println() println("SOLUTION 2") println("Test case 1:") println(Solution2().subtractProductAndSum(234)) // 15 println() println("Test case 2:") println(Solution2().subtractProductAndSum(4421)) // 21 println() } class Solution { fun subtractProductAndSum(n: Int): Int { val numbers = n.toString().toCharArray().map { it.toString().toInt() } var product = 1 var sum = 0 numbers.forEach { num -> product *= num sum += num } return product - sum } } class Solution2 { fun subtractProductAndSum(n: Int): Int { val numbers = n.toString().toCharArray().map { it.toString().toInt() } val product = numbers.reduce { acc, i -> acc * i } val sum = numbers.sum() return product - sum } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/random_problems/easy/substract_product_and_sum/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.random_problems.easy.substract_product_and_sum.MainKt {\n public static final void main();\n Code:\n ...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/random_problems/easy/best_buy_sell_stock/Main.kt
package com.leetcode.random_problems.easy.best_buy_sell_stock fun main() { println("Test case 1:") println(Solution().maxProfit(intArrayOf(7, 1, 5, 3, 6, 4))) // 5 println() println("Test case 2:") println(Solution().maxProfit(intArrayOf(7, 6, 4, 3, 1))) // 0 println() println("Test case 3:") println(Solution().maxProfit(intArrayOf(2, 4, 1))) // 2 println() println("Test case 4:") println(Solution().maxProfit(intArrayOf(1, 2, 3, 4, 5))) // 4 println() } class Solution { fun maxProfit(prices: IntArray): Int { if (prices.isEmpty()) return 0 var min = prices.first() var max = Short.MIN_VALUE.toInt() var maxProfit = 0 prices.forEach { if (it < min) { min = Math.min(min, it) max = Short.MIN_VALUE.toInt() } else { max = Math.max(max, it) } maxProfit = Math.max(maxProfit, max - min) } return maxProfit } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/random_problems/easy/best_buy_sell_stock/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.random_problems.easy.best_buy_sell_stock.MainKt {\n public static final void main();\n Code:\n 0: ldc ...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/random_problems/easy/roman_to_integer/Main.kt
package com.leetcode.random_problems.easy.roman_to_integer fun main() { println("Test case 1:") println(Solution().romanToInt("III")) // 3 println() println("Test case 2:") println(Solution().romanToInt("IV")) // 4 println() println("Test case 3:") println(Solution().romanToInt("IX")) // 9 println() println("Test case 4:") println(Solution().romanToInt("LVIII")) // 58 Explanation: L = 50, V= 5, III = 3. println() println("Test case 5:") println(Solution().romanToInt("MCMXCIV")) // 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. println() } class Solution { val numberMap = mapOf( 'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 ) fun romanToInt(s: String): Int { var current: Int var previous = -1 val operations = s.map { c -> current = numberMap[c] ?: throw IllegalArgumentException("Map doesnt contain $c") when { previous == -1 -> { previous = current +current } previous < current -> { +(current - (previous * 2)) } else -> { previous = current current } } } return operations.reduce { acc, i -> acc + i } } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/random_problems/easy/roman_to_integer/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.random_problems.easy.roman_to_integer.MainKt {\n public static final void main();\n Code:\n 0: ldc #...
frikit__leet-code-problems__dda6831/src/main/kotlin/com/leetcode/random_problems/medium/atoi/Main.kt
package com.leetcode.random_problems.medium.atoi fun main() { println("Test case 1:") println(Solution().myAtoi("42")) // 42 println() println("Test case 2:") println(Solution().myAtoi(" -42")) // -42 println() println("Test case 3:") println(Solution().myAtoi("4193 with words")) // 4193 println() println("Test case 4:") println(Solution().myAtoi("-91283472332")) // -2147483648 println() println("Test case 5:") println(Solution().myAtoi("words and 987")) // 0 println() println("Test case 6:") println(Solution().myAtoi("3.14159")) // 3 println() println("Test case 7:") println(Solution().myAtoi("+-12")) // 0 println() println("Test case 8:") println(Solution().myAtoi(".1")) // 0 println() } class Solution { fun myAtoi(s: String): Int { if (s.trim().isEmpty()) return 0 val isPositive = s.trim().first() != '-' var firstDigit = true var finalNumb = "" val isFirstSign = s.trim().first() == '+' || s.trim().first() == '-' val drop = if (isFirstSign) 1 else 0 s.trim().drop(drop).takeWhile { it.isDigit() }.toCharArray().forEach { if (!it.isDigit() && !it.isWhitespace() && firstDigit) { return 0 } else if (it.isDigit() && firstDigit) { finalNumb += it firstDigit = false } else if (it.isDigit() && finalNumb.isNotEmpty()) { finalNumb += it if (finalNumb.toBigInteger() !in Int.MIN_VALUE.toBigInteger()..Int.MAX_VALUE.toBigInteger()) { return if (isPositive) { Int.MAX_VALUE } else { Int.MIN_VALUE } } } else if (!it.isDigit() && finalNumb.isNotEmpty() && !firstDigit) { return if (isPositive) finalNumb.toInt() else finalNumb.toInt() * -1 } } if (finalNumb.isEmpty()) finalNumb = "0" return if (isPositive) finalNumb.toInt() else finalNumb.toInt() * -1 } }
[ { "class_path": "frikit__leet-code-problems__dda6831/com/leetcode/random_problems/medium/atoi/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.leetcode.random_problems.medium.atoi.MainKt {\n public static final void main();\n Code:\n 0: ldc #8 /...
davidcurrie__advent-of-code-2021__dd37372/src/day4/result.kt
package day4 import java.io.File data class Board(val numbers: Map<Int, Pair<Int, Int>>) { private val rows = numbers.values.maxOf { it.first } + 1 private val cols = numbers.values.maxOf { it.second } + 1 private val matches = mutableListOf<Int>() private val rowCounts = MutableList(rows) { 0 } private val colCounts = MutableList(cols) { 0 } fun play(number: Int): Boolean { val coords = numbers[number] if (coords != null) { matches.add(number) rowCounts[coords.first] += 1 colCounts[coords.second] += 1 return rowCounts[coords.first] == rows || colCounts[coords.second] == cols } return false } fun score() = (numbers.keys.sum() - matches.sum()) * matches.last() } fun main() { val parts = File("src/day4/input.txt").readText().split("\n\n") val numbers = parts[0].split(",").map { it.toInt() } var boards = parts.subList(1, parts.size).map { it.readBoard() } val scores = mutableListOf<Int>() for (number in numbers) { val newBoards = mutableListOf<Board>() for (board in boards) { if (board.play(number)) { scores += board.score() } else { newBoards += board } } boards = newBoards } println(scores.first()) println(scores.last()) } fun String.readBoard() : Board { val numbers = mutableMapOf<Int, Pair<Int, Int>>() for ((row, line) in this.lines().withIndex()) { numbers.putAll(line.split(" ") .filter { it.isNotEmpty() } .map { it.toInt() } .mapIndexed { col, number -> number to Pair(row, col) }) } return Board(numbers) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day4/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day4.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day3/result.kt
package day3 import java.io.File import kotlin.reflect.KFunction1 fun main() { val lines = File("src/day3/input.txt") .readLines() .map { line -> line.toList().map { char -> Character.getNumericValue(char) } } val columns = lines.transpose() println(columns.map { it.gamma() }.toDecimal() * columns.map { it.epsilon() }.toDecimal()) println(filter(lines, List<Int>::gamma).toDecimal() * filter(lines, List<Int>::epsilon).toDecimal()) } fun List<Int>.gamma() = if (sum() >= size / 2.0) 1 else 0 fun List<Int>.epsilon() = 1 - gamma() fun List<Int>.toDecimal() = reduce { a, b -> a * 2 + b } fun <T> List<List<T>>.transpose(): List<List<T>> = (first().indices).map { column(it) } fun <T> List<List<T>>.column(index: Int): List<T> = fold(listOf()) { acc, row -> acc + row[index] } fun filter(lines: List<List<Int>>, fn: KFunction1<List<Int>, Int>): List<Int> = lines.indices.fold(lines) { candidates, index -> if (candidates.size == 1) candidates else candidates.filter { line -> line[index] == fn(candidates.column(index)) } }.single()
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day3/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day3.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day2/result.kt
package day2 import day2.Direction.* import java.io.File import java.util.* fun main() { val moves = File("src/day2/input.txt") .readLines() .map { it.split(" ") } .map { Move(valueOf(it[0].uppercase(Locale.getDefault())), it[1].toInt()) } println(calculate(PartOneState(), moves)) println(calculate(PartTwoState(), moves)) } fun calculate(initialState: State, moves: List<Move>): Int { val finalState = moves.fold(initialState) { state, move -> state.transform(move) } return finalState.horizontal * finalState.depth } enum class Direction { UP, DOWN, FORWARD } data class Move(val direction: Direction, val units: Int) interface State { val horizontal: Int val depth: Int fun transform(move: Move): State } data class PartOneState(override val horizontal: Int = 0, override val depth: Int = 0) : State { override fun transform(move: Move): PartOneState { return when (move.direction) { UP -> copy(depth = depth - move.units) DOWN -> copy(depth = depth + move.units) FORWARD -> copy(horizontal = horizontal + move.units) } } } data class PartTwoState(override val horizontal: Int = 0, override val depth: Int = 0, val aim: Int = 0) : State { override fun transform(move: Move): PartTwoState { return when (move.direction) { UP -> copy(aim = aim - move.units) DOWN -> copy(aim = aim + move.units) FORWARD -> copy(horizontal = horizontal + move.units, depth = depth + aim * move.units) } } }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day2/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day2.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day5/result.kt
package day5 import java.io.File import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.sign data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int) fun main() { val input = File("src/day5/input.txt").readLines() val regex = Regex("([0-9]*),([0-9]*) -> ([0-9]*),([0-9]*)") val lines = input.map { regex.matchEntire(it)!!.destructured.toList().map { it.toInt() } } .map { Line(it[0], it[1], it[2], it[3]) } val rectilinear = lines.filter { it.x1 == it.x2 || it.y1 == it.y2 } println(solve(rectilinear)) println(solve(lines)) } fun solve(lines: List<Line>): Int { val points = mutableMapOf<Pair<Int, Int>, Int>() lines.forEach { line -> val dx = (line.x2 - line.x1).sign val dy = (line.y2 - line.y1).sign val length = max((line.x1 - line.x2).absoluteValue, (line.y1 - line.y2).absoluteValue) (0..length).map { i -> Pair(line.x1 + i * dx, line.y1 + i * dy) }.forEach { point -> points[point] = (points[point] ?: 0).plus(1) } } return points.count { it.value > 1 } }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day5/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day5.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day23/result.kt
package day23 import java.io.File import java.util.* import kotlin.math.abs fun main() { println(solve("src/day23/input.txt")) println(solve("src/day23/input-part2.txt")) } enum class Amphipod(val stepEnergy: Int) { A(1), B(10), C(100), D(1000) } data class Room(val natives: Amphipod, val size: Int, val entry: Int, val inhabitants: List<Amphipod>) { fun allHome() = full() && allNatives() fun full() = inhabitants.size == size fun allNatives() = inhabitants.all { it == natives } fun exit(): Pair<Amphipod, Room>? { if (allNatives()) return null if (inhabitants.isEmpty()) return null return Pair(inhabitants.first(), copy(inhabitants = inhabitants.subList(1, inhabitants.size))) } fun entry(a: Amphipod?): Room? { if (a != natives) return null if (!allNatives()) return null return copy(inhabitants = listOf(a) + inhabitants) } } data class Burrow(val hallway: List<Amphipod?>, val rooms: List<Room>, val energy: Int = 0) { fun allHome() = rooms.all { it.allHome() } fun hallwayClear(from: Int, to: Int) = (if (from < to) (from+1..to) else (to until from)).all { hallway[it] == null } fun entries() = rooms.map { it.entry } fun hallwayStops() = hallway.indices.filterNot { it in entries() } fun moves(): List<Burrow> { val roomExits = rooms.withIndex().map { (roomIndex, room) -> val exit = room.exit() if (exit == null) { emptyList() } else { hallwayStops().filter { hallwayClear(room.entry, it) }.map { to -> val newHallway = hallway.mapIndexed { index, amphipod -> if (index == to) exit.first else amphipod } val newRooms = rooms.mapIndexed { index, room -> if (index == roomIndex) exit.second else room } val steps = 1 + abs(to - room.entry) + (room.size - room.inhabitants.size) val energyUse = steps * exit.first.stepEnergy Burrow(newHallway, newRooms, energy + energyUse) } } }.flatten() val roomEntries = hallway.mapIndexed { from, amphipod -> rooms.mapIndexedNotNull { roomIndex, room -> val newRoom = room.entry(amphipod) if (newRoom != null && hallwayClear(from, room.entry)) { val newHallway = hallway.mapIndexed { index, amphipod -> if (index == from) null else amphipod } val newRooms = rooms.mapIndexed { index, room -> if (index == roomIndex) newRoom else room } val steps = abs(from - room.entry) + (room.size - room.inhabitants.size) val energyUse = steps * amphipod!!.stepEnergy Burrow(newHallway, newRooms, energy + energyUse) } else { null } } }.flatten() return roomEntries + roomExits } fun print() { println("Energy: $energy") println(hallway.map { amphipod -> amphipod?.name ?: "." }.joinToString("") { it }) (0 until rooms[0].size).forEach { row -> println(hallway.indices.map { index -> rooms.firstOrNull { room -> room.entry == index } } .map { room -> if (room == null) " " else (row + room.inhabitants.size - room.size).let { if (it >= 0) room.inhabitants[it].name else "." } } .joinToString("") { it }) } } } fun solve(filename: String): Int? { val queue = PriorityQueue<List<Burrow>>(Comparator.comparingInt { it.last().energy }) queue.add(listOf(parse(filename))) val visited = mutableMapOf<Pair<List<Amphipod?>, List<Room>>, Int>() while (queue.isNotEmpty()) { val burrows = queue.poll() val burrow = burrows.last() val signature = Pair(burrow.hallway, burrow.rooms) val previousBestEnergy = visited[signature] if ((previousBestEnergy != null) && (previousBestEnergy <= burrow.energy)) { continue } visited[signature] = burrow.energy if (burrow.allHome()) { burrows.forEach { it.print() } return burrow.energy } queue.addAll(burrow.moves().map { burrows + it }) } return null } fun parse(filename: String): Burrow { val lines = File(filename).readLines() val hallway = lines[1].drop(1).dropLast(1).map { if (it == '.') null else Amphipod.valueOf(it.toString()) } val roomLines = lines.drop(2).dropLast(1) val rooms = (0..3).map { room -> val natives = Amphipod.values()[room] val inhabitants = roomLines.mapNotNull { if (it[3 + (room * 2)] == '.') null else Amphipod.valueOf(it[3 + (room * 2)].toString()) } Room(natives, roomLines.size, 2 + (room * 2), inhabitants) } return Burrow(hallway, rooms) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day23/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day23.ResultKt {\n public static final void main();\n Code:\n 0: ldc #8 // String src/day23/input.txt\n 2: invokestatic #12 ...
davidcurrie__advent-of-code-2021__dd37372/src/day12/result.kt
package day12 import java.io.File fun Map<String, List<String>>.partOne(path: List<String>) : List<List<String>> { if (path.last() == "end") { return listOf(path) } return this[path.last()]!! .filter { it.uppercase() == it || !path.contains(it) } .map{ partOne( path + it) } .flatten() } fun Map<String, List<String>>.partTwo(path: List<String>, revisited: String? = null) : List<List<String>> { if (path.last() == "end") { return listOf(path) } return this[path.last()]!! .filter { it.uppercase() == it || !path.contains(it) || (it != "start" && path.contains(it) && revisited == null) } .map{ partTwo( path + it, if (it.lowercase() == it && path.contains(it)) it else revisited ) } .flatten() } fun main() { val input = File("src/day12/input.txt") .readLines() .map { it.split("-") } val bidirectional = input.map { (a, b) -> listOf(b, a) } + input val links = bidirectional.groupBy( keySelector = { it[0] }, valueTransform = { it[1] } ) println(links.partOne(listOf("start")).size) println(links.partTwo(listOf("start")).size) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day12/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day12.ResultKt {\n public static final java.util.List<java.util.List<java.lang.String>> partOne(java.util.Map<java.lang.String, ? extends java.util.List<java.lang.Stri...
davidcurrie__advent-of-code-2021__dd37372/src/day15/result.kt
package day15 import java.io.File import java.util.* val deltas = listOf(Coord(-1, 0), Coord(1, 0), Coord(0, -1), Coord(0, 1)) data class Coord(val x: Int, val y: Int) data class CoordRisk(val coord: Coord, val risk: Int) fun Map<Coord, Int>.explore(): Int { val end = Coord(keys.maxOf { it.x }, keys.maxOf { it.y }) val visited = mutableSetOf<Coord>() val queue = PriorityQueue<CoordRisk> { p1, p2 -> p1.risk - p2.risk } queue.add(CoordRisk(Coord(0, 0), 0)) while (queue.peek().coord != end) { val pair = queue.poll() deltas.map { delta -> Coord(pair.coord.x + delta.x, pair.coord.y + delta.y) } .filter { it in this.keys } .filter { it !in visited } .forEach { visited += it queue.add(CoordRisk(it, pair.risk + this[it]!!)) } } return queue.peek().risk } fun main() { val grid = File("src/day15/input.txt").readLines() .mapIndexed { y, line -> line.toList().mapIndexed { x, ch -> Coord(x, y) to ch.digitToInt() } } .flatten().toMap() println(grid.explore()) val width = grid.keys.maxOf { it.x } + 1 val height = grid.keys.maxOf { it.y } + 1 val extendedGrid = mutableMapOf<Coord, Int>() for (x in 0..4) { for (y in 0..4) { extendedGrid.putAll(grid.map { (coord, value) -> Coord(coord.x + (x * width), coord.y + (y * height)) to ((value + x + y - 1) % 9) + 1 }.toMap()) } } println(extendedGrid.explore()) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day15/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day15.ResultKt {\n private static final java.util.List<day15.Coord> deltas;\n\n public static final java.util.List<day15.Coord> getDeltas();\n Code:\n 0: get...
davidcurrie__advent-of-code-2021__dd37372/src/day14/result.kt
package day14 import java.io.File fun solve(rules: Map<Pair<Char, Char>, Char>, initialPairCounts: Map<Pair<Char, Char>, Long>, steps: Int): Long { var pairCounts = initialPairCounts for (step in 1..steps) { pairCounts = pairCounts.entries.fold(emptyMap()) { acc, pairCount -> val ch = rules[pairCount.key] if (ch != null) { acc + Pair(pairCount.key.first, ch).let { it to (acc[it] ?: 0L) + pairCount.value } + Pair(ch, pairCount.key.second).let { it to (acc[it] ?: 0L) + pairCount.value } } else { acc + (pairCount.key to pairCount.value) } } } val counts = pairCounts.entries .fold(emptyMap<Char, Long>()) { acc, pairCount -> acc + (pairCount.key.first to (acc[pairCount.key.first] ?: 0L) + pairCount.value) } return counts.values.let { it.maxOrNull()!! - it.minOrNull()!! } } fun main() { val lines = File("src/day14/input.txt").readLines() val template = lines[0] val rules = lines.drop(2).map { it.split(" -> ") }.associate { Pair(it[0][0], it[0][1]) to it[1][0] } val pairCounts = "$template ".zipWithNext().groupingBy { it }.eachCount().map { (k, v) -> k to v.toLong() }.toMap() println(solve(rules, pairCounts, 10)) println(solve(rules, pairCounts, 40)) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day14/ResultKt$main$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class day14.ResultKt$main$$inlined$groupingBy$1 implements kotlin.collections.Grouping<kotlin.Pair<? extends java.lang.Character, ? extends j...
davidcurrie__advent-of-code-2021__dd37372/src/day13/result.kt
package day13 import java.io.File import kotlin.math.abs fun main() { val input = File("src/day13/input.txt").readText() val coords = Regex("([0-9]*),([0-9]*)").findAll(input) .map { Pair(it.groupValues[1].toInt(), it.groupValues[2].toInt()) } .toSet() val folds = Regex("fold along ([xy])=([0-9]*)").findAll(input) .map { Pair(it.groupValues[1], it.groupValues[2].toInt()) } .toList() println(coords.map { p -> p.fold(folds[0]) }.toSet().size) folds.fold(coords) { c, f -> c.map { p -> p.fold(f) }.toSet() }.output() } fun Pair<Int, Int>.fold(fold: Pair<String, Int>) = Pair( if (fold.first == "x") fold.second - abs(first - fold.second) else first, if (fold.first == "y") fold.second - abs(second - fold.second) else second ) fun Set<Pair<Int, Int>>.output() { (0..maxOf { it.second }).forEach { y -> (0..maxOf { it.first }).forEach { x -> print(if (contains(Pair(x, y))) "#" else ".") } println() } println() }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day13/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day13.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day25/result.kt
package day25 import java.io.File fun main() { val lines = File("src/day25/input.txt").readLines() val seafloor = Seafloor(lines[0].length, lines.size, Herd.values().associateWith { herd -> herd.parse(lines) }.toMutableMap()) while (seafloor.move()) {} println(seafloor.steps) } data class Seafloor(val width: Int, val height: Int, val cucumbers: MutableMap<Herd, Set<Coord>>, var steps: Int = 0) data class Coord(val x: Int, val y: Int) enum class Herd(val ch: Char, val delta: Coord) { EAST('>', Coord(1, 0)), SOUTH('v', Coord(0, 1)) } fun Herd.parse(lines: List<String>) = lines.mapIndexed { j, row -> row.toList().mapIndexedNotNull { i, c -> if (c == ch) Coord(i, j) else null } } .flatten().toSet() fun Seafloor.empty(coord: Coord) = cucumbers.values.none { coords -> coords.contains(coord) } fun Seafloor.print() { for (y in 0 until height) { for (x in 0 until width) { print(Herd.values() .mapNotNull { if (cucumbers[it]!!.contains(Coord(x, y))) it.ch else null } .firstOrNull() ?: '.') } println() } println() } fun Seafloor.move(): Boolean { var moved = false Herd.values().forEach { herd -> cucumbers[herd] = cucumbers[herd]!!.map { coord -> Coord((coord.x + herd.delta.x) % width, (coord.y + herd.delta.y) % height) .let { newCoord -> if (empty(newCoord)) newCoord.also { moved = true } else coord } }.toSet() } steps++ return moved }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day25/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day25.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day22/result.kt
package day22 import java.io.File import kotlin.math.max import kotlin.math.min data class Line(val min: Int, val max: Int) { fun overlap(other: Line): Line? { val start = max(min, other.min) val end = min(max, other.max) return if (start <= end) Line(start, end) else null } } data class Cuboid(val on: Boolean, val x: Line, val y: Line, val z: Line) { fun volume() = (if (on) 1L else -1L) * (1 + x.max - x.min) * (1 + y.max - y.min) * (1 + z.max - z.min) fun intersection(other: Cuboid): Cuboid? { val overlapX = x.overlap(other.x) val overlapY = y.overlap(other.y) val overlapZ = z.overlap(other.z) if (overlapX != null && overlapY != null && overlapZ != null) { return Cuboid(!on, overlapX, overlapY, overlapZ) } return null } } fun calculate(cuboids: List<Cuboid>) = cuboids.fold(mutableListOf<Cuboid>()) { acc, c -> acc.addAll(acc.mapNotNull { existing -> existing.intersection(c) }) if (c.on) { acc.add(c) } acc }.sumOf { it.volume() } fun main() { val cuboids = File("src/day22/input.txt").readLines() .map { val (on, minX, maxX, minY, maxY, minZ, maxZ) = Regex("(on|off) x=(-?[0-9]*)..(-?[0-9]*),y=(-?[0-9]*)..(-?[0-9]*),z=(-?[0-9]*)..(-?[0-9]*)") .matchEntire(it)!!.destructured Cuboid( on == "on", Line(minX.toInt(), maxX.toInt()), Line(minY.toInt(), maxY.toInt()), Line(minZ.toInt(), maxZ.toInt()) ) } val cuboidsInRegion = cuboids .filter { c -> c.x.min >= -50 && c.x.max <= 50 && c.y.min >= -50 && c.y.max <= 50 && c.z.min >= -50 && c.z.max <= 50 } println(calculate(cuboidsInRegion)) println(calculate(cuboids)) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day22/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day22.ResultKt {\n public static final long calculate(java.util.List<day22.Cuboid>);\n Code:\n 0: aload_0\n 1: ldc #10 // Stri...
davidcurrie__advent-of-code-2021__dd37372/src/day9/result.kt
package day9 import java.io.File data class Coord(val x: Int, val y: Int) fun Map<Coord, Int>.neighbours(coord: Coord) = listOf(Pair(-1, 0), Pair(0, -1), Pair(1, 0), Pair(0, 1)) .map { Coord(coord.x + it.first, coord.y + it.second) } .filter { contains(it) } .toSet() fun Map<Coord, Int>.isLowest(coord: Coord) = neighbours(coord).map { this[coord]!! < this[it]!! }.all { it } fun Map<Coord, Int>.basin(coord: Coord, visited: Set<Coord>): Set<Coord> { if (visited.contains(coord)) { return visited } return neighbours(coord) .filter { this[it] != 9 && this[coord]!! < this[it]!! } .fold(visited + coord) { acc, neighbour -> acc + basin(neighbour, acc) } } fun main() { val grid = File("src/day9/input.txt").readLines() .mapIndexed { i, row -> row.toList().mapIndexed { j, ch -> Coord(i, j) to Character.getNumericValue(ch) } } .flatten() .toMap() val lowest = grid.filter { (coord, _) -> grid.isLowest(coord) } println(lowest.values.sumOf { it + 1 }) println(lowest.keys .map { grid.basin(it, emptySet()).size } .sortedDescending() .take(3) .reduce(Int::times)) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day9/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day9.ResultKt {\n public static final java.util.Set<day9.Coord> neighbours(java.util.Map<day9.Coord, java.lang.Integer>, day9.Coord);\n Code:\n 0: aload_0\n ...
davidcurrie__advent-of-code-2021__dd37372/src/day8/result.kt
package day8 import java.io.File data class Line(val input:Set<Set<Char>>, val output: List<Set<Char>>) { private val from: Map<Set<Char>, Int> init { val to = mutableMapOf( 1 to input.find { it.size == 2 }!!, 4 to input.find { it.size == 4 }!!, 7 to input.find { it.size == 3 }!!, 8 to input.find { it.size == 7 }!! ) to[6] = (input - to.values).find { it.size == 6 && (it - to[1]!!).size == 5 }!! to[3] = (input - to.values).find { it.size == 5 && (to[8]!! - it - to[1]!!).size == 2}!! to[5] = (input - to.values).find { it.size == 5 && (it - to[4]!!).size == 2}!! to[9] = (input - to.values).find { (it - to[4]!!).size == 2 }!! to[2] = (input - to.values).find { it.size == 5 }!! to[0] = (input - to.values).single() from = to.entries.associate { (k, v) -> v to k } } fun partOne() = output.map { segments -> if (setOf(1, 4, 7, 8).contains(from[segments])) 1 else 0 }.sum() fun partTwo() = output.fold(0) { acc, segments -> acc * 10 + from[segments]!! } } fun String.toSegments() = split(" ").map { it.toCharArray().toSet() } fun main() { val lines = File("src/day8/input.txt").readLines() .map { it.split(" | ") } .map { line -> Line(line[0].toSegments().toSet(), line[1].toSegments())} println(lines.sumOf { it.partOne() }) println(lines.sumOf { it.partTwo() }) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day8/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day8.ResultKt {\n public static final java.util.List<java.util.Set<java.lang.Character>> toSegments(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day18/result.kt
package day18 import java.io.File import java.lang.IllegalStateException interface Element class RegularNumber(val value: Int) : Element object Open : Element object Close : Element fun main() { val elements = File("src/day18/input.txt").readLines().map { line -> line.toList().map { ch -> when (ch) { '[' -> Open ']' -> Close ',' -> null else -> RegularNumber(ch.digitToInt()) } }.filterNotNull() } println(elements.reduce { x, y -> x + y }.magnitude()) println(sequence { for ((i, x) in elements.withIndex()) { for ((j, y) in elements.withIndex()) { if (i != j) yield(x + y) } } }.maxOf { it.magnitude() }) } private operator fun List<Element>.plus(other: List<Element>): List<Element> { val result = ArrayList<Element>(this.size + other.size + 2) result.add(Open) result.addAll(this) result.addAll(other) result.add(Close) outer@ while (true) { var depth = 0 for (i in 0 until result.size - 4) { if (depth > 3 && result[i] is Open && result[i + 3] is Close) { // Explode val left = result[i + 1] val right = result[i + 2] if (left is RegularNumber && right is RegularNumber) { result[i] = RegularNumber(0) result.subList(i + 1, i + 4).clear() for (j in i - 1 downTo 0) { val number = result[j] as? RegularNumber ?: continue result[j] = RegularNumber(number.value + left.value) break } for (j in i + 1 until result.size) { val number = result[j] as? RegularNumber ?: continue result[j] = RegularNumber(number.value + right.value) break } continue@outer } } depth += when (result[i]) { Open -> 1 Close -> -1 else -> 0 } } for ((i, element) in result.withIndex()) { if (element is RegularNumber && element.value > 9) { // Split result.removeAt(i) result.addAll( i, listOf(Open, RegularNumber(element.value / 2), RegularNumber((element.value + 1) / 2), Close) ) continue@outer } } break@outer } return result } fun List<Element>.magnitude() = recurse(0).first fun List<Element>.recurse(index: Int): Pair<Int, Int> { return when (val element = this[index]) { Open -> { val (left, leftEnd) = recurse(index + 1) val (right, rightEnd) = recurse(leftEnd) Pair(3 * left + 2 * right, rightEnd + 1) } is RegularNumber -> Pair(element.value, index + 1) else -> throw IllegalStateException() } }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day18/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day18.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day20/result.kt
package day20 import java.io.File fun Array<Array<Boolean>>.count() = sumOf { row -> row.count { it } } fun Array<Array<Boolean>>.enhance(algo: List<Boolean>, infinity: Boolean) = (-1..size).map { y -> (-1..this[0].size).map { x -> algo[index(x, y, infinity)] }.toTypedArray() }.toTypedArray() fun Array<Array<Boolean>>.index(x: Int, y: Int, infinity: Boolean) = (-1..1).map { dy -> (-1..1).map { dx -> if (get(x + dx, y + dy, infinity)) 1 else 0 } } .flatten().joinToString("").toInt(2) fun Array<Array<Boolean>>.get(x: Int, y: Int, infinity: Boolean) = if (y < 0 || y >= size || x < 0 || x >= this[0].size) infinity else this[y][x] fun main() { val lines = File("src/day20/input.txt").readLines() val algo = lines[0].toList().map { it == '#' } var pixels = lines.drop(2) .map { line -> line.toList().map { (it == '#') }.toTypedArray() }.toTypedArray() repeat(2) { pixels = pixels.enhance(algo, algo[0] && (it % 2 != 0)) } println(pixels.count()) repeat(48) { pixels = pixels.enhance(algo, algo[0] && (it % 2 != 0)) } println(pixels.count()) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day20/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day20.ResultKt {\n public static final int count(java.lang.Boolean[][]);\n Code:\n 0: aload_0\n 1: ldc #9 // String <this>\n ...
davidcurrie__advent-of-code-2021__dd37372/src/day16/result.kt
package day16 import java.io.File import java.lang.IllegalStateException import kotlin.math.max import kotlin.math.min data class Packet(val length: Int, val versionSum: Int, val value: Long) data class Literal(val length: Int, val value: Long) data class Bits(val input: String) { private var index = 0 private fun getString(length: Int): String { val result = input.substring(index, index + length) index += length return result } private fun getInt(length: Int) = getString(length).toInt(2) private fun getLong(length: Int) = getString(length).toLong(2) private fun getLiteral(): Literal { val startIndex = index var result = "" do { val hasNext = getInt(1) == 1 result += getString(4) } while (hasNext) return Literal(index - startIndex, result.toLong(2)) } fun getPacket(): Packet { val version = getInt(3) val type = getInt(3) if (type == 4) { return getLiteral().let { Packet(it.length + 6, version, it.value) } } else { val lengthType = getInt(1) val subPackets = mutableListOf<Packet>() if (lengthType == 0) { val totalLength = getLong(15) val startIndex = index while (index < startIndex + totalLength) { subPackets += getPacket() } } else { val numSubPackets = getLong(11) for (i in 0 until numSubPackets) { subPackets += getPacket() } } val fn: (Long, Long) -> Long = when (type) { 0 -> Long::plus 1 -> Long::times 2 -> ::min 3 -> ::max 5 -> { p1, p2 -> if (p1 > p2) 1 else 0 } 6 -> { p1, p2 -> if (p1 < p2) 1 else 0 } 7 -> { p1, p2 -> if (p1 == p2) 1 else 0 } else -> throw IllegalStateException() } return subPackets .reduce { p1, p2 -> Packet( p1.length + p2.length, p1.versionSum + p2.versionSum, fn(p1.value, p2.value) ) } .let { it.copy(length = it.length + 6, versionSum = it.versionSum + version) } } } } fun main() { val bits = Bits(File("src/day16/input.txt").readText() .map { hex -> Integer.parseInt(hex.toString(), 16) } .map { int -> Integer.toBinaryString(int) } .map { str -> str.padStart(4, '0') } .joinToString("")) bits.getPacket().let { println(it.versionSum) println(it.value) } }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day16/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day16.ResultKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
davidcurrie__advent-of-code-2021__dd37372/src/day10/result.kt
package day10 import java.io.File val closings = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val partOneScores = mapOf(null to 0, ')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val partTwoScores = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4) fun main() { val lines = File("src/day10/input.txt").readLines().map { it.toList() } val results = lines.map { line -> line.let { line.fold(ArrayDeque<Char>()) { stack, ch -> if (ch in closings.keys) stack.addLast(closings[ch]!!) else if (ch != stack.removeLast()) return@let Pair(ch, null) stack }.let { stack -> Pair(null, stack) } } } println(results.map { it.first }.sumOf { partOneScores[it]!! }) println(results.map { it.second } .filterNotNull() .map { it.reversed().fold(0L) { acc, ch -> (acc * 5) + partTwoScores[ch]!! } } .sorted() .let { it[it.size / 2] }) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day10/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day10.ResultKt {\n private static final java.util.Map<java.lang.Character, java.lang.Character> closings;\n\n private static final java.util.Map<java.lang.Character, ...
davidcurrie__advent-of-code-2021__dd37372/src/day21/result.kt
package day21 import java.io.File fun Int.mod(m: Int) = ((this - 1) % m) + 1 class Die(val sides: Int) { var value = 1 var rolled = 0 fun roll() : Int { return value.also { value = (value + 1).mod(sides) rolled++ } } } fun partOne(initialPositions: List<Int>) { val positions = initialPositions.toTypedArray() val scores = arrayOf(0, 0) val die = Die(100) var player = 0 while (scores.maxOrNull()!! < 1000) { val score = (0..2).map { die.roll() }.sum() positions[player] = (positions[player] + score).mod(10) scores[player] += positions[player] player = (player + 1) % 2 } println(scores.minOrNull()!! * die.rolled) } data class PlayerState(val number: Int, val position: Int, val score: Int) fun partTwo(initialPositions: List<Int>) { val states = mutableMapOf( listOf(PlayerState(0, initialPositions[0], 0), PlayerState(1, initialPositions[1], 0)) to 1L ) val wins = arrayOf(0L, 0L) while (states.isNotEmpty()) { val iterator = states.iterator() val (players, count) = iterator.next() iterator.remove() // Next player always comes first in list val (player, position, score) = players[0] (1..3).map { die1 -> (1..3).map { die2 -> (1..3).map { die3 -> val newPosition = (position + die1 + die2 + die3).mod(10) val newScore = score + newPosition if (newScore >= 21) { wins[player] += count } else { val newPlayerState = PlayerState(player, newPosition, newScore) val newGameState = listOf(players[1], newPlayerState) states[newGameState] = count + (states[newGameState] ?: 0) } } } } } println(wins.maxOrNull()) } fun main() { val initialPositions = File("src/day21/input.txt").readLines().map { it.last().digitToInt() } partOne(initialPositions) partTwo(initialPositions) }
[ { "class_path": "davidcurrie__advent-of-code-2021__dd37372/day21/ResultKt.class", "javap": "Compiled from \"result.kt\"\npublic final class day21.ResultKt {\n public static final int mod(int, int);\n Code:\n 0: iload_0\n 1: iconst_1\n 2: isub\n 3: iload_1\n 4: irem\n ...
apankowski__garcon__10f5126/src/main/kotlin/dev/pankowski/garcon/domain/Texts.kt
package dev.pankowski.garcon.domain import java.text.BreakIterator import java.util.* import java.util.Collections.unmodifiableList /** * Calculates [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) * between given char sequences. */ fun levenshtein(a: CharSequence, b: CharSequence): Int { val aLength = a.length val bLength = b.length var cost = IntArray(aLength + 1) { it } var newCost = IntArray(aLength + 1) { 0 } for (j in 1..bLength) { newCost[0] = j for (i in 1..aLength) { val insertCost = cost[i] + 1 val deleteCost = newCost[i - 1] + 1 val replaceCost = cost[i - 1] + if (a[i - 1] == b[j - 1]) 0 else 1 newCost[i] = minOf(insertCost, deleteCost, replaceCost) } run { val temp = cost; cost = newCost; newCost = temp } // Or: cost = newCost.also { newCost = cost } } return cost[aLength] } /** * Calculates [Damerau-Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) * between given char sequences. */ fun damerauLevenshtein(a: CharSequence, b: CharSequence): Int { fun distance(a: CharSequence, b: CharSequence): Int { assert(a.length >= 2) assert(b.length >= 2) fun levenshteinCost(cost0: IntArray, cost1: IntArray, i: Int, j: Int): Int { val insertCost = cost0[i] + 1 val deleteCost = cost1[i - 1] + 1 val replaceCost = cost0[i - 1] + if (a[i - 1] == b[j - 1]) 0 else 1 return minOf(insertCost, deleteCost, replaceCost) } fun damerauCost(cost0: IntArray, cost1: IntArray, cost2: IntArray, i: Int, j: Int): Int { val levenshteinCost = levenshteinCost(cost1, cost2, i, j) if (a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) { val transpositionCost = cost0[i - 2] + 1 return minOf(levenshteinCost, transpositionCost) } return levenshteinCost } val aLength = a.length val bLength = b.length // First seed row, corresponding to j = 0 val cost0 = IntArray(aLength + 1) { it } // Second seed row, corresponding to j = 1 val cost1 = IntArray(aLength + 1) cost1[0] = 1 for (i in 1..aLength) cost1[i] = levenshteinCost(cost0, cost1, i, 1) val cost2 = IntArray(aLength + 1) tailrec fun cost(cost0: IntArray, cost1: IntArray, cost2: IntArray, j: Int): Int { cost2[0] = j cost2[1] = levenshteinCost(cost1, cost2, 1, j) for (i in 2..aLength) cost2[i] = damerauCost(cost0, cost1, cost2, i, j) return if (j == bLength) cost2[aLength] else cost(cost1, cost2, cost0, j + 1) } return cost(cost0, cost1, cost2, 2) } // Analyze input and eliminate simple cases: // - Order strings by length, so that we have longer (l) and shorter (s). // - Exit early when shorter string has zero or one character. // This leaves us with l.length >= s.length >= 2. val (l, s) = if (a.length >= b.length) Pair(a, b) else Pair(b, a) return when { s.isEmpty() -> l.length s.length == 1 -> if (l.contains(s[0])) l.length - 1 else l.length else -> distance(l, s) } } fun String.extractWords(locale: Locale): List<String> { val it = BreakIterator.getWordInstance(locale) it.setText(this) tailrec fun collectWords(start: Int, end: Int, words: List<String>): List<String> { if (end == BreakIterator.DONE) return words val word = this.substring(start, end) val newWords = if (Character.isLetterOrDigit(word[0])) words + word else words return collectWords(end, it.next(), newWords) } return unmodifiableList(collectWords(it.first(), it.next(), emptyList())) } fun CharSequence.ellipsize(at: Int) = when { length <= at -> this else -> substring(0, at) + Typography.ellipsis } fun CharSequence.oneLinePreview(maxLength: Int) = replace("\\s*\\n+\\s*".toRegex(), " ").ellipsize(maxLength)
[ { "class_path": "apankowski__garcon__10f5126/dev/pankowski/garcon/domain/TextsKt.class", "javap": "Compiled from \"Texts.kt\"\npublic final class dev.pankowski.garcon.domain.TextsKt {\n public static final int levenshtein(java.lang.CharSequence, java.lang.CharSequence);\n Code:\n 0: aload_0\n ...
samjdixon__git-training__c5ab05f/src/main/kotlin/com/gitTraining/Fibbonaci.kt
package com.gitTraining fun computeFibbonaciNumber(position: Int, recursion: Boolean = false): Int { if (recursion) return recursiveFibbonachi(position) if (position == 0) return 0 if (position < 0) { val positionIsOdd = position % 2 == -1 return if (positionIsOdd) computeFibbonaciNumber(-position) else (computeFibbonaciNumber(-position) * -1) } if (position == 1 || position == 2) return 1 var smallFibbonachiNumber = 1 var largeFibbonachiNumber = 1 var currentPosition = 2 while (currentPosition < position) { val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber smallFibbonachiNumber = largeFibbonachiNumber largeFibbonachiNumber = nextFibbonachiNumber currentPosition ++ } return largeFibbonachiNumber } fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> { if (!efficient) return (start..end).map { computeFibbonaciNumber(it) } if (start > end) return listOf() if (start == end) return listOf(computeFibbonaciNumber(start)) val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1)) (2..(end-start)).forEach { output.add(output[it-2] + output[it-1]) } return output } fun recursiveFibbonachi(initialPosition: Int, left: Int = 0, right: Int = 1, position: Int = initialPosition): Int { if (initialPosition == 0) return 0 if (position == 0) return left if (initialPosition > 0) { return recursiveFibbonachi(initialPosition, right, left + right, position - 1) } else { return recursiveFibbonachi(initialPosition, right - left, left, position + 1) } }
[ { "class_path": "samjdixon__git-training__c5ab05f/com/gitTraining/FibbonaciKt.class", "javap": "Compiled from \"Fibbonaci.kt\"\npublic final class com.gitTraining.FibbonaciKt {\n public static final int computeFibbonaciNumber(int, boolean);\n Code:\n 0: iload_1\n 1: ifeq 15\n ...
SeanShubin__code-structure-2__f83b9e3/tree/src/main/kotlin/com/seanshubin/code/structure/tree/Tree.kt
package com.seanshubin.code.structure.tree sealed interface Tree<KeyType, ValueType> { fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType> fun getValue(path: List<KeyType>): ValueType? fun toLines( keyOrder: Comparator<KeyType>, keyToString: (KeyType) -> String, valueToString: (ValueType) -> String ): List<String> fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>> data class Branch<KeyType, ValueType>(val parts: Map<KeyType, Tree<KeyType, ValueType>>) : Tree<KeyType, ValueType> { override fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType> { if (path.isEmpty()) return Leaf(value) val key = path[0] val remainingPath = path.drop(1) val innerValue = when (val existingInnerValue = parts[key]) { is Branch -> existingInnerValue else -> empty() } val newInnerValue = innerValue.setValue(remainingPath, value) val newValue = Branch(parts + (key to newInnerValue)) return newValue } override fun getValue(path: List<KeyType>): ValueType? { if (path.isEmpty()) return null val key = path[0] val remainingPath = path.drop(1) val innerValue = when (val existingInnerValue = parts[key]) { is Branch -> existingInnerValue is Leaf -> return existingInnerValue.value null -> return null } val finalValue = innerValue.getValue(remainingPath) return finalValue } override fun toLines( keyOrder: Comparator<KeyType>, keyToString: (KeyType) -> String, valueToString: (ValueType) -> String ): List<String> { val keys = parts.keys.toList().sortedWith(keyOrder) val lines = keys.flatMap { key -> val value = parts.getValue(key) val thisLine = keyToString(key) val subLines = value.toLines(keyOrder, keyToString, valueToString).map { " $it" } listOf(thisLine) + subLines } return lines } override fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>> { return parts.flatMap { (key, value) -> val newPath = path + key value.pathValues(newPath) } } } data class Leaf<KeyType, ValueType>(val value: ValueType) : Tree<KeyType, ValueType> { override fun setValue(path: List<KeyType>, value: ValueType): Tree<KeyType, ValueType> { return empty<KeyType, ValueType>().setValue(path, value) } override fun getValue(path: List<KeyType>): ValueType? { return if (path.isEmpty()) this.value else null } override fun toLines( keyOrder: Comparator<KeyType>, keyToString: (KeyType) -> String, valueToString: (ValueType) -> String ): List<String> = listOf(valueToString(value)) override fun pathValues(path: List<KeyType>): List<Pair<List<KeyType>, ValueType>> { return listOf(path to value) } } companion object { fun <KeyType, ValueType> empty(): Branch<KeyType, ValueType> = Branch(emptyMap()) } }
[ { "class_path": "SeanShubin__code-structure-2__f83b9e3/com/seanshubin/code/structure/tree/Tree$Branch.class", "javap": "Compiled from \"Tree.kt\"\npublic final class com.seanshubin.code.structure.tree.Tree$Branch<KeyType, ValueType> implements com.seanshubin.code.structure.tree.Tree<KeyType, ValueType> {\n ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day09/solution.kt
package day09 import java.io.File private const val MAX_HEIGHT = 9 fun main() { val lines = File("src/main/kotlin/day09/input.txt").readLines() val mapSize = lines.size val heightMap: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() } var riskLevel = 0 val basins = mutableListOf<Set<Point>>() for (row in heightMap.indices) { for (col in heightMap[row].indices) { val currHeight = heightMap[row][col] val isLowPoint = ( (row == 0 || heightMap[row - 1][col] > currHeight) && (row == mapSize - 1 || row < mapSize - 1 && heightMap[row + 1][col] > currHeight) && (col == 0 || heightMap[row][col - 1] > currHeight) && (col == mapSize - 1 || col < mapSize - 1 && heightMap[row][col + 1] > currHeight) ) if (isLowPoint) { riskLevel += currHeight + 1 val lowPoint = Point(row, col) basins += scanBasinAroundPoint(lowPoint, heightMap, mutableSetOf()) } } } println(riskLevel) println(basins.map { it.size }.sortedDescending().take(3).reduce(Int::times)) } fun scanBasinAroundPoint(point: Point, heightMap: Array<IntArray>, basinPoints: MutableSet<Point>): Set<Point> { val heightMapSize = heightMap.size if ( point.row < 0 || point.row >= heightMapSize || point.col < 0 || point.col >= heightMapSize || heightMap[point.row][point.col] == MAX_HEIGHT || point in basinPoints ) return emptySet() basinPoints.add(point) scanBasinAroundPoint(Point(point.row - 1, point.col), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row + 1, point.col), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row, point.col - 1), heightMap, basinPoints) scanBasinAroundPoint(Point(point.row, point.col + 1), heightMap, basinPoints) return basinPoints } data class Point(val row: Int, val col: Int)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day09/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day09.SolutionKt {\n private static final int MAX_HEIGHT;\n\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day08/solution.kt
package day08 import java.io.File import java.util.* fun main() { val lines = File("src/main/kotlin/day08/input.txt").readLines() val signalToOutputList = lines.map { line -> line.substringBefore(" | ").split(" ").map { it.toSortedSet() } to line.substringAfter(" | ").split(" ") .map { it.toSortedSet() } } println(signalToOutputList.flatMap { it.second }.count { it.size in setOf(2, 3, 4, 7) }) println(signalToOutputList.sumOf { decodeNumber(it.first, it.second) }) } /** * Segments * 111 * 2 3 * 2 3 * 444 * 5 6 * 5 6 * 777 */ fun decodeNumber(uniqueSignalPatterns: List<SortedSet<Char>>, unknownNumber: List<SortedSet<Char>>): Int { val segmentsToDigit = HashMap<SortedSet<Char>, Int>() segmentsToDigit[uniqueSignalPatterns.first { it.size == 2 }] = 1 segmentsToDigit[uniqueSignalPatterns.first { it.size == 3 }] = 7 segmentsToDigit[uniqueSignalPatterns.first { it.size == 4 }] = 4 segmentsToDigit[uniqueSignalPatterns.first { it.size == 7 }] = 8 val segmentFrequencies = uniqueSignalPatterns.flatten() .groupBy { it } .mapValues { it.value.size } val fifthSegmentChar = segmentFrequencies .filter { it.value == 4 }.map { it.key } .first() val unknownFiveSegmentSignals = uniqueSignalPatterns.filter { it.size == 5 }.toMutableList() val unknownSixSegmentSignals = uniqueSignalPatterns.filter { it.size == 6 }.toMutableList() var segmentsRepresentingFive: SortedSet<Char>? = null var segmentsRepresentingSix: SortedSet<Char>? = null //5 with fifth segment is 6 for (fiveSegmentSignal in unknownFiveSegmentSignals) { val fiveSegmentSignalWithFifthSegment = fiveSegmentSignal.toSortedSet() fiveSegmentSignalWithFifthSegment.add(fifthSegmentChar) if (unknownSixSegmentSignals.contains(fiveSegmentSignalWithFifthSegment)) { segmentsRepresentingFive = fiveSegmentSignal segmentsRepresentingSix = fiveSegmentSignalWithFifthSegment unknownFiveSegmentSignals.remove(segmentsRepresentingFive) unknownSixSegmentSignals.remove(segmentsRepresentingSix) break } } segmentsToDigit[segmentsRepresentingFive!!] = 5 segmentsToDigit[segmentsRepresentingSix!!] = 6 segmentsToDigit[unknownFiveSegmentSignals.first { it.contains(fifthSegmentChar) }] = 2 segmentsToDigit[unknownFiveSegmentSignals.first { !it.contains(fifthSegmentChar) }] = 3 segmentsToDigit[unknownSixSegmentSignals.first { it.contains(fifthSegmentChar) }] = 0 segmentsToDigit[unknownSixSegmentSignals.first { !it.contains(fifthSegmentChar) }] = 9 return unknownNumber.mapNotNull { segmentsToDigit[it] }.joinToString("").toInt() }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day08/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day08.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day06/solution.kt
package day06 import java.io.File private const val REPRODUCTION_INTERVAL = 7 fun main() { val fishReproductionTimers = File("src/main/kotlin/day06/input.txt").readLines().first().split(",").map { it.toInt() } val fishCountByTimer = fishReproductionTimers.fold(Array(9) { 0L }) { acc, fishReproductionTimer -> acc[fishReproductionTimer]++ acc } for (day in 0..79) { calculateFishCount(day, fishCountByTimer) } println(fishCountByTimer.asSequence().sumOf { it }) for (day in 80..255) { calculateFishCount(day, fishCountByTimer) } println(fishCountByTimer.asSequence().sumOf { it }) } private fun calculateFishCount(day: Int, fishCountByTimer: Array<Long>) { val reproductionDayTimer = day % REPRODUCTION_INTERVAL val newFishCount = fishCountByTimer[reproductionDayTimer] fishCountByTimer[reproductionDayTimer] += fishCountByTimer[7] fishCountByTimer[7] = fishCountByTimer[8] fishCountByTimer[8] = newFishCount }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day06/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day06.SolutionKt {\n private static final int REPRODUCTION_INTERVAL;\n\n public static final void main();\n Code:\n 0: new #8 // class ja...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day12/solution.kt
package day12 import java.io.File fun main() { val lines = File("src/main/kotlin/day12/input.txt").readLines() val cavesByName: MutableMap<String, Cave> = mutableMapOf() lines.forEach { val fromCaveName = it.substringBefore("-") val toCaveName = it.substringAfter("-") val fromCave = cavesByName.computeIfAbsent(fromCaveName) { Cave(fromCaveName) } val toCave = cavesByName.computeIfAbsent(toCaveName) { Cave(toCaveName) } fromCave.addConnection(toCave) } val startCave = cavesByName.getValue("start") val endCave = cavesByName.getValue("end") println( search(endCave, listOf(startCave)) { cave, visitedCavesPath -> cave.isLarge() || cave !in visitedCavesPath } .count() ) println( search(endCave, listOf(startCave)) { cave, visitedCavesPath -> cave.isLarge() || cave !in visitedCavesPath || cave.name != "start" && visitedCavesPath.filter { !it.isLarge() } .groupBy { it } .mapValues { it.value.size } .let { map -> map.isNotEmpty() && map.all { it.value == 1 } } } .count() ) } fun search(toCave: Cave, visitedCavesPath: List<Cave>, visitStrategy: (Cave, List<Cave>) -> Boolean): Set<List<Cave>> { val lastVisited = visitedCavesPath.last() if (lastVisited == toCave) return mutableSetOf(visitedCavesPath) return lastVisited.connectsTo .filter { visitStrategy(it, visitedCavesPath) } .map { search(toCave, visitedCavesPath + it, visitStrategy) } .flatten().toSet() } data class Cave(val name: String) { val connectsTo: MutableSet<Cave> = mutableSetOf() fun addConnection(other: Cave) { if (other !in connectsTo) { connectsTo.add(other) other.addConnection(this) } } fun isLarge() = name.all { it.isUpperCase() } override fun toString(): String { return name } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day12/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day12.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day15/solution.kt
package day15 import java.io.File import java.util.* fun main() { val lines = File("src/main/kotlin/day15/input.txt").readLines() val mapSize = lines.size val riskLevelGrid: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() } val minimumRiskLevelGrid: Array<IntArray> = findMinimumRiskLevels(mapSize, riskLevelGrid) println(minimumRiskLevelGrid[mapSize - 1][mapSize - 1]) val riskLevelFullGrid: Array<IntArray> = Array(mapSize * 5) { y -> IntArray(mapSize * 5) { x -> (riskLevelGrid[y % mapSize][x % mapSize] + x / mapSize + y / mapSize - 1) % 9 + 1 } } val minimumRiskLevelFullGrid: Array<IntArray> = findMinimumRiskLevels(mapSize * 5, riskLevelFullGrid) println(minimumRiskLevelFullGrid[mapSize * 5 - 1][mapSize * 5 - 1]) } private fun findMinimumRiskLevels( mapSize: Int, riskLevelGrid: Array<IntArray> ): Array<IntArray> { val minimumRiskLevelGrid: Array<IntArray> = Array(mapSize) { IntArray(mapSize) { Int.MAX_VALUE } } val parents: MutableMap<Point, Point> = mutableMapOf() val unvisited: MutableSet<Point> = (0 until mapSize).flatMap { y -> (0 until mapSize).map { x -> Point(x, y) } }.toMutableSet() minimumRiskLevelGrid[0][0] = 0 val visiting: PriorityQueue<Pair<Point, Int>> = PriorityQueue { o1, o2 -> o1.second - o2.second } visiting.add(Point(0, 0) to 0) while (visiting.isNotEmpty()) { val (nextCandidate, parentRiskLevel) = visiting.poll() for (adjacent in nextCandidate.adjacents(mapSize)) { if (adjacent in unvisited) { val adjacentRiskLevel = riskLevelGrid[adjacent.y][adjacent.x] val adjacentMinimumRiskLevel = minimumRiskLevelGrid[adjacent.y][adjacent.x] if (adjacentRiskLevel + parentRiskLevel < adjacentMinimumRiskLevel) { minimumRiskLevelGrid[adjacent.y][adjacent.x] = adjacentRiskLevel + parentRiskLevel parents[adjacent] = nextCandidate visiting.offer(adjacent to adjacentRiskLevel + parentRiskLevel) } } } unvisited.remove(nextCandidate) } return minimumRiskLevelGrid } data class Point(val x: Int, val y: Int) fun Point.adjacents(size: Int): Set<Point> { val points = mutableSetOf<Point>() if (this.x > 0) points.add(Point(this.x - 1, this.y)) if (this.x < size) points.add(Point(this.x + 1, this.y)) if (this.y > 0) points.add(Point(this.x, this.y - 1)) if (this.y < size) points.add(Point(this.x, this.y + 1)) return points }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day15/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day15.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day14/solution.kt
package day14 import java.io.File import java.util.* fun main() { var template: List<Char> = LinkedList() var pairInsertionsRules: Map<Pair<Char, Char>, Char> = emptyMap() File("src/main/kotlin/day14/input.txt").useLines { linesSequence -> val linesIterator = linesSequence.iterator() template = List(1) { linesIterator.next() }.first().toCollection(LinkedList<Char>()) linesIterator.next() pairInsertionsRules = linesIterator.asSequence().map { (it.substringBefore(" -> ").first() to it.substringBefore(" -> ").last()) to it.substringAfter(" -> ") .first() }.toMap() } val edgeCharacters = arrayOf(template.first(), template.last()).groupBy { it }.mapValues { it.value.count() } val initialPairCount: Map<Pair<Char, Char>, Long> = template.windowed(2).map { it[0] to it[1] }.groupBy { it }.mapValues { it.value.size.toLong() } val pairCountAfter10Steps = (0..9).fold(initialPairCount) { acc, _ -> acc.react(pairInsertionsRules) } val characterCountAfter10Steps = pairCountAfter10Steps.frequencies(edgeCharacters) println(characterCountAfter10Steps.maxMinDiff()) val pairCountAfter40Steps = (0..29).fold(pairCountAfter10Steps) { acc, _ -> acc.react(pairInsertionsRules) } val characterCountAfter40Steps = pairCountAfter40Steps.frequencies(edgeCharacters) println(characterCountAfter40Steps.maxMinDiff()) } fun Map<Pair<Char, Char>, Long>.react(pairInsertionsRules: Map<Pair<Char, Char>, Char>): Map<Pair<Char, Char>, Long> = buildMap { this@react.forEach { entry -> val originalPair = entry.key val newChar = pairInsertionsRules.getValue(originalPair) val pairOne = originalPair.first to newChar val pairTwo = newChar to originalPair.second val originalPairCount = entry.value merge(pairOne, originalPairCount) { a, b -> a + b } merge(pairTwo, originalPairCount) { a, b -> a + b } } } fun Map<Pair<Char, Char>, Long>.frequencies(edgeCharacters: Map<Char, Int>): Map<Char, Long> = this.flatMap { listOf(it.key.first to it.value, it.key.second to it.value) } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() + (edgeCharacters[it.key] ?: 0) } fun Map<Char, Long>.maxMinDiff() = this.maxOf { it.value } / 2 - this.minOf { it.value } / 2
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day14/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day14.SolutionKt {\n public static final void main();\n Code:\n 0: new #10 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day13/solution.kt
package day13 import java.io.File fun main() { var points: Set<Point> = emptySet() var foldCommands: List<FoldCommand> = emptyList() File("src/main/kotlin/day13/input.txt").useLines { linesSequence -> val linesIterator = linesSequence.iterator() points = linesIterator.asSequence().takeWhile { s -> s.isNotBlank() }.map { Point( it.substringBefore(",").toInt(), it.substringAfter(",").toInt() ) }.toSet() foldCommands = linesIterator.asSequence().map { FoldCommand( it.substringBefore('=').last(), it.substringAfter('=').toInt() ) }.toList() } println(fold(points, foldCommands[0]).count()) val codePoints = foldCommands.fold(points) { acc, foldCommand -> fold(acc, foldCommand) } codePoints.display() } fun fold(points: Set<Point>, foldCommand: FoldCommand): Set<Point> = points.map { point -> if (foldCommand.axis == 'x' && point.x > foldCommand.position) { Point(2 * foldCommand.position - point.x, point.y) } else if (foldCommand.axis == 'y' && point.y > foldCommand.position) { Point(point.x, 2 * foldCommand.position - point.y) } else { point } }.toSet() fun Set<Point>.display() { (0..this.maxOf { it.y }).forEach { y -> (0..this.maxOf { it.x }).forEach { x -> print(if (Point(x, y) in this) "\u2588" else "\u2591") } println() } } data class Point(val x: Int, val y: Int) data class FoldCommand(val axis: Char, val position: Int)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day13/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day13.SolutionKt {\n public static final void main();\n Code:\n 0: aconst_null\n 1: astore_0\n 2: invokestatic #14 // Method kotlin/coll...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day25/solution.kt
package day25 import java.io.File typealias SeaFloor = Array<Array<SeaCucumberType?>> fun main() { val lines = File("src/main/kotlin/day25/input.txt").readLines() val seaFloor: SeaFloor = SeaFloor(lines.size) { i -> lines[i].map { SeaCucumberType.fromSymbol(it) }.toTypedArray() } var iterationCount = 0 var tmpState = seaFloor.copyOf() do { // tmpState.print() val (newState, numberOfMoves) = evolve(tmpState) tmpState = newState iterationCount++ } while (numberOfMoves != 0) println(iterationCount) } fun evolve(seaFloor: SeaFloor): Pair<SeaFloor, Int> { val seaFloorHeight = seaFloor.size val seaFloorWidth = seaFloor[0].size var movesCount = 0 val newState = SeaFloor(seaFloorHeight) { Array(seaFloorWidth) { null } } for (row in seaFloor.indices) { for (col in seaFloor[row].indices) { val seaCucumberType = seaFloor[row][col] if (seaCucumberType == SeaCucumberType.EAST) { if (seaFloor[row][(col + 1) % seaFloorWidth] == null) { newState[row][(col + 1) % seaFloorWidth] = seaCucumberType movesCount++ } else { newState[row][col] = seaCucumberType } } } } for (col in 0 until seaFloorWidth) { for (row in 0 until seaFloorHeight) { val seaCucumberType = seaFloor[row][col] if (seaCucumberType == SeaCucumberType.SOUTH) { if (seaFloor[(row + 1) % seaFloorHeight][col] == SeaCucumberType.SOUTH || newState[(row + 1) % seaFloorHeight][col] != null) { newState[row][col] = seaCucumberType } else { newState[(row + 1) % seaFloorHeight][col] = seaCucumberType movesCount++ } } } } return newState to movesCount } fun SeaFloor.print() { for (row in indices) { for (col in get(row).indices) { print(get(row).get(col)?.symbol ?: '.') } println() } println("========================") } enum class SeaCucumberType(val symbol: Char) { EAST('>'), SOUTH('v'), ; companion object { fun fromSymbol(symbol: Char) = values().firstOrNull { it.symbol == symbol } } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day25/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day25.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day22/solution.kt
package day22 import java.io.File fun main() { val inputLineRegex = """(on|off) x=([-]?\d+)..([-]?\d+),y=([-]?\d+)..([-]?\d+),z=([-]?\d+)..([-]?\d+)""".toRegex() val lines = File("src/main/kotlin/day22/input.txt").readLines() val rebootSteps = lines.map { line -> val (state, x0, x1, y0, y1, z0, z1) = inputLineRegex.matchEntire(line)?.destructured ?: throw IllegalArgumentException("Invalid input") RebootStep(state == "on", Cuboid(x0.toInt()..x1.toInt(), y0.toInt()..y1.toInt(), z0.toInt()..z1.toInt())) } val initializingRebootSteps = rebootSteps.filter { it.cube.x.first >= -50 && it.cube.x.last <= 50 && it.cube.y.first >= -50 && it.cube.y.last <= 50 && it.cube.z.first >= -50 && it.cube.z.last <= 50 } println(initializingRebootSteps.calculateTurnedOn()) println(rebootSteps.calculateTurnedOn()) } fun List<RebootStep>.calculateTurnedOn(): Long { val xCutPoints = flatMap { listOf(it.cube.x.first, it.cube.x.last + 1) }.distinct().sorted() val yCutPoints = flatMap { listOf(it.cube.y.first, it.cube.y.last + 1) }.distinct().sorted() val zCutPoints = flatMap { listOf(it.cube.z.first, it.cube.z.last + 1) }.distinct().sorted() val space = Array(xCutPoints.size - 1) { Array(yCutPoints.size - 1) { BooleanArray(zCutPoints.size - 1) } } //compress val xCompressedCutPoints = xCutPoints.withIndex().associateBy({ it.value }, { it.index }) val yCompressedCutPoints = yCutPoints.withIndex().associateBy({ it.value }, { it.index }) val zCompressedCutPoints = zCutPoints.withIndex().associateBy({ it.value }, { it.index }) for (rebootStep in this) { val cube = rebootStep.cube for (x in xCompressedCutPoints[cube.x.first]!! until xCompressedCutPoints[cube.x.last + 1]!!) { for (y in yCompressedCutPoints[cube.y.first]!! until yCompressedCutPoints[cube.y.last + 1]!!) { for (z in zCompressedCutPoints[cube.z.first]!! until zCompressedCutPoints[cube.z.last + 1]!!) { space[x][y][z] = rebootStep.turnedOn } } } } //decompress and count var count = 0L for (x in space.indices) { for (y in space[x].indices) { for (z in space[x][y].indices) { if (space[x][y][z]) count += 1L * (xCutPoints[x + 1] - xCutPoints[x]) * (yCutPoints[y + 1] - yCutPoints[y]) * (zCutPoints[z + 1] - zCutPoints[z]) } } } return count } data class RebootStep(val turnedOn: Boolean, val cube: Cuboid) data class Cuboid(val x: IntRange, val y: IntRange, val z: IntRange)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day22/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day22.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day04/solution.kt
package day04 import java.io.File fun main() { var drawnNumbers: List<Int> = listOf() var bingoBoards: List<BingoBoard> = listOf() File("src/main/kotlin/day04/input.txt").useLines { seq -> val iterator = seq.iterator() drawnNumbers = List(1) { iterator.next() }.single().split(",").map { it.toInt() } bingoBoards = iterator.asSequence() .filter { it.isNotEmpty() } .chunked(5) .map { BingoBoard(it.map { it.split(" ").filter { it.isNotEmpty() }.map { it.toInt() } }.toList()) } .toList() } for (drawnNumber in drawnNumbers) { val indexOfWinningBoard = bingoBoards.indexOfFirst { it.isWinning(drawnNumber) } if (indexOfWinningBoard != -1) { println(drawnNumber * bingoBoards[indexOfWinningBoard].unmarkedNumbers().sum()) break } } val notYetWonBoards = ArrayList(bingoBoards) val wonBoards = mutableListOf<BingoBoard>() for (drawnNumber in drawnNumbers) { val wonBoardsForDrawnNumber = notYetWonBoards.filter { it.isWinning(drawnNumber) } wonBoards.addAll(wonBoardsForDrawnNumber) notYetWonBoards.removeAll(wonBoardsForDrawnNumber) if (notYetWonBoards.isEmpty()) { println(drawnNumber * wonBoards.last().unmarkedNumbers().sum()) break } } } class BingoBoard(private val board: List<List<Int>>) { private val markedNumbers: MutableList<Int> = mutableListOf() fun isWinning(drawnNumber: Int): Boolean { board.forEach { if (it.contains(drawnNumber)) { markedNumbers.add(drawnNumber) } } return checkBoard() } private fun checkBoard(): Boolean { return board.any { it.all { it in markedNumbers } } || (0..4).map { column -> board.map { it[column] } }.any { it.all { it in markedNumbers } } } fun unmarkedNumbers(): List<Int> = board.flatten().filter { it !in markedNumbers } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day04/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day04.SolutionKt {\n public static final void main();\n Code:\n 0: new #10 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day03/solution.kt
package day03 import java.io.File fun main() { val lines = File("src/main/kotlin/day03/input.txt").readLines() val binaryCodeCounts = IntArray(12) { 0 } val reportDatBitsHistogram = lines .map { it.toCharArray() } .fold(binaryCodeCounts) { counter, reportLine -> for (i in counter.indices) { counter[i] += reportLine[i].digitToInt() } counter } val gammaRate = reportDatBitsHistogram .map { if (it > lines.size / 2) 0 else 1 } .joinToString(separator = "") .toCharArray() .binaryToDecimal() val epsilonRate = reportDatBitsHistogram .map { if (it > lines.size / 2) 1 else 0 } .joinToString(separator = "") .toCharArray() .binaryToDecimal() println(gammaRate) //1519 println(epsilonRate) //2576 println(gammaRate * epsilonRate) //Part 2 val diagnosticReportLines = lines .map { it.toCharArray() } val oxygenGeneratorRating = filterOxygenGeneratorRating(diagnosticReportLines, 0)[0].binaryToDecimal() println(oxygenGeneratorRating) //3597 val co2ScrubberRating = filterCO2ScrubberRating(diagnosticReportLines, 0)[0].binaryToDecimal() println(co2ScrubberRating) //1389 println(oxygenGeneratorRating * co2ScrubberRating) } fun filterOxygenGeneratorRating(reportData: List<CharArray>, reportIndex: Int): List<CharArray> = filterDiagnosticReport( reportData, reportIndex ) { filterSize, significantBit, reportSize -> (filterSize + if (reportSize % 2 == 0 && significantBit != null && significantBit == 1) 1 else 0) > reportSize / 2 } fun filterCO2ScrubberRating(reportData: List<CharArray>, reportIndex: Int): List<CharArray> = filterDiagnosticReport( reportData, reportIndex ) { filterSize, significantBit, reportSize -> (filterSize - if (reportSize % 2 == 0 && significantBit != null && significantBit == 0) 1 else 0) < (reportSize + 1) / 2 } fun filterDiagnosticReport( reportData: List<CharArray>, reportIndex: Int, evaluationPredicate: (Int, Int?, Int) -> Boolean ): List<CharArray> { if (reportIndex == reportData[0].size || reportData.size == 1) { return reportData } val filteredReportData = reportData .partition { it[reportIndex] == '1' } .toList() .first { evaluationPredicate( it.size, if (it.isNotEmpty()) it[0][reportIndex].digitToInt() else null, reportData.size ) } return filterDiagnosticReport(filteredReportData, reportIndex + 1, evaluationPredicate) } fun CharArray.binaryToDecimal(): Int { var value = 0 for (char in this) { value = value shl 1 value += char - '0' } return value }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day03/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day03.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day02/solution.kt
package day02 import java.io.File fun main() { val lines = File("src/main/kotlin/day02/input.txt").readLines() val submarineV1 = lines .fold(SubmarineV1()) { submarine, commandString -> submarine.execute(commandString.toCommand()) } println(submarineV1.x * submarineV1.y) val submarineV2 = lines .fold(SubmarineV2()) { submarine, commandString -> submarine.execute(commandString.toCommand()) } println(submarineV2.x * submarineV2.y) } sealed class Command class Forward(val amount: Int): Command() class Down(val amount: Int): Command() class Up(val amount: Int): Command() fun String.toCommand(): Command { val moveType = this.substringBefore(" ") val amount = this.substringAfter(" ").toInt() return when (moveType) { "forward" -> Forward(amount) "down" -> Down(amount) "up" -> Up(amount) else -> Forward(0) } } class SubmarineV1(var x: Int = 0, var y: Int = 0) { fun execute(command: Command): SubmarineV1 = when (command) { is Forward -> apply { x += command.amount } is Down -> apply { y += command.amount } is Up -> apply { y -= command.amount } } } class SubmarineV2(var x: Int = 0, var y: Int = 0, var aim: Int = 0) { fun execute(command: Command): SubmarineV2 = when (command) { is Forward -> apply { x += command.amount; y += aim * command.amount } is Down -> apply { aim += command.amount } is Up -> apply { aim -= command.amount } } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day02/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day02.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day05/solution.kt
package day05 import java.io.File import kotlin.math.abs fun main() { val segmentPattern = Regex("""(\d+),(\d+) -> (\d+),(\d+)""") val inputLines = File("src/main/kotlin/day05/input.txt").readLines() val segments = inputLines .mapNotNull { segmentPattern.matchEntire(it) } .map { Segment( Point(it.groupValues[1].toInt(), it.groupValues[2].toInt()), Point(it.groupValues[3].toInt(), it.groupValues[4].toInt()) ) } val dangerousVentCount = segments.asSequence() .filter { it.isLateral() } .dangerousVentCount() println(dangerousVentCount) val dangerousVentCount2 = segments.asSequence() .dangerousVentCount() println(dangerousVentCount2) } fun Sequence<Segment>.dangerousVentCount() = this .map { it.getSegmentPoints() } .flatten() .groupBy { it } .count { it.value.size > 1 } data class Segment(val p1: Point, val p2: Point) { fun isLateral(): Boolean = p1.x == p2.x || p1.y == p2.y fun getSegmentPoints(): List<Point> { val points = mutableListOf<Point>() var lastPoint: Point = p1 for (i in 0..getLength()) { points.add(lastPoint) lastPoint += getDirectionVector() } return points } private fun getDirectionVector(): Vector { val dx = p2.x - p1.x val dy = p2.y - p1.y return Vector(dx / getLength(), dy / getLength()) } private fun getLength(): Int = maxOf(abs(p2.x - p1.x), abs(p2.y - p1.y)) } data class Point(val x: Int, val y:Int) { operator fun plus(vector: Vector): Point = Point(x + vector.dx, y + vector.dy) } data class Vector(val dx: Int, val dy: Int)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day05/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day05.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day18/solution.kt
package day18 import java.io.File fun main() { val lines = File("src/main/kotlin/day18/input.txt").readLines() val snailFishNumbers = lines.map { parseSnailFish(it) } println(snailFishNumbers.reduce { acc, snailFishNumber -> acc.copy() + snailFishNumber.copy() }.magnitude()) var highestMagnitude = 0 for (number1 in snailFishNumbers) { for (number2 in snailFishNumbers) { val magnitude1 = (number1.copy() + number2.copy()).magnitude() if (magnitude1 > highestMagnitude) highestMagnitude = magnitude1 val magnitude2 = (number2.copy() + number1.copy()).magnitude() if (magnitude2 > highestMagnitude) highestMagnitude = magnitude2 } } println(highestMagnitude) } fun parseSnailFish(value: String): SnailFishNumber { if (!value.startsWith('[')) return Regular(value.toInt()) val inside = value.removeSurrounding("[", "]") var nestLevel = 0 val index = inside.indexOfFirst { if (it == '[') nestLevel++ else if (it == ']') nestLevel-- else if (it == ',' && nestLevel == 0) return@indexOfFirst true false } return Pair(parseSnailFish(inside.substring(0, index)), parseSnailFish(inside.substring(index + 1))) .also { it.childsParent(it) } } sealed class SnailFishNumber(var parent: Pair? = null) { operator fun plus(other: SnailFishNumber): SnailFishNumber = Pair(this, other).also { it.childsParent(it) }.reduce() abstract fun print() abstract fun magnitude(): Int fun copy(): SnailFishNumber { return when(this) { is Pair -> Pair(this.left.copy(), this.right.copy()).also { it.childsParent(it) } is Regular -> Regular(this.value) } } protected fun reduce(): SnailFishNumber { while (true) { // this.print() // println() val exploding = findExploding() if (exploding != null) { exploding.explode() continue } val splitting = findSplitting() if (splitting != null) { splitting.split() continue } break } return this } private fun findExploding(nestLevel: Int = 0): Pair? { if (this is Pair) { if (nestLevel == 4) return this return this.left.findExploding( nestLevel + 1) ?: this.right.findExploding(nestLevel + 1) } return null } private fun findSplitting(): Regular? { return when (this) { is Regular -> if (this.value >= 10) this else null is Pair -> this.left.findSplitting() ?: this.right.findSplitting() } } } class Regular(var value: Int, parent: Pair? = null) : SnailFishNumber(parent) { override fun magnitude(): Int = value override fun print() { print(value) } fun add(addition: Int) { value += addition } fun split() { val newValue = Pair(Regular(value / 2), Regular(value / 2 + value % 2), parent) .also { it.childsParent(it) } if (parent != null) { if (parent!!.left == this) { parent!!.left = newValue } else { parent!!.right = newValue } } } } class Pair(var left: SnailFishNumber, var right: SnailFishNumber, parent: Pair? = null) : SnailFishNumber(parent) { override fun magnitude(): Int = 3 * left.magnitude() + 2 * right.magnitude() override fun print() { print("[");left.print();print(",");right.print();print("]") } fun explode() { findClosestLeftRegular()?.add((left as Regular).value) findClosestRightRegular()?.add((right as Regular).value) if (parent != null) { val newValue = Regular(0, parent) if (parent!!.left == this) { parent!!.left = newValue } else { parent!!.right = newValue } } } private fun findClosestLeftRegular(): Regular? { return if (parent != null) { if (parent!!.left == this) { parent!!.findClosestLeftRegular() } else { when (parent!!.left) { is Regular -> parent!!.left as Regular is Pair -> { return (parent!!.left as Pair).findRightMostChild() } } } } else { null } } private fun findRightMostChild(): Regular = when (this.right) { is Regular -> this.right as Regular else -> (this.right as Pair).findRightMostChild() } private fun findClosestRightRegular(): Regular? { return if (parent != null) { if (parent!!.right == this) { parent!!.findClosestRightRegular() } else { when (parent!!.right) { is Regular -> parent!!.right as Regular is Pair -> { return (parent!!.right as Pair).findLeftMostChild() } } } } else { null } } private fun findLeftMostChild(): Regular = when (this.left) { is Regular -> this.left as Regular else -> (this.left as Pair).findLeftMostChild() } fun childsParent(parent: Pair?) { left.parent = parent right.parent = parent } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day18/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day18.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day20/solution.kt
package day20 import java.io.File fun main() { val lines = File("src/main/kotlin/day20/input.txt").readLines() val imageEnhancementAlgorithm: BooleanArray = lines[0].map { it == '#' }.toBooleanArray() val imageYSize = lines.size + 2 val imageXSize = lines[2].length + 4 val image = InfiniteImage( Array(imageYSize) { i -> if (i in (0..1) || i in (imageYSize - 2 until imageYSize)) { BooleanArray(imageXSize) } else { (".." + lines[i] + "..").map { it == '#' }.toBooleanArray() } }, false ) val enhancedImage = (0..1).fold(image) { acc, _ -> enhanceImage(acc, imageEnhancementAlgorithm) } println(enhancedImage.innerData.sumOf { imageLine -> imageLine.count { it } }) val enhancedImage2 = (0..49).fold(image) { acc, _ -> enhanceImage(acc, imageEnhancementAlgorithm) } println(enhancedImage2.innerData.sumOf { imageLine -> imageLine.count { it } }) } fun enhanceImage(image: InfiniteImage, imageEnhancementAlgorithm: BooleanArray): InfiniteImage { val imageYResolution = image.innerData.size + 2 val imageXResolution = image.innerData[0].size + 2 val newOuterPixelValue = image.outerPixelValue.not() val newInnerData = Array(imageYResolution) { y -> if (y in (0..1) || y in (imageYResolution - 2 until imageYResolution)) { BooleanArray(imageXResolution) { newOuterPixelValue } } else { BooleanArray(imageXResolution) { x -> if (x in (0..1) || x in (imageXResolution - 2 until imageXResolution)) { newOuterPixelValue } else { val pixelValueArray = BooleanArray(9) pixelValueArray[0] = image.innerData[y - 2][x - 2] pixelValueArray[1] = image.innerData[y - 2][x - 1] pixelValueArray[2] = image.innerData[y - 2][x] pixelValueArray[3] = image.innerData[y - 1][x - 2] pixelValueArray[4] = image.innerData[y - 1][x - 1] pixelValueArray[5] = image.innerData[y - 1][x] pixelValueArray[6] = image.innerData[y][x - 2] pixelValueArray[7] = image.innerData[y][x - 1] pixelValueArray[8] = image.innerData[y][x] imageEnhancementAlgorithm[pixelValueArray.toInt()] } } } } return InfiniteImage( newInnerData, newOuterPixelValue ) } fun BooleanArray.toInt(): Int = this.map { if (it) 1 else 0 }.joinToString("").toInt(2) data class InfiniteImage(val innerData: Array<BooleanArray>, val outerPixelValue: Boolean)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day20/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day20.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day16/solution.kt
package day16 import java.io.File fun main() { val lines = File("src/main/kotlin/day16/input.txt").readLines() val bitsIterator = lines.first().map { hexToBinary(it) }.joinToString(separator = "").iterator() val packet = Packet.parse(bitsIterator) println(packet.versionAggregate()) println(packet.evaluate()) } sealed class Packet(val version: Int) { abstract fun versionAggregate(): Int abstract fun evaluate(): Long class Literal(version: Int, val value: Long) : Packet(version) { override fun versionAggregate() = version override fun evaluate(): Long = value companion object { fun parse(version: Int, iterator: CharIterator): Literal { var lastBitChunk = false var numberBits = "" while (!lastBitChunk) { lastBitChunk = iterator.take(1) == "0" numberBits += iterator.take(4) } return Literal(version, numberBits.toLong(2)) } } } class Operator(version: Int, val type: Int, val subPackets: List<Packet>) : Packet(version) { override fun versionAggregate(): Int = version + subPackets.sumOf { it.versionAggregate() } override fun evaluate(): Long = when (type) { 0 -> subPackets.sumOf { it.evaluate() } 1 -> subPackets.fold(1L) { acc, packet -> acc * packet.evaluate() } 2 -> subPackets.minOf { it.evaluate() } 3 -> subPackets.maxOf { it.evaluate() } 5 -> if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1 else 0 6 -> if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1 else 0 7 -> if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1 else 0 else -> 0L } companion object { fun parse(version: Int, type: Int, iterator: CharIterator): Operator { val lengthType = iterator.take(1) return when (lengthType) { "0" -> { val numberOfBits = iterator.take(15).toInt(2) val subPacketsIterator = iterator.take(numberOfBits).iterator() val packets = mutableListOf<Packet>() while (subPacketsIterator.hasNext()) { packets.add(parse(subPacketsIterator)) } Operator(version, type, packets) } else -> { val numberOfPackets = iterator.take(11).toInt(2) val packets = (1..numberOfPackets).map { parse(iterator) } Operator(version, type, packets) } } } } } companion object { fun parse(iterator: CharIterator): Packet { val version = iterator.take(3).toInt(2) val type = iterator.take(3).toInt(2) return when (type) { 4 -> Literal.parse(version, iterator) else -> Operator.parse(version, type, iterator) } } } } fun CharIterator.take(n: Int): String = this.asSequence().take(n).joinToString("") fun hexToBinary(hex: Char): String { return when (hex) { '0' -> "0000" '1' -> "0001" '2' -> "0010" '3' -> "0011" '4' -> "0100" '5' -> "0101" '6' -> "0110" '7' -> "0111" '8' -> "1000" '9' -> "1001" 'A' -> "1010" 'B' -> "1011" 'C' -> "1100" 'D' -> "1101" 'E' -> "1110" 'F' -> "1111" else -> "" } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day16/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day16.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day11/solution.kt
package day11 import java.io.File fun main() { val lines = File("src/main/kotlin/day11/input.txt").readLines() val mapSize = lines.size val energyLevelsMap: Array<IntArray> = Array(mapSize) { i -> lines[i].map { it.digitToInt() }.toIntArray() } val dumboOctopuses: MutableMap<Coordinate, DumboOctopus> = mutableMapOf() for (y in energyLevelsMap.indices) { for (x in energyLevelsMap[y].indices) { val coordinate = Coordinate(x, y) val dumboOctopus = DumboOctopus(coordinate, energyLevelsMap[y][x]) dumboOctopuses[coordinate] = dumboOctopus if (y > 0) dumboOctopuses.getValue(Coordinate(x, y - 1)).addAdjacent(dumboOctopus) if (x > 0) dumboOctopuses.getValue(Coordinate(x - 1, y)).addAdjacent(dumboOctopus) if (x > 0 && y > 0) dumboOctopuses.getValue(Coordinate(x - 1, y - 1)).addAdjacent(dumboOctopus) if (x < mapSize - 1 && y > 0) dumboOctopuses.getValue(Coordinate(x + 1, y - 1)).addAdjacent(dumboOctopus) } } var flashCount = 0 for (step in 1..100) { dumboOctopuses.values.forEach { it.increaseChargeLevel() } flashCount += dumboOctopuses.values.count { it.flash() } } println(flashCount) var stepAllFlashed = 100 var allFlashed = false while(!allFlashed) { stepAllFlashed++ dumboOctopuses.values.forEach { it.increaseChargeLevel() } allFlashed = dumboOctopuses.values.count { it.flash() } == dumboOctopuses.size } println(stepAllFlashed) } class DumboOctopus(val coordinate: Coordinate, var energyLevel: Int) { private val adjacents: MutableSet<DumboOctopus> = mutableSetOf() fun increaseChargeLevel() { energyLevel++ if (energyLevel == FLASH_ENERGY_LEVEL) { adjacents.forEach { it.increaseChargeLevel() } } } fun addAdjacent(adjacent: DumboOctopus) { if (adjacent !in adjacents) { adjacents.add(adjacent) adjacent.addAdjacent(this) } } fun flash(): Boolean { val charged = energyLevel >= FLASH_ENERGY_LEVEL if (charged) energyLevel = 0 return charged } companion object { const val FLASH_ENERGY_LEVEL = 10 } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DumboOctopus if (coordinate != other.coordinate) return false return true } override fun hashCode(): Int { return coordinate.hashCode() } override fun toString(): String { return "DumboOctopus(coordinate=$coordinate, chargeLevel=$energyLevel)" } } data class Coordinate(val x: Int, val y: Int)
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day11/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day11.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day10/solution.kt
package day10 import java.io.File val chunkPairs = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>', ) val illegalCharacterPoints = mapOf( ')' to 3, ']' to 57, '}' to 1197, '>' to 25137, ) val autocompleteCharacterPoints = mapOf( ')' to 1, ']' to 2, '}' to 3, '>' to 4, ) fun main() { val lines = File("src/main/kotlin/day10/input.txt").readLines() val autoCompletesByState = lines .map { it.toCharArray() } .map { autocomplete(it) } .partition { it.failed() } println(autoCompletesByState.first .mapNotNull { it.illegalChar } .mapNotNull { illegalCharacterPoints[it] } .sumOf { it } ) println(autoCompletesByState.second .mapNotNull { it.missedChars } .map { it.fold(0L) { acc, unit -> acc * 5 + (autocompleteCharacterPoints[unit] ?: 0) } } .sorted().let { it[it.size / 2] }) } fun autocomplete(line: CharArray): Autocomplete { val stack = ArrayDeque<Char>() for (char in line) { if (char in chunkPairs.keys) { stack.addLast(char) } else { stack.removeLastOrNull()?.let { if (chunkPairs[it] != char) { return Autocomplete(illegalChar = char) } } } } return Autocomplete(missedChars = stack.mapNotNull { chunkPairs[it] }.reversed()) } data class Autocomplete(val illegalChar: Char? = null, val missedChars: List<Char>? = null) { fun failed() = illegalChar != null }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day10/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day10.SolutionKt {\n private static final java.util.Map<java.lang.Character, java.lang.Character> chunkPairs;\n\n private static final java.util.Map<java.lang.Character, jav...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day17/solution.kt
package day17 import java.io.File import kotlin.math.abs import kotlin.math.round import kotlin.math.sqrt fun main() { val lines = File("src/main/kotlin/day17/input.txt").readLines() val (x1, x2) = lines.first().substringAfter("target area: x=").substringBefore(", y=").split("..") .map { it.toInt() } val (y1, y2) = lines.first().substringAfter("y=").split("..").map { it.toInt() } println(y1 * (y1 + 1) / 2) val maxSteps = abs(2*y1) val validSpeeds: MutableSet<Pair<Int, Int>> = mutableSetOf() for (steps in 1..maxSteps) { val minYSpeed = decrementalSpeed(y1, steps) val maxYSpeed = decrementalSpeed(y2, steps) val minXSpeed = decrementalSpeedWithFloor(x1, steps) val maxXSpeed = decrementalSpeedWithFloor(x2, steps) for (speedX in minXSpeed..maxXSpeed) { for (speedY in minYSpeed..maxYSpeed) { if (targetCoordinateY(speedY, steps) in y1..y2 && targetCoordinateX(speedX, steps) in x1..x2) { validSpeeds.add(speedX to speedY) } } } } println(validSpeeds.size) } fun targetCoordinateX(speed: Int, steps: Int): Int { val coefficient = minOf(speed, steps) return coefficient * speed - (coefficient - 1) * coefficient / 2 } fun targetCoordinateY(speed: Int, steps: Int): Int = steps * speed - (steps - 1) * steps / 2 fun decrementalSpeed(targetCoordinate: Int, steps: Int): Int = (targetCoordinate.toDouble() / steps + (steps - 1).toDouble() / 2).toInt() fun decrementalSpeedWithFloor(targetCoordinate: Int, steps: Int): Int { val minXSpeedToReachCoordinate = minXSpeedToReach(targetCoordinate) val speed = decrementalSpeed(targetCoordinate, steps) return if (steps > minXSpeedToReachCoordinate) minXSpeedToReachCoordinate else speed } fun minXSpeedToReach(targetCoordinate: Int): Int = round(sqrt((targetCoordinate * 8 + 1).toDouble()) / 2 - 0.5).toInt()
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day17/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day17.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #1...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day21/solution.kt
package day21 fun main() { val player1 = Player(4) val player2 = Player(3) val die = DeterministicDie() var roundNumber = 0 var losingPlayer: Player while (player1.score < 1000 && player2.score < 1000) { if (roundNumber % 2 == 0) { val score = die.roll() + die.roll() + die.roll() player1.addScore(score) } else { val score = die.roll() + die.roll() + die.roll() player2.addScore(score) } roundNumber++ } losingPlayer = if (player1.score >= 1000) { player2 } else { player1 } println(losingPlayer.score * die.numberOfRolls) val thrownValueToNumberOfUniverses = mapOf<Int, Long>( 3 to 1, 4 to 3, 5 to 6, 6 to 7, 7 to 6, 8 to 3, 9 to 1, ) val (player1WonUniverses, player2WonUniverses) = thrownValueToNumberOfUniverses.keys .map { playRound( true, it, 4, 0, 3, 0, 1, thrownValueToNumberOfUniverses ) } .reduce { p1, p2 -> p1.first + p2.first to p1.second + p2.second } println(maxOf(player1WonUniverses, player2WonUniverses)) } fun playRound( playsFirstPlayer: Boolean, thrownValue: Int, player1Position: Int, player1Score: Int, player2Position: Int, player2Score: Int, numberOfUniverses: Long, thrownValueToNumberOfUniverses: Map<Int, Long> ): Pair<Long, Long> { val newPlayer1Position: Int val newPlayer1Score: Int val newPlayer2Position: Int val newPlayer2Score: Int val newNumberOfUniverses: Long if (playsFirstPlayer) { newPlayer1Position = (player1Position + thrownValue - 1) % 10 + 1 newPlayer1Score = player1Score + newPlayer1Position newNumberOfUniverses = numberOfUniverses * thrownValueToNumberOfUniverses.getValue(thrownValue) newPlayer2Position = player2Position newPlayer2Score = player2Score if (newPlayer1Score >= 21) return newNumberOfUniverses to 0L } else { newPlayer2Position = (player2Position + thrownValue - 1) % 10 + 1 newPlayer2Score = player2Score + newPlayer2Position newNumberOfUniverses = numberOfUniverses * thrownValueToNumberOfUniverses.getValue(thrownValue) newPlayer1Position = player1Position newPlayer1Score = player1Score if (newPlayer2Score >= 21) return 0L to newNumberOfUniverses } return thrownValueToNumberOfUniverses.keys .map { playRound( !playsFirstPlayer, it, newPlayer1Position, newPlayer1Score, newPlayer2Position, newPlayer2Score, newNumberOfUniverses, thrownValueToNumberOfUniverses ) } .reduce { p1, p2 -> p1.first + p2.first to p1.second + p2.second} } data class Player(var position: Int) { var score: Int = 0 fun addScore(value: Int) { position = (position + value - 1) % 10 + 1 score += position } } data class DeterministicDie(var currentValue: Int = 0) { var numberOfRolls: Int = 0 fun roll(): Int { numberOfRolls++ return (++currentValue - 1) % 100 + 1 } }
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day21/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day21.SolutionKt {\n public static final void main();\n Code:\n 0: new #8 // class day21/Player\n 3: dup\n 4: iconst_4\n ...
bukajsytlos__aoc-2021__f47d092/src/main/kotlin/day19/solution.kt
package day19 import java.io.File import kotlin.math.abs fun main() { val unidentifiedScanners = mutableListOf<UnidentifiedScanner>() File("src/main/kotlin/day19/input.txt").useLines { linesSeq -> val linesIterator = linesSeq.iterator() while (linesIterator.hasNext()) { val scannerId = linesIterator.next().substringAfter("scanner ").substringBefore(" ---") val scannerBeacons = mutableListOf<Vector3D>() while (linesIterator.hasNext()) { val line = linesIterator.next() if (line.isEmpty()) break val (x, y, z) = line.split(",") scannerBeacons.add(Vector3D.from(end = Point3D(x.toInt(), y.toInt(), z.toInt()))) } unidentifiedScanners.add(UnidentifiedScanner(scannerId, scannerBeacons)) } } val identifiedScanners = mutableSetOf<IdentifiedScanner>() var baseScanner = unidentifiedScanners.removeAt(0).run { IdentifiedScanner(id, Point3D.CENTER, beaconVectors) } identifiedScanners.add(baseScanner) val testedScanners = mutableListOf(baseScanner) while (unidentifiedScanners.isNotEmpty()) { val baseScannerInterBeaconVectors = baseScanner.beaconVectors.eachVector() val unidentifiedScannersIterator = unidentifiedScanners.iterator() for (unidentifiedScanner in unidentifiedScannersIterator) { val unidentifiedScannerInterBeaconsVectors = unidentifiedScanner.beaconVectors.eachVector() val commonDistances = baseScannerInterBeaconVectors.keys .map { it.squaredLength() } .intersect(unidentifiedScannerInterBeaconsVectors.keys.map { it.squaredLength() }.toSet()) //scanner have at least 12 common beacons (12 inter beacon combinations == 66 (12 * 11 / 2)) if (commonDistances.size >= 66) { val commonDistance = commonDistances.first() val identifiedBeaconsForCommonDistance = baseScannerInterBeaconVectors .filter { it.key.squaredLength() == commonDistance } .entries.first() val unidentifiedBeaconsForCommonDistance = unidentifiedScannerInterBeaconsVectors .filter { it.key.squaredLength() == commonDistance } val scannerTransformation = TRANSFORMATIONS.first { transformation -> unidentifiedBeaconsForCommonDistance .map { it.key.transform(transformation) } .any { it == identifiedBeaconsForCommonDistance.key } } val unidentifiedBeaconVector = unidentifiedBeaconsForCommonDistance.entries.first { it.key.transform(scannerTransformation) == identifiedBeaconsForCommonDistance.key }.value.first val identifiedBeaconVector = identifiedBeaconsForCommonDistance.value.first val transformedBeaconVector = unidentifiedBeaconVector.transform(scannerTransformation) val scannerPositionShift = identifiedBeaconVector - transformedBeaconVector val identifiedScanner = IdentifiedScanner( unidentifiedScanner.id, baseScanner.position + scannerPositionShift, unidentifiedScanner.beaconVectors.map { it.transform(scannerTransformation) } ) identifiedScanners.add(identifiedScanner) unidentifiedScannersIterator.remove() } } testedScanners.add(baseScanner) baseScanner = identifiedScanners.first { it !in testedScanners } } println(identifiedScanners.flatMap { scanner -> scanner.beaconVectors.map { scanner.position + it } }.toSet().size) println(identifiedScanners.flatMap { identifiedScanner1 -> identifiedScanners.map { identifiedScanner2 -> identifiedScanner1.position.manhattanDistance(identifiedScanner2.position) } }.maxOrNull()) } fun List<Vector3D>.eachVector(): Map<Vector3D, Pair<Vector3D, Vector3D>> = buildMap { this@eachVector.forEach { v1 -> this@eachVector.forEach { v2 -> if (v1 != v2) { put(v2 - v1, v1 to v2) } } } } data class UnidentifiedScanner(val id: String, val beaconVectors: List<Vector3D>) data class IdentifiedScanner(val id: String, val position: Point3D, val beaconVectors: List<Vector3D>) data class Vector3D(val dx: Int, val dy: Int, val dz: Int) { operator fun plus(other: Vector3D) = Vector3D(dx + other.dx, dy + other.dy, dz + other.dz) operator fun minus(other: Vector3D) = Vector3D(dx - other.dx, dy - other.dy, dz - other.dz) fun squaredLength(): Int = dx * dx + dy * dy + dz * dz fun transform(matrix: Matrix3D): Vector3D = Vector3D( dx * matrix.m00 + dy * matrix.m01 + dz * matrix.m02, dx * matrix.m10 + dy * matrix.m11 + dz * matrix.m12, dx * matrix.m20 + dy * matrix.m21 + dz * matrix.m22 ) companion object { fun from(start: Point3D = Point3D.CENTER, end: Point3D): Vector3D = Vector3D(end.x - start.x, end.y - start.y, end.z - start.z) } } data class Matrix3D( val m00: Int, val m01: Int, val m02: Int, val m10: Int, val m11: Int, val m12: Int, val m20: Int, val m21: Int, val m22: Int ) data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(vector: Vector3D) = Point3D(x + vector.dx, y + vector.dy, z + vector.dz) operator fun minus(vector: Vector3D) = Point3D(x - vector.dx, y - vector.dy, z - vector.dz) fun manhattanDistance(other: Point3D) = abs(x - other.x) + abs(y - other.y) + abs(z - other.z) companion object { val CENTER = Point3D(0, 0, 0) } } val TRANSFORMATIONS: List<Matrix3D> = listOf( Matrix3D( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), Matrix3D( 1, 0, 0, 0, 0, -1, 0, 1, 0 ), Matrix3D( 1, 0, 0, 0, -1, 0, 0, 0, -1 ), Matrix3D( 1, 0, 0, 0, 0, 1, 0, -1, 0 ), Matrix3D( -1, 0, 0, 0, -1, 0, 0, 0, 1 ), Matrix3D( -1, 0, 0, 0, 0, -1, 0, -1, 0 ), Matrix3D( -1, 0, 0, 0, 1, 0, 0, 0, -1 ), Matrix3D( -1, 0, 0, 0, 0, 1, 0, 1, 0 ), Matrix3D( 0, -1, 0, 1, 0, 0, 0, 0, 1 ), Matrix3D( 0, 0, 1, 1, 0, 0, 0, 1, 0 ), Matrix3D( 0, 1, 0, 1, 0, 0, 0, 0, -1 ), Matrix3D( 0, 0, -1, 1, 0, 0, 0, -1, 0 ), Matrix3D( 0, 1, 0, -1, 0, 0, 0, 0, 1 ), Matrix3D( 0, 0, 1, -1, 0, 0, 0, -1, 0 ), Matrix3D( 0, -1, 0, -1, 0, 0, 0, 0, -1 ), Matrix3D( 0, 0, -1, -1, 0, 0, 0, 1, 0 ), Matrix3D( 0, 0, -1, 0, 1, 0, 1, 0, 0 ), Matrix3D( 0, 1, 0, 0, 0, 1, 1, 0, 0 ), Matrix3D( 0, 0, 1, 0, -1, 0, 1, 0, 0 ), Matrix3D( 0, -1, 0, 0, 0, -1, 1, 0, 0 ), Matrix3D( 0, 0, -1, 0, -1, 0, -1, 0, 0 ), Matrix3D( 0, -1, 0, 0, 0, 1, -1, 0, 0 ), Matrix3D( 0, 0, 1, 0, 1, 0, -1, 0, 0 ), Matrix3D( 0, 1, 0, 0, 0, -1, -1, 0, 0 ), )
[ { "class_path": "bukajsytlos__aoc-2021__f47d092/day19/SolutionKt.class", "javap": "Compiled from \"solution.kt\"\npublic final class day19.SolutionKt {\n private static final java.util.List<day19.Matrix3D> TRANSFORMATIONS;\n\n public static final void main();\n Code:\n 0: new #10 ...
TimothyEarley__rosetta-code-compiler__bb10aca/code-gen/src/main/kotlin/gen/CodeGen.kt
package gen import java.io.File import java.util.* import kotlin.math.abs fun main(args: Array<String>) { require(args.size == 1) { "Please pass a file as the first argument" } val source = File(args[0]).readText() println(gen(source)) } fun gen(input: String): String { val ast = readAST(input.lineSequence().filterNot(String::isBlank)) return (ast.compile() + "halt").print() } fun readAST(lines: Sequence<String>): AST { fun Sequence<String>.recurse(): Pair<AST, Sequence<String>> { val split = first().split("\\s+".toRegex(), 2) val (type, value) = if (split.size == 2) split else split + "" val tail = drop(1) return when (type) { ";" -> AST.EMPTY to tail in listOf( "Sequence", "Prts", "Prti", "Prtc", "Assign", "While", "Less", "LessEqual", "NotEqual", "Add", "Negate", "Greater", "Divide", "Multiply", "Mod", "If", //TODO check "Subtract" ) -> { val (first, firstLines) = tail.recurse() val (second, secondLines) = firstLines.recurse() AST.Binary(type, first, second) to secondLines } in listOf( "String", "Identifier", "Integer" ) -> AST.Terminal(type, value) to tail else -> error("Unknown type $type") } } return lines.recurse().also { (_, lines) -> require(lines.toList().isEmpty()) { "Not everything was parsed: ${lines.toList()}" } }.first } sealed class AST { object EMPTY : AST() data class Binary(val name: String, val left: AST, val right: AST): AST() data class Terminal(val name: String, val value: String): AST() } data class Instruction(val address: Int, var name: String) data class Assembly( val variables: Map<String, Int>, val constantStrings: List<String>, val code: List<Instruction> ) { val pc: Int get() = code.size fun print(): String = "Datasize: ${variables.size} Strings: ${constantStrings.size}\n" + (if (constantStrings.isNotEmpty()) constantStrings.joinToString(separator = "\n", postfix = "\n") else "") + code.joinToString(transform = { "%4d %-4s".format(it.address, it.name).trimEnd() }, separator = "\n") fun addConstantString(string: String): Assembly = if (constantStrings.contains(string)) this else this.copy(constantStrings = constantStrings + string) fun addVariable(string: String): Assembly = if (variables.contains(string)) this else this.copy(variables = variables + (string to variables.size)) operator fun plus(name: String): Assembly = this.copy( code = code + Instruction(code.size, name) ) } fun AST.compile(state: Assembly = Assembly(emptyMap(), emptyList(), emptyList())): Assembly = when(this) { AST.EMPTY -> state is AST.Binary -> when (name) { "Sequence" -> left.compile(state).let { right.compile(it) } //TODO merge all the cases of compiler right, compile left, do instruction "Prts" -> left.compile(state) + "prts" "Prti" -> left.compile(state) + "prti" "Prtc" -> left.compile(state) + "prtc" "Assign" -> (left as AST.Terminal).value.let { id -> right.compile(state).addVariable(id).let { it + "store [${it.variables[id]}]" } } "While" -> { val start = state.pc lateinit var jzPlaceholder: Instruction // test (left.compile(state) + // jz to end "jz placeholder" ).let { jzPlaceholder = it.code.last() // body right.compile(it) }.let { // jmp back jzPlaceholder.name = "jz ${jumpDescriptor(jzPlaceholder.address, it.pc + 1)}" it + "jmp ${jumpDescriptor(it.pc, start)}" } } "If" -> { lateinit var jzPlaceholder: Instruction (left.compile(state) + "jz placeholder").let { jzPlaceholder = it.code.last() val (_, ifBody, elseBody) = right as AST.Binary ifBody.compile(it).let { jzPlaceholder.name = "jz ${jumpDescriptor(jzPlaceholder.address, it.pc)}" it //TODO else } } } "Less" -> left.compile(state).let { right.compile(it) + "lt" } "LessEqual" -> left.compile(state).let { right.compile(it) + "le" } "Equal" -> left.compile(state).let { right.compile(it) + "eq" } "NotEqual" -> left.compile(state).let { right.compile(it) + "ne" } "Greater" -> left.compile(state).let { right.compile(it) + "gt" } "Add" -> left.compile(state).let { right.compile(it) + "add" } "Subtract" -> left.compile(state).let { right.compile(it) + "sub" } "Divide" -> left.compile(state).let { right.compile(it) + "div" } "Multiply" -> left.compile(state).let { right.compile(it) + "mul" } "Mod" -> left.compile(state).let { right.compile(it) + "mod" } "Negate" -> left.compile(state) + "neg" else -> TODO(name) } is AST.Terminal -> when(name) { "String" -> state.addConstantString(value).let { it + "push ${it.constantStrings.indexOf(value)}" } "Integer" -> state + "push $value" "Identifier" -> state + "fetch [${state.variables[value]}]" else -> TODO(this.toString()) } } private fun jumpDescriptor(from: Int, to: Int) = if (from > to) { "(${to - from + 1}) $to" } else { "(${to - from - 1}) $to" }
[ { "class_path": "TimothyEarley__rosetta-code-compiler__bb10aca/gen/CodeGenKt.class", "javap": "Compiled from \"CodeGen.kt\"\npublic final class gen.CodeGenKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...