kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
akshaybhongale__Largest-Sum-Contiguous-Subarray-Kotlin__e2de2c9/MaximumSubArray.kt
/** * Array Data Structure Problem * Largest Sum Contiguous Sub-array * Kotlin solution : * 1- Simple approach = time complexity O(n*n) where n is size of array * 2- kadane approach = time complexity O(n) where n is size of array */ class MaximumSubArray { companion object { @JvmStatic fun main(args: Array<String>) { val array = arrayOf(1, 3, 8, -2, 6, -8, 5) val simpleApproach = simpleApproach(array) val kadaneSolution = kadaneSolution(array) print("Maximum Sub array : simpleSolution $simpleApproach kadaneSolution $kadaneSolution") } private fun simpleApproach(array: Array<Int>): Int { var maximumSubArray = Int.MIN_VALUE for (i in array.indices) { var curSum = 0 for (j in i until array.size) { curSum += array[j] if (curSum > maximumSubArray) { maximumSubArray = curSum } }// end of j }// end of i return maximumSubArray } private fun kadaneSolution(array: Array<Int>): Int { var maximumSubArray = Int.MIN_VALUE var currentSum = 0 for (i in array.indices) { currentSum += array[i] if (currentSum > maximumSubArray) { maximumSubArray = currentSum } if (currentSum < 0) { currentSum = 0 } } return maximumSubArray } } }
[ { "class_path": "akshaybhongale__Largest-Sum-Contiguous-Subarray-Kotlin__e2de2c9/MaximumSubArray.class", "javap": "Compiled from \"MaximumSubArray.kt\"\npublic final class MaximumSubArray {\n public static final MaximumSubArray$Companion Companion;\n\n public MaximumSubArray();\n Code:\n 0: aload...
strouilhet__KeepCalmAndCode3__f779bf1/séance 1 et 2 _ classe et objet/correction/Complexe.kt
import kotlin.math.PI import kotlin.math.atan import kotlin.math.round import kotlin.math.sqrt class Complexe(val reel: Double = 0.0, val im: Double = 0.0) { constructor(c: Complexe) : this(c.reel, c.im) fun module(): Double = sqrt(reel * reel + im * im) fun argument(): Double = if (reel == 0.0) if (im >= 0) PI / 2 else -PI / 2 else atan(im / reel) fun add(z:Complexe): Complexe =Complexe(reel+z.reel, im+ z.im) fun mul(z:Complexe): Complexe = Complexe(reel*z.reel - im*z.im,reel*z.im + im*z.reel) /** * puissance * précondition n >=1 * @param n, puissance * @return puissance (Complexe) */ fun puissance(n:Int):Complexe { var r:Complexe=this for (i in 2..n) r=mul(r) return Complexe(round(r.reel), round(r.im)) } fun puissanceBis(n: Int): Complexe { var r = Complexe(1.0, 0.0) for (i in 0 until n) // n-1 compris r = r.mul(this) return r } /** * inverse du nombre complexe * précondition : this est non nul * @return inverse (Complexe) */ fun inverse(): Complexe =Complexe(reel / (reel * reel + im * im), -im / (reel * reel + im * im)) /** * division du nombre complexe par z * précondition : z non nul * @param z, diviseur * @return quotiont (Complexe) */ fun div(z: Complexe): Complexe = this.mul(z.inverse()) override fun toString(): String = "$reel + i $im" companion object { val I = Complexe(0.0, 1.0) val J = Complexe(-1 / 2.0, Math.sqrt(3.0) / 2) } } // question 1 --> avant l'ajout des getters /* class Complexe constructor(_reel:Double = 0.0, _im:Double= 0.0) { private val reel:Double=_reel private val im: Double=_im constructor(c:Complexe): this(c.reel, c.im) { } }*/
[ { "class_path": "strouilhet__KeepCalmAndCode3__f779bf1/Complexe.class", "javap": "Compiled from \"Complexe.kt\"\npublic final class Complexe {\n public static final Complexe$Companion Companion;\n\n private final double reel;\n\n private final double im;\n\n private static final Complexe I;\n\n private...
benjaminjkraft__aoc2017__e3ac356/day10.kt
fun doHash(lengths: List<Int>, n: Int, rounds: Int): Array<Int> { var pos = 0 var skip = 0 val list = Array(n, { it }) for (round in 0 until rounds) { for (i in lengths.indices) { val listAgain = list.copyOf() for (j in 0 until lengths[i]) { list[(pos + j) % n] = listAgain[(pos + lengths[i] - 1 - j) % n] } pos += lengths[i] + skip skip++; } } return list } fun firstProd(list: Array<Int>): Int { return list[0] * list[1] } fun denseHash(list: Array<Int>, n: Int): String { var output = "" val blockSize = list.size / n for (i in 0 until n) { val byte = list.slice(i * blockSize until (i + 1) * blockSize).reduce( { j, k -> j xor k }) output += byte.toString(16).padStart(2, '0') } return output } fun main(args: Array<String>) { val line = readLine()!! val extra = arrayOf(17, 31, 73, 47, 23) println(firstProd(doHash(line.split(",").map({ it.toInt() }), 256, 1))) println(denseHash(doHash(line.map({ it.toInt() }) + extra, 256, 64), 16)) }
[ { "class_path": "benjaminjkraft__aoc2017__e3ac356/Day10Kt.class", "javap": "Compiled from \"day10.kt\"\npublic final class Day10Kt {\n public static final java.lang.Integer[] doHash(java.util.List<java.lang.Integer>, int, int);\n Code:\n 0: aload_0\n 1: ldc #10 // S...
thuva4__Algorithms__7da835f/algorithms/Kotlin/QuickSort/QuickSort.kt
fun printArray(x: IntArray) { for (i in x.indices) print(x[i].toString() + " ") } fun IntArray.sort(low: Int = 0, high: Int = this.size - 1) { if (low >= high) return val middle = partition(low, high) sort(low, middle - 1) sort(middle + 1, high) } fun IntArray.partition(low: Int, high: Int): Int { val middle = low + (high - low) / 2 val a = this swap(a, middle, high) var storeIndex = low for (i in low until high) { if (a[i] < a[high]) { swap(a, storeIndex, i) storeIndex++ } } swap(a, high, storeIndex) return storeIndex } fun swap(a: IntArray, i: Int, j: Int) { val temp = a[i] a[i] = a[j] a[j] = temp } fun main(args: Array<String>) { println("Enter the number of elements :") val n = readLine()!!.toInt() val arr = IntArray(n) println("Enter the elements.") for (i in 0 until n) { arr[i] = readLine()!!.toInt() } println("Given array") printArray(arr) arr.sort() println("\nSorted array") printArray(arr) }
[ { "class_path": "thuva4__Algorithms__7da835f/QuickSortKt.class", "javap": "Compiled from \"QuickSort.kt\"\npublic final class QuickSortKt {\n public static final void printArray(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String x\n 3: invokestatic #15 ...
dlfelps__aoc-2022__3ebcc49/src/Day01.kt
import java.io.File fun main() { fun parseInput(input: String) : List<Int> { fun getNext(rest: List<Int?>): Pair<Int,List<Int?>> { val next = rest.takeWhile {it != null} as List<Int> val temp = rest.dropWhile {it != null} val rest = if (temp.isEmpty()) { temp } else { temp.drop(1) //drop null } return Pair(next.sum(), rest) } var rest = input.lines().map {it.toIntOrNull()} val sums = mutableListOf<Int>() while (rest.isNotEmpty()) { val (sum, temp) = getNext(rest) rest = temp sums.add(sum) } return sums } fun part1(input: String): Int { val data = parseInput(input) return data.max() } fun part2(input:String): Int { val data = parseInput(input) return data .sortedDescending() .take(3) .sum() } val input = File("src/Day01.txt").readText() println(part1(input)) println(part2(input)) }
[ { "class_path": "dlfelps__aoc-2022__3ebcc49/Day01Kt.class", "javap": "Compiled from \"Day01.kt\"\npublic final class Day01Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // Stri...
MisterTeatime__AoC2022__d684bd2/src/Utils.kt
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.absoluteValue /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') typealias Graph = Map<String, List<String>> typealias Path = List<String> typealias Fold = Pair<Char, Int> data class Point2D (var x: Int, var y: Int) { operator fun plus(inc: Point2D) = Point2D(x + inc.x, y + inc.y) operator fun minus(inc: Point2D) = Point2D(x - inc.x, y - inc.y) fun neighbors4(): List<Point2D> { val neighborPoints = listOf(Point2D(1,0), Point2D(0,1), Point2D(-1, 0), Point2D(0,-1)) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors8(): List<Point2D> { val neighborPoints = listOf( Point2D(1,0), Point2D(1,1), Point2D(0,1), Point2D(-1,1), Point2D(-1,0), Point2D(-1,-1), Point2D(0,-1), Point2D(1,-1) ) return neighborPoints.map { this + it }.sortedWith(Point2DComparator()) } fun neighbors4AndSelf(): List<Point2D> { val neighborPoints = neighbors4().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun neighbors8AndSelf(): List<Point2D> { val neighborPoints = neighbors8().toMutableList() neighborPoints.add(this) return neighborPoints.sortedWith(Point2DComparator()) } fun distanceTo(other: Point2D) = (this.x - other.x).absoluteValue + (this.y - other.y).absoluteValue class Point2DComparator: Comparator<Point2D> { override fun compare(p0: Point2D?, p1: Point2D?): Int { return if (p0 == null || p1 == null) 0 else { when { (p0.y > p1.y) -> 1 (p0.y < p1.y) -> -1 else -> { when { (p0.x > p1.x) -> 1 (p0.x < p1.x) -> -1 else -> 0 } } } } } } } class Line(coords: List<String>) { val start: Point2D val end: Point2D init { val startPoint = coords[0].split(",") val endPoint = coords[1].split(",") this.start = Point2D(startPoint[0].toInt(), startPoint[1].toInt()) this.end = Point2D(endPoint[0].toInt(), endPoint[1].toInt()) } fun isHorizontal() = start.y == end.y fun isVertical() = start.x == end.x fun contains(point: Point2D) = point.y == getYAt(point.x) fun getYAt(x: Int) = ((end.y - start.y)/(end.x - start.x)) * (x - start.x) + start.y fun getAllIntegerPoints(): List<Point2D> { return when { isHorizontal() -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, start.y) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, start.y) } } } isVertical() -> { when { (start.y < end.y) -> IntRange(start.y, end.y).map{ p -> Point2D(start.x, p) } else -> IntRange(end.y, start.y).map { p -> Point2D(start.x, p) } } } else -> { when { (start.x < end.x) -> IntRange(start.x, end.x).map{ p -> Point2D(p, getYAt(p)) } else -> IntRange(end.x, start.x).map{ p -> Point2D(p, getYAt(p)) } } } } } override fun toString(): String { return "(${start.x}, ${start.y}) -> (${end.x}, ${end.y})" } } class MyStack<E>(vararg items: E): Collection<E> { private val elements = items.toMutableList() fun push(element: E) = elements.add(element) fun peek(): E = elements.last() fun pop(): E = elements.removeAt(elements.size-1) override fun isEmpty() = elements.isEmpty() override fun contains(element: E) = elements.contains(element) override fun containsAll(elements: Collection<E>) = elements.containsAll(elements) override fun toString() = "Stack(${elements.joinToString()})" override fun iterator() = elements.iterator() override val size: Int get() = elements.size } data class Area<T>(var points: List<MutableList<T>>) { fun at(p: Point2D): T? { return points.getOrElse(p.y) { listOf() }.getOrNull(p.x) } fun setValue(p: Point2D, v: T) { if (at(p) != null) points[p.y][p.x] = v } companion object Factory { fun toIntArea(input: List<String>): Area<Int> { return Area(input.map { it.map { ch -> ch.toString().toInt() }.toMutableList() }) } fun toBinaryArea(input: List<String>, one: Char, zero: Char): Area<Int> { return Area(input.map { it.map { c -> when (c) { one -> 1 zero -> 0 else -> 0 } }.toMutableList() }) } } } data class Point3D(val x: Int, val y: Int, val z: Int) { operator fun plus(inc: Point3D) = Point3D(x + inc.x, y + inc.y, z + inc.z) operator fun minus(inc: Point3D) = Point3D(x - inc.x, y - inc.y, z - inc.z) } fun <T> List<T>.partitionGroups(divider: T): List<List<T>> { var startIndex = 0 val result = mutableListOf<List<T>>() this.forEachIndexed { index, t -> if (t == divider) { result.add(this.subList(startIndex, index)) startIndex = index + 1 } } if (startIndex < this.size) result.add(this.subList(startIndex, this.size)) return result }
[ { "class_path": "MisterTeatime__AoC2022__d684bd2/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name\n...
UlrichBerntien__Codewars-Katas__034d7f2/6_kyu/Playing_with_digits.kt
/** Power function for integers */ fun Int.pow(exp: Int): Long { return this.toBigInteger().pow(exp).toLong() } /** * Sum decimal digits with power. * * @param x Calculate the digit powerd sum of this int. * @param p The exponent of the most significant digit. * @return sum of all decimal digits with power p,p+1,.. */ fun digitSum(x: Int, p: Int): Long { var digits = IntArray(32) assert( 10.pow(digits.size) > Int.MAX_VALUE.toLong() ) var nDigits = 0 var rest = x while (rest > 0) { digits[nDigits] = rest % 10 rest /= 10 nDigits++ } var sum: Long = 0 for (i in 0..nDigits - 1) { sum += digits[i].pow(p + nDigits - i - 1) } return sum } /** * Calculates funny integer. * * @param n Integer to analyse. * @param p exponent of the most significant digit in the sum. * @return k with k*n = powered decimal digit sum of n. */ fun digPow(n: Int, p: Int): Int { val s = digitSum(n, p) return if (s % n == 0L) (s / n).toInt() else -1 }
[ { "class_path": "UlrichBerntien__Codewars-Katas__034d7f2/Playing_with_digitsKt.class", "javap": "Compiled from \"Playing_with_digits.kt\"\npublic final class Playing_with_digitsKt {\n public static final long pow(int, int);\n Code:\n 0: iload_0\n 1: i2l\n 2: invokestatic #12 ...
UlrichBerntien__Codewars-Katas__034d7f2/4_kyu/The_observed_PIN.kt
/** * Generates all possible PINs based on the observed PIN. The true PIN is around the observed PIN. * Each key could be also the key around the observed key. * * @param The observed PIN. * @return All possible PINs. */ fun getPINs(observed: String): List<String> = when (observed.length) { 0 -> emptyList() 1 -> keyNeighbours[observed[0]]!!.map { it.toString() } else -> { var accu = emptyList<String>() val lhs = keyNeighbours[observed[0]]!! getPINs(observed.substring(1)).forEach { rhs -> lhs.forEach { it -> accu += it + rhs } } accu } } /** * Map from observed key to all possible input kyes. Maps to an empty array if the key is not on the * keypad. */ private val keyNeighbours: Map<Char, CharArray> = generateKeyNeighbours("123,456,789, 0 ") /** * Generates the map from observed key to possible keys. * * @param layout The layout of the keypad. Rows of the key pad are separated by comma. * @return Map observerd key -> possible keys. */ private fun generateKeyNeighbours(layout: String): Map<Char, CharArray> { var accu = HashMap<Char, CharArray>().withDefault { CharArray(0) } val keys: Array<String> = layout.split(',').toTypedArray() fun getKey(x: Int, y: Int): Char? = if (y in keys.indices && x in keys[y].indices && keys[y][x] != ' ') keys[y][x] else null for (row in keys.indices) for (col in keys[row].indices) getKey(col, row)?.let { k -> var options = emptyList<Char>() listOf(Pair(0, +1), Pair(0, -1), Pair(+1, 0), Pair(-1, 0), Pair(0, 0)).forEach { (x, y) -> getKey(col + x, row + y)?.let { options += it } } accu[k] = options.toCharArray() } return accu }
[ { "class_path": "UlrichBerntien__Codewars-Katas__034d7f2/The_observed_PINKt.class", "javap": "Compiled from \"The_observed_PIN.kt\"\npublic final class The_observed_PINKt {\n private static final java.util.Map<java.lang.Character, char[]> keyNeighbours;\n\n public static final java.util.List<java.lang.Str...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/LargestPalindromicNumber.kt
/** * # Largest Palindromic Number * Problem: * https://leetcode.com/problems/largest-palindromic-number/ */ class LargestPalindromicNumber { fun largestPalindromic(num: String): String { val digits = intArrayOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) for (c in num) { val digit = c.digitToInt() digits[digit] += 1 } val available = digits.mapIndexed { digit, count -> digit to count }.filter { (_, count) -> count > 0 }.sortedWith { (digit1, count1), (digit2, count2) -> /** * Returns zero if the arguments are equal, * a negative number if the first argument is less than the second, * or a positive number if the first argument is greater than the second. */ val oneRank = (if (count1 > 1) 100 else 0) + digit1 val twoRank = (if (count2 > 1) 100 else 0) + digit2 twoRank - oneRank// sort descending } val mirror = mirror(available) val palindrome = palindrome(mirror) // Filter leading 0's return if (palindrome.first() == '0') { palindrome.replace("0", "").takeIf { it.isNotEmpty() } ?: "0" } else palindrome } private fun palindrome(mirror: Pair<String, String?>): String { val (str, left) = mirror return if (left != null) str + left + str.reversed() else str + str.reversed() } private fun mirror(available: List<Pair<Int, Int>>): Pair<String, String?> { fun biggestLeftover(currentDigit: Int, secondLeft: String?): Int { val secondLeftSafe = secondLeft?.toInt() ?: 0 val next = available.getOrNull(1)?.first ?: return maxOf(currentDigit, secondLeftSafe) return if (next > currentDigit) { maxOf(next, secondLeftSafe) } else maxOf(currentDigit, secondLeftSafe) } if (available.isEmpty()) return "" to null val (digit, count) = available.first() return if (count.isEven()) { val first = digit.toString().repeat(count / 2) val (secondStr, secondLeft) = mirror(available.drop(1)) first + secondStr to secondLeft } else { if (count > 1) { // not even; count >= 3 val first = digit.toString().repeat((count - 1) / 2) val (secondStr, secondLeft) = mirror(available.drop(1)) first + secondStr to biggestLeftover( currentDigit = digit, secondLeft = secondLeft ).toString() } else { // count = 1 "" to digit.toString() } } } private fun Int.isEven(): Boolean = this % 2 == 0 }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/LargestPalindromicNumber.class", "javap": "Compiled from \"LargestPalindromicNumber.kt\"\npublic final class LargestPalindromicNumber {\n public LargestPalindromicNumber();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Met...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/NextClosestTime.kt
fun main() { val sut = NextClosestTime() for (h in 0..23) { val hour = if (h < 10) "0$h" else h.toString() for (m in 0..59) { val minute = if (m < 10) "0$m" else m.toString() val time = "$hour:$minute" println("\"$time\" -> \"${sut.nextClosestTime(time)}\"") } } } class NextClosestTime { fun nextClosestTime(time: String): String { val digits = mutableSetOf<Int>() digits.add(time[0].digitToInt()) digits.add(time[1].digitToInt()) digits.add(time[3].digitToInt()) digits.add(time[4].digitToInt()) val sortedDigits = digits.sorted() val hour = String(charArrayOf(time[0], time[1])) val minute = String(charArrayOf(time[3], time[4])) val minuteInt = minute.toInt() val hasZero: Boolean = sortedDigits.first() == 0 return tryNextMinute( sortedDigits = sortedDigits, hour = hour, minute = minute, minuteInt = minuteInt, hasZero = hasZero ) ?: tryNextHorWithMinimizedMin( sortedDigits = sortedDigits, hour = hour, hasZero = hasZero ) ?: minimizeTime(sortedDigits) } private fun tryNextMinute( sortedDigits: List<Int>, hour: String, minute: String, minuteInt: Int, hasZero: Boolean ): String? { if (minute == "59") return null for (i in sortedDigits.indices) { val digit1 = sortedDigits[i] if (hasZero) { // try single digit if (digit1 > minuteInt) return "$hour:0$digit1" } for (j in sortedDigits.indices) { val digit2 = sortedDigits[j] val newMinute = validMinute(digit1, digit2) if (newMinute != null && newMinute > minuteInt) return "$hour:${format(newMinute)}" } } return null } private fun tryNextHorWithMinimizedMin( sortedDigits: List<Int>, hour: String, hasZero: Boolean ): String? { fun minimizedMin(): String = sortedDigits.first().run { if (hasZero) "0$this" else "$this$this" } if (hour == "23") return null val hourInt = hour.toInt() for (i in sortedDigits.indices) { val digit1 = sortedDigits[i] if (hasZero) { // try single digit if (digit1 > hourInt) return "0$digit1:${minimizedMin()}" } for (j in sortedDigits.indices) { val digit2 = sortedDigits[j] val newHour = validHour(digit1, digit2) if (newHour != null && newHour > hourInt) return "${format(newHour)}:${minimizedMin()}" } } return null } private fun minimizeTime( sortedDigits: List<Int> ): String { val first = sortedDigits.first() return "$first$first:$first$first" } private fun format(newNumber: Int): String = if (newNumber < 10) "0$newNumber" else newNumber.toString() private fun validHour(digit1: Int, digit2: Int): Int? { val newHour = digit1 * 10 + digit2 return newHour.takeIf { it in 0..23 } } private fun validMinute(digit1: Int, digit2: Int): Int? { val newMinute = digit1 * 10 + digit2 return newMinute.takeIf { it in 0..59 } } /** * LeetCode compatibility */ private fun Char.digitToInt(): Int = this.toInt() - '0'.toInt() }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/NextClosestTimeKt.class", "javap": "Compiled from \"NextClosestTime.kt\"\npublic final class NextClosestTimeKt {\n public static final void main();\n Code:\n 0: new #8 // class NextClosestTime\n 3: dup\n 4:...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/MinimumAreaRectangle.kt
import kotlin.math.pow import kotlin.math.sqrt typealias Point = IntArray /** * # Minimum Area Rectangle * * _Note: Time Limit Exceeded (not optimal)_ * * Problem: * https://leetcode.com/problems/minimum-area-rectangle/ */ class MinimumAreaRectangle { fun minAreaRect(points: Array<Point>): Int { var minArea: Int? = null chooseFourUnique(points) { a, b, c, d -> if (parallel(a, b, c, d) && rectangle(a, b, c, d)) { println("rect: ${a.toList()}, ${b.toList()}, ${c.toList()}, ${d.toList()}") val area = area(a, b, c, d) minArea = minArea?.let { minOf(it, area) } ?: area } } return minArea ?: 0 } private inline fun chooseFourUnique( points: Array<Point>, block: (Point, Point, Point, Point) -> Unit ) { for (a in points) { for (b in points) { if (a sameAs b) continue for (c in points) { if (a sameAs c || b sameAs c) continue for (d in points) { if (a sameAs d || b sameAs d || c sameAs d) continue block(a, b, c, d) } } } } } private infix fun Point.sameAs(other: Point): Boolean = x() == other.x() && y() == other.y() private fun area( a: Point, b: Point, c: Point, d: Point ): Int { val minX = minOf(a.x(), b.x(), c.x(), d.x()) val maxX = maxOf(a.x(), b.x(), c.x(), d.x()) val minY = minOf(a.y(), b.y(), c.y(), d.y()) val maxY = maxOf(a.y(), b.y(), c.y(), d.y()) return (maxX - minX) * (maxY - minY) } private fun parallel( a: Point, b: Point, c: Point, d: Point, ): Boolean { val points = arrayOf(a, b, c, d) if (points.map { it.x() }.toSet().size > 2) return false if (points.map { it.y() }.toSet().size > 2) return false return true } /** * Conditions for rectangle: * - distance(a,b) == distance(c,d) * - distance(a,c) == distance(b,d) * - distance(a,d) == distance(b,c) * * @return whether four points form an rectangle, note: it might be rotated */ private fun rectangle( a: Point, b: Point, c: Point, d: Point ): Boolean = distance(a, b) == distance(c, d) && distance(a, c) == distance(b, d) && distance(a, d) == distance(b, c) /** * Formula: * d=√((x2 – x1)² + (y2 – y1)²) */ private fun distance(p1: Point, p2: Point): Double = sqrt( (p1.x().toDouble() - p2.x()).pow(2.0) + (p1.y().toDouble() - p2.y()).pow(2.0) ) private fun IntArray.x() = this[0] private fun IntArray.y() = this[1] }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/MinimumAreaRectangleKt.class", "javap": "Compiled from \"MinimumAreaRectangle.kt\"\npublic final class MinimumAreaRectangleKt {\n}\n", "javap_err": "" }, { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/MinimumAreaRectangle.class", "ja...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/AllWaysToMakeChange.kt
fun numberOfWaysToMakeChange(n: Int, denoms: List<Int>): Int { // Write your code here. println("----------- CASE: n = $n, denoms = $denoms ----------------") val allWays = ways( n = n, ds = denoms, ) println("All ways: $allWays") val uniqueWays = allWays.map { it.sorted() }.toSet() println("Unique ways: $uniqueWays") println("------------- END CASE ---------------") return uniqueWays.size } /* n = 3, denoms = [1,2] ways(3) = ways(1) + ways(2) */ fun ways( n: Int, ds: List<Int>, ways: List<Int> = emptyList() ): List<List<Int>> { if (n < 0) return emptyList() if (n == 0) return listOf(ways) val validDs = ds.filter { it <= n } return validDs.foldRight(initial = emptyList()) { d, allWays -> ways(n = n - d, ways = ways + d, ds = validDs) + allWays } }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/AllWaysToMakeChangeKt.class", "javap": "Compiled from \"AllWaysToMakeChange.kt\"\npublic final class AllWaysToMakeChangeKt {\n public static final int numberOfWaysToMakeChange(int, java.util.List<java.lang.Integer>);\n Code:\n 0: aload_1\n ...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/PermutationInString.kt
/** * # 567. Permutation in String * Problem: * https://leetcode.com/problems/permutation-in-string/ * * WARNING: This solution is not optimal! */ class PermutationInString { fun checkInclusion(target: String, source: String): Boolean { if (target.length > source.length) return false return permuteFind(target) { source.contains(it) } } private fun permuteFind( arr: String, n: Int = arr.length, k: Int = 0, find: (String) -> Boolean ): Boolean { if (k == n - 1) { return find(arr) } for (i in k until n) { val newArr = arr.swap(k, i) if (i != k && arr == newArr) continue if (permuteFind(arr = newArr, n = n, k = k + 1, find = find)) { return true } } return false } private fun String.swap(i: Int, j: Int): String { if (i == j) return this val arr = this.toCharArray() val temp = arr[i] arr[i] = arr[j] arr[j] = temp return arr.concatToString() } }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/PermutationInString.class", "javap": "Compiled from \"PermutationInString.kt\"\npublic final class PermutationInString {\n public PermutationInString();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/MaxSubArray.kt
/** * # Maximum Subarray * Problem: * https://leetcode.com/problems/maximum-subarray/ */ class MaxSubArray { fun maxSubArray(nums: IntArray): Int { val size = nums.size if (size == 1) return nums[0] var sum = nums.first() var localMax = sum for (i in 1 until size) { val n = nums[i] when { n > 0 -> if (sum > 0) { // n(+) + sum(+) => continue the sum: n + sum sum += n } else { // n(+) + sum(-) => reset to n(+) sum = n } else -> { if (sum > 0) { // n(-) + sum(+) => we can't know if we should reset the sum, // because we can't predict the next numbers coming // => 1) remember local max; 2) continue the sum; localMax = maxOf(localMax, sum) sum += n } else { // sum(-) if (n > sum) { // n(-) is better than sum(-) => reset the sum to n(-) sum = n } else { // n(-) is worse than sum(-) but we can't predict the future // => 1) remember local max; 2) continue the sum; localMax = maxOf(localMax, sum) sum += n } } } } } return maxOf(localMax, sum) } }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/MaxSubArray.class", "javap": "Compiled from \"MaxSubArray.kt\"\npublic final class MaxSubArray {\n public MaxSubArray();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: retur...
ILIYANGERMANOV__algorithms__4abe4b5/Algorithms/src/main/kotlin/Search2DMatrix.kt
/** * # Search a 2D Matrix * Problem: * https://leetcode.com/problems/search-a-2d-matrix/ */ class Search2DMatrix { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { val rowsCount = matrix.size if (rowsCount == 1) return binarySearchRow(matrix[0], target) return binarySearchMatrix( matrix = matrix, target = target, lowIndex = 0, highIndex = rowsCount - 1 ) } private fun binarySearchMatrix( matrix: Array<IntArray>, target: Int, lowIndex: Int, highIndex: Int ): Boolean { if (lowIndex > highIndex) return false val mid = (lowIndex + highIndex) / 2 val row = matrix[mid] val rowFirst = row[0] val rowLast = row.last() return when { target in rowFirst..rowLast -> binarySearchRow(row, target) target < rowLast -> // search lower row binarySearchMatrix( matrix = matrix, target = target, lowIndex = 0, highIndex = mid - 1 ) else -> // search higher row binarySearchMatrix( matrix = matrix, target = target, lowIndex = mid + 1, highIndex = highIndex ) } } private fun binarySearchRow( row: IntArray, target: Int, low: Int = 0, high: Int = row.size - 1 ): Boolean { if (low > high) return false val mid = (low + high) / 2 val midValue = row[mid] if (target == midValue) return true return if (target > midValue) { // search right binarySearchRow( row = row, target = target, low = mid + 1, high = high ) } else { // search left binarySearchRow( row = row, target = target, low = low, high = mid - 1 ) } } }
[ { "class_path": "ILIYANGERMANOV__algorithms__4abe4b5/Search2DMatrix.class", "javap": "Compiled from \"Search2DMatrix.kt\"\npublic final class Search2DMatrix {\n public Search2DMatrix();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Droplets.kt
fun main() = Droplets.solve() private object Droplets { fun solve() { val input = readInput() val droplet = Droplet(input) println("total surface area ${droplet.surfaceArea1()}") println("outside surface area ${droplet.surfaceArea2()}") } private fun readInput(): List<Pos> = generateSequence(::readLine).map { val parts = it.split(",").map { it.toInt(10) } Pos(parts[0], parts[1], parts[2]) }.toList() data class Pos(val x: Int, val y: Int, val z: Int) { fun sides() = listOf( Pos(x + 1, y, z), Pos(x - 1, y, z), Pos(x, y + 1, z), Pos(x, y - 1, z), Pos(x, y, z + 1), Pos(x, y, z - 1) ) } class Droplet(val points: List<Pos>) { fun surfaceArea1(): Int { var area = 0 val pointSet = points.toSet() for (point in points) { area += 6 - point.sides().count { pointSet.contains(it) } } // println("${joined.size} $area") return area } fun surfaceArea2(): Int { val minX = points.minOf { it.x } val maxX = points.maxOf { it.x } val minY = points.minOf { it.y } val maxY = points.maxOf { it.y } val minZ = points.minOf { it.z } val maxZ = points.maxOf { it.z } val xRange = (minX - 1)..(maxX + 1) val yRange = (minY - 1)..(maxY + 1) val zRange = (minZ - 1)..(maxZ + 1) println("$xRange $yRange $zRange") val outsideCells = mutableSetOf<Pos>() val pointsSet = points.toSet() val q = mutableListOf(Pos(xRange.start, yRange.start, zRange.start)) while (q.isNotEmpty()) { val cell = q.removeFirst() if (cell in pointsSet || cell in outsideCells) { continue } outsideCells.add(cell) q.addAll(cell.sides().filter { it.x in xRange && it.y in yRange && it.z in zRange }) } var result = 0 for (point in pointsSet) { result += point.sides().count { it in outsideCells } } return result } } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/DropletsKt.class", "javap": "Compiled from \"Droplets.kt\"\npublic final class DropletsKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field Droplets.INSTANCE:LDroplets;\n 3: invokevirtual #15 ...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Sand.kt
fun main() = Sand.solve() private object Sand { fun solve() { val input = readInput() val (grid, start) = inputToGrid(input) drawGrid(grid) println("Start: $start") drawGrid(addSand(grid, start)) } private fun addSand(grid: List<MutableList<Cell>>, start: Pos): List<List<Cell>> { val result = grid.map { it.toMutableList() } fun nextPos(pos: Pos): Pos? { val variants = listOf( Pos(pos.x, pos.y + 1), Pos(pos.x - 1, pos.y + 1), Pos(pos.x + 1, pos.y + 1) ) for (variant in variants) { if (variant.y >= result.size) { return null } if (variant.x < 0 || variant.x >= result.first().size) { return null } if (result[variant.y][variant.x] == Cell.Empty) { return variant } } return pos } fun percolate(): Boolean { var pos = start while (true) { val next = nextPos(pos) ?: return false if (next == pos) { result[pos.y][pos.x] = Cell.Sand return pos != start } pos = next } } var iterations = 1 while (percolate()) { iterations += 1 } println("Iterations: $iterations") return result } private fun readInput(): List<List<Pos>> { return generateSequence(::readLine).map { it.splitToSequence(" -> ").map { val parts = it.split(",") Pos(parts[0].toInt(10), parts[1].toInt(10)) }.toList() }.toList() } private fun inputToGrid(input: List<List<Pos>>): Pair<List<MutableList<Cell>>, Pos> { val start = Pos(500, 0) val positions = input.flatten() val minX = minOf(start.x, positions.map { it.x }.min()) - 200 val maxX = maxOf(start.x, positions.map { it.x }.max()) + 200 val minY = minOf(start.y, positions.map { it.y }.min()) val maxY = maxOf(start.y, positions.map { it.y }.max()) + 2 println("$minX $maxX $minY $maxY") val result = mutableListOf<MutableList<Cell>>() for (y in minY..maxY) { val line = mutableListOf<Cell>() for (x in minX..maxX) { line.add(Cell.Empty) } result.add(line) } fun fillWithRock(grid: List<MutableList<Cell>>, from: Pos, to: Pos) { // println("$from $to") if (from.x != to.x) { val src = Pos(minOf(from.x, to.x), from.y) val dst = Pos(maxOf(from.x, to.x), from.y) for (x in src.x..dst.x) { grid[src.y - minY][x - minX] = Cell.Rock } } else { val src = Pos(from.x, minOf(from.y, to.y)) val dst = Pos(from.x, maxOf(from.y, to.y)) for (y in src.y..dst.y) { grid[y - minY][src.x - minX] = Cell.Rock } } } for (rock in input) { val points = rock.toMutableList() var from = points.removeFirst() while (!points.isEmpty()) { val to = points.removeFirst() fillWithRock(result, from, to) from = to } } fillWithRock(result, Pos(minX, maxY), Pos(maxX, maxY)) return Pair(result, Pos(start.x - minX, start.y - minY)) } private fun drawGrid(grid: List<List<Cell>>) { for (line in grid) { println(line.map { when (it) { Cell.Empty -> '.' Cell.Rock -> '#' Cell.Sand -> 'o' } }.joinToString("")) } } enum class Cell { Empty, Rock, Sand, } data class Pos(val x: Int, val y: Int) : Comparable<Pos> { override fun compareTo(other: Pos): Int { val cmpX = x.compareTo(other.x) if (cmpX != 0) { return cmpX } val cmpY = y.compareTo(other.y) if (cmpY != 0) { return cmpY } return 0 } } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Sand$Pos.class", "javap": "Compiled from \"Sand.kt\"\npublic final class Sand$Pos implements java.lang.Comparable<Sand$Pos> {\n private final int x;\n\n private final int y;\n\n public Sand$Pos(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Path.kt
fun main() = Path.solve() private typealias Matrix = List<List<Int>> private object Path { const val START = 0 const val TARGET = ('z'.code - 'a'.code) + 1 fun solve() { val input = readInput() val starts = findAll(input, START) val target = findAll(input, TARGET).first() val graph = buildGraph(input) println("Shorted max elevation path: ${starts.map { shortestPath(graph, it, target) }.filter { it > 0 }.min()}") } private fun readInput(): Matrix { return generateSequence(::readLine).map { it.splitToSequence("").filter { !it.isEmpty() }.map { when (val char = it.first()) { in 'a'..'z' -> char.code - 'a'.code 'S' -> START 'E' -> TARGET else -> throw Error("Unexpected input char $char") } }.toList() }.toList() } private fun findAll(matrix: Matrix, target: Int): List<Pos> { val result = mutableListOf<Pos>() for (y in matrix.indices) { for (x in matrix[y].indices) { if (matrix[y][x] == target) { result.add(Pos(x, y)) } } } return result } private fun buildGraph(matrix: Matrix): Map<Pos, Node> { val height = matrix.size val width = matrix.first().size fun neighbours(pos: Pos) = listOf( Pos(pos.x - 1, pos.y), Pos(pos.x + 1, pos.y), Pos(pos.x, pos.y - 1), Pos(pos.x, pos.y + 1) ).filter { it.x in 0 until width && it.y in 0 until height } val result = mutableMapOf<Pos, Node>() for (y in matrix.indices) { for (x in matrix[y].indices) { val pos = Pos(x, y) val node = result.getOrPut(pos) { Node(pos, matrix[y][x]) } for (nPos in neighbours(pos)) { val nNode = result.getOrPut(nPos) { Node(nPos, matrix[nPos.y][nPos.x]) } if (nNode.height <= node.height + 1) { node.edges.add(nPos) } } } } return result } private fun shortestPath(graph: Map<Pos, Node>, start: Pos, target: Pos): Int { val paths = mutableMapOf<Pos, Int>() val queue = mutableListOf(Pair(start, 0)) while (queue.size > 0) { val (pos, pathLen) = queue.removeAt(0) if (pos in paths) continue paths[pos] = pathLen for (edge in graph[pos]!!.edges) { if (edge in paths) continue if (edge == target) { return pathLen + 1 } queue.add(Pair(edge, pathLen + 1)) } } return -1 } data class Pos(val x: Int, val y: Int) data class Node(val pos: Pos, val height: Int, val edges: MutableList<Pos> = mutableListOf()) }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Path$Pos.class", "javap": "Compiled from \"Path.kt\"\npublic final class Path$Pos {\n private final int x;\n\n private final int y;\n\n public Path$Pos(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 // Method java/lang/Obj...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Calculator.kt
fun main() = Calculator.solve() private object Calculator { fun solve() { val expressions = readInput() println("Part 1: root value ${calcValue(expressions, "root")}") println("Part 2, humn requires value ${matchValuesAt(expressions, "root")}") } private fun readInput(): Map<String, Expr> = buildMap { generateSequence(::readLine).forEach { line -> val parts = line.split(":") val label = parts.get(0).trim() val expr = parts.get(1).trim() when { expr.contains(" ") -> { val parts = expr.split(" ") val op = when (parts.get(1)) { "+" -> Op.Plus "-" -> Op.Minus "*" -> Op.Mul "/" -> Op.Div else -> throw Error("Unexpected operation: ${parts.get(1)}") } put(label, Calc(parts[0], parts[2], op)) } else -> { put(label, Just(expr.toLong(10))) } } } } private fun calcValue(expressions: Map<String, Expr>, label: String): Long { val values = mutableMapOf<String, Long>() fun getValue(label: String): Long { var value = values[label] if (value == null) { val expr = expressions.getValue(label) value = when (expr) { is Just -> expr.value is Calc -> { val a = getValue(expr.a) val b = getValue(expr.b) expr.operation.calc(a, b) } } values[label] = value } return value } return getValue(label) } private fun matchValuesAt(expressions: Map<String, Expr>, rootLabel: String): Long { val root = expressions.getValue(rootLabel) as Calc fun findDeps(start: String, needle: String): List<String> { val stack = mutableListOf(listOf(start)) while (stack.isNotEmpty()) { val item = stack.removeFirst() if (item.first() == needle) { return item } val expr = expressions.getValue(item.first()) if (expr is Just) { continue } if (expr is Calc) { stack.add(listOf(expr.a).plus(item)) stack.add(listOf(expr.b).plus(item)) } } return listOf() } val aDeps = findDeps(root.a, "humn") val bDeps = findDeps(root.b, "humn") if (aDeps.isNotEmpty() && bDeps.isNotEmpty()) { TODO("Dont know how to solve this yet") } else if (aDeps.isEmpty() && bDeps.isEmpty()) { throw Error("Failed to find dep list to humn") } val (targetValue, deps) = if (aDeps.isNotEmpty()) { println("A: ${root.a}") Pair(calcValue(expressions, root.b), aDeps) } else { println("B: ${root.b}") Pair(calcValue(expressions, root.a), bDeps) } println("$root, targetValue: $targetValue, deps: $deps") val targetValues = mutableMapOf(Pair(deps.last(), targetValue)) println("$targetValues") for (pair in deps.reversed().windowed(2, 1)) { val calc = expressions.getValue(pair.first()) as Calc val next = pair.last() val other = if (next == calc.a) calc.b else calc.a val otherValue = calcValue(expressions, other) val target = targetValues.getValue(pair.first()) val nextTarget = when (calc.operation) { Op.Plus -> target - otherValue Op.Mul -> target / otherValue Op.Minus -> if (next == calc.a) target + otherValue else otherValue - target Op.Div -> if (next == calc.a) target * otherValue else otherValue / target } targetValues[next] = nextTarget } return 0 } sealed interface Expr data class Just(val value: Long) : Expr data class Calc(val a: String, val b: String, val operation: Op) : Expr enum class Op { Plus { override fun calc(a: Long, b: Long): Long = a + b }, Minus { override fun calc(a: Long, b: Long): Long = a - b }, Mul { override fun calc(a: Long, b: Long): Long = a * b }, Div { override fun calc(a: Long, b: Long): Long = a / b }; abstract fun calc(a: Long, b: Long): Long } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Calculator.class", "javap": "Compiled from \"Calculator.kt\"\nfinal class Calculator {\n public static final Calculator INSTANCE;\n\n private Calculator();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<i...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Crane.kt
fun main() { Crane.solve() } object Crane { fun solve() { val input = readInput() val result = runMoves(input.state, input.moves) println("Top of stacks: ${result.map { it.first() }.joinToString("")}") } private fun readInput(): Input { val stacks = mutableListOf<Pair<Int, String>>() val moves = mutableListOf<Move>() var width = 0 var isStateSection = true for (line in generateSequence(::readLine)) { when { isStateSection -> { if (line == "") { isStateSection = false continue } val labelsRowMatch = "^\\s*(\\d+\\s*)+$".toRegex().matchEntire(line) if (labelsRowMatch != null) { width = line.trim().split("\\s+".toRegex()).size } val matchResults = "\\[(\\w+)]".toRegex().findAll(line) for (result in matchResults) { val index = result.range.first / 4 val value = result.groupValues[1] stacks.add(0, Pair(index, value)) } } else -> { // parse move val matchResult = "^move (\\d+) from (\\d+) to (\\d+)$".toRegex().matchEntire(line) ?: throw Error("Unexpected move input") moves.add( Move( matchResult.groupValues[2].toInt() - 1, matchResult.groupValues[3].toInt() - 1, matchResult.groupValues[1].toInt() ) ) } } } val state = List<MutableList<String>>(width) { mutableListOf() } for (item in stacks) { state[item.first].add(0, item.second) } return Input(state, moves) } private fun runMoves(state: List<List<String>>, moves: List<Move>): List<List<String>> { val result = state.map { it.toMutableList() } for (move in moves) { val fromStack = result[move.from] val loaded = fromStack.subList(0, move.count).toList() //.reversed() for (i in loaded) { fromStack.removeAt(0) } result[move.to].addAll(0,loaded) } return result } data class Move(val from: Int, val to: Int, val count: Int) data class Input(val state: List<List<String>>, val moves: List<Move>) }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Crane$Move.class", "javap": "Compiled from \"Crane.kt\"\npublic final class Crane$Move {\n private final int from;\n\n private final int to;\n\n private final int count;\n\n public Crane$Move(int, int, int);\n Code:\n 0: aload_0\n 1: invokespeci...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Beacons.kt
import kotlin.math.abs fun main() = Beacons.solve(0..4_000_000) private object Beacons { fun solve(possibleCoordinates: IntRange) { val sensors = readInput() val distress = findDistressBeacon(sensors, possibleCoordinates) println("Distress breacon at $distress, freq: ${distress.x.toBigInteger() * 4_000_000.toBigInteger() + distress.y.toBigInteger()}") } private fun findDistressBeacon(sensors: List<Sensor>, possibleCoordinates: IntRange): Pos { for (y in possibleCoordinates) { val ranges: List<IntRange> = rangesAtRow(sensors, y) var prev: IntRange? = null for (range in ranges) { if (prev == null) { prev = range continue } if (range.last <= prev.last) { continue } else if (range.first <= prev.last) { prev = prev.first..range.last } else { if (prev.last in possibleCoordinates) { return Pos(prev.last + 1, y) } } } } throw Error("Distress beacon not found") } // Problem 1 private fun solveIntersections(sensors: List<Sensor>, targetRow: Int) { val ranges: List<IntRange> = rangesAtRow(sensors, targetRow) // Calculate intersections var result = 0 var currentRange: IntRange? = null for (range in ranges) { if (currentRange == null) { currentRange = range } else { if (range.last <= currentRange.last) continue else if (range.first <= currentRange.last) { currentRange = currentRange.first..range.last } else { result += currentRange.last - currentRange.start + 1 currentRange = range } } } if (currentRange != null) { result += currentRange.last - currentRange.start + 1 } println("Beacon cannot take $result positions in row $targetRow") } private fun readInput(): List<Sensor> = generateSequence(::readLine).map { val groupValues = "Sensor at x=([-\\d]+), y=([-\\d]+): closest beacon is at x=([-\\d]+), y=([-\\d]+)".toRegex() .matchEntire(it)!!.groupValues Sensor( Pos(groupValues[1].toInt(10), groupValues[2].toInt(10)), Pos(groupValues[3].toInt(10), groupValues[4].toInt(10)) ) }.toList() private fun rangesAtRow(sensors: List<Sensor>, targetRow: Int): List<IntRange> = sensors.filter { abs(targetRow - it.pos.y) <= it.distanceToBeacon() }.map { val dx = it.distanceToBeacon() - abs(targetRow - it.pos.y) (it.pos.x - dx)..(it.pos.x + dx) }.sortedBy { it.start } data class Pos(val x: Int, val y: Int) { fun distanceTo(other: Pos): Int = abs(x - other.x) + abs(y - other.y) } data class Sensor(val pos: Pos, val nearestBeacon: Pos) { fun distanceToBeacon(): Int = pos.distanceTo(nearestBeacon) } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Beacons$Sensor.class", "javap": "Compiled from \"Beacons.kt\"\npublic final class Beacons$Sensor {\n private final Beacons$Pos pos;\n\n private final Beacons$Pos nearestBeacon;\n\n public Beacons$Sensor(Beacons$Pos, Beacons$Pos);\n Code:\n 0: aload_1\n...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Robots.kt
fun main() = Robots.solve() private object Robots { const val MAX_TURNS = 32 fun solve() { val blueprints = readInput().take(3) // println("1st: ${maxGeodes(blueprints.first())}") val score = blueprints.map { maxGeodes(it) }.reduce { x, y -> x * y } println("Total score: ${score}") } private fun readInput(): List<Blueprint> = generateSequence(::readLine).map { line -> val match = "Blueprint (\\d+):(.+)".toRegex().matchEntire(line)!! val id = match.groupValues[1].toInt(10) val recipes = buildMap<Resource, Recipe> { match.groupValues[2].split(".").filterNot { it.isEmpty() }.forEach { recipe -> val match = "\\s*Each (\\w+) robot costs (.+)".toRegex().matchEntire(recipe) ?: throw Error("Recipe match failed") val resource = parseResource(match.groupValues[1]) val ingredients = parseIngredients(match.groupValues[2]) put(resource, Recipe(resource, ingredients)) } } Blueprint(id, recipes) }.toList() private fun parseIngredients(string: String): Map<Resource, Int> { return buildMap { string.split(" and ".toRegex()).forEach { val values = "(\\d+) (\\w+)".toRegex().matchEntire(it)!!.groupValues put(parseResource(values[2]), values[1].toInt(10)) } } } private fun maxGeodes(blueprint: Blueprint): Int { println("Max for ${blueprint}...") val maxCost = buildMap { Resource.values().forEach { resource -> put(resource, blueprint.recipes.maxOf { it.value.cost.getOrDefault(resource, 0) }) } }.plus(Pair(Resource.Geode, Int.MAX_VALUE)) println("Max costs $maxCost") fun isGoodStep(step: Step, resource: Resource): Boolean { // println("$resource, $maxCost") if (resource === Resource.Geode) { return true } if (step.robots.getOrDefault(resource, 0) > maxCost[resource]!!) { return false } return true } fun normalizeNextStep(nextStep: Step): Step { val resources = nextStep.resources.mapValues { it -> minOf(it.value, maxCost[it.key]!! * 3) } return Step(resources, nextStep.robots, nextStep.time) } fun nextSteps(step: Step): List<Step> { val result = mutableListOf<Step>() for (resource in Resource.values()) { val cost = blueprint.recipes[resource]!!.cost if (step.hasEnough(cost) && isGoodStep(step, resource)) { val nextStep = normalizeNextStep(step.nextStepWithBuild(resource, cost)) if (resource == Resource.Geode) { return listOf(nextStep) } else { result.add(nextStep) } } } if (result.size < Resource.values().size) { result.add(step.nextStepWithIdle()) } return result } val stack = mutableListOf<Step>( Step(mapOf(), mapOf(Pair(Resource.Ore, 1)), 1) ) val seenStates = mutableSetOf<String>() val maxGeodesAtStep = mutableMapOf<Int, Int>() var maxGeodes = 0 var i = 0 while (stack.isNotEmpty()) { val step = stack.removeLast() if (step.fingerprint() in seenStates) { continue } i += 1 seenStates.add(step.fingerprint()) if (i % 1_000_000 == 0) { println("step ${i / 1_000_000}M, depth=${step.time}, max=$maxGeodes, stack size=${stack.size}") } val oldMax = maxGeodes val geodes = step.resources.getOrDefault(Resource.Geode, 0) maxGeodes = maxOf(maxGeodes, geodes) maxGeodesAtStep[step.time] = maxOf(geodes, maxGeodesAtStep.getOrDefault(step.time, 0)) if (maxGeodes > oldMax && step.time == MAX_TURNS + 1) { println("New best found $i ${step.robots} -> $maxGeodes") } val remainingTime = 1 + MAX_TURNS - step.time if (remainingTime <= 0) { continue } val maxPossibleGeodes = geodes + step.robots.getOrDefault(Resource.Geode, 0) * remainingTime + (1..remainingTime).sum() if (maxPossibleGeodes <= maxGeodes) { continue } if (maxGeodesAtStep[step.time]!! > geodes + 2) { continue } // if (geodes + 2 < maxGeodes) { // continue // } stack.addAll(nextSteps(step)) } println("$maxGeodesAtStep") println("max= ${maxGeodes}") return maxGeodes } private data class Blueprint(val id: Int, val recipes: Map<Resource, Recipe>) private data class Recipe(val robotType: Resource, val cost: Map<Resource, Int>) private enum class Resource { Ore, Clay, Obsidian, Geode, } private fun parseResource(string: String): Resource = when (string) { "ore" -> Resource.Ore "clay" -> Resource.Clay "obsidian" -> Resource.Obsidian "geode" -> Resource.Geode else -> throw Error("Failed to parse resource: $string") } private data class Step(val resources: Map<Resource, Int>, val robots: Map<Resource, Int>, val time: Int) { fun nextStepWithIdle(): Step = Step( nextResources(), robots, time + 1 ) fun nextStepWithBuild(robotType: Resource, cost: Map<Resource, Int>): Step { val resources = nextResources().mapValues { it.value - cost.getOrDefault(it.key, 0) } val nextRobots = robots.toMutableMap() nextRobots[robotType] = robots.getOrDefault(robotType, 0) + 1 return Step(resources, nextRobots, time + 1) } fun hasEnough(cost: Map<Resource, Int>): Boolean = cost.entries.all { resources.getOrDefault(it.key, 0) >= it.value } private fun nextResources(): Map<Resource, Int> = buildMap { Resource.values().forEach { put(it, resources.getOrDefault(it, 0) + robots.getOrDefault(it, 0)) } } fun fingerprint(): String = "$time.${ Resource.values().map { robots.getOrDefault(it, 0) }.joinToString("_") }.${ Resource.values().map { resources.getOrDefault(it, 0) }.joinToString("_") }" } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Robots.class", "javap": "Compiled from \"Robots.kt\"\nfinal class Robots {\n public static final Robots INSTANCE;\n\n public static final int MAX_TURNS;\n\n private Robots();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method j...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Packets.kt
fun main() = Packets.solve() private object Packets { fun solve() { val input = readInput().toMutableList() val dividers = setOf( Lst(listOf(Lst(listOf(Num(2))))), Lst(listOf(Lst(listOf(Num(6))))) ) input.addAll(dividers) val sorted = input.sorted() println("Problem 2: ${(sorted.indexOf(dividers.first()) + 1) * (sorted.indexOf(dividers.last()) + 1)}") } private fun readInput(): List<Item> { val items = mutableListOf<Item>() generateSequence(::readLine).forEach { when { !it.isEmpty() -> { items.add(parseItem(it)) } } } return items } private fun parseItem(line: String): Item { fun extractNums(string: String): List<Num> = string.split(",").map { it.toIntOrNull(10) }.filterNotNull().map { Num(it) } fun parseLst(): Lst { val values = mutableListOf<MutableList<Item>>() val indices = mutableListOf<Int>() var lastGroupClose = 0 for (i in line.indices) { when (line[i]) { '[' -> { if (!indices.isEmpty()) { val substr = line.substring((indices.last() + 1) until i) values.last().addAll(extractNums(substr)) } indices.add(i) values.add(mutableListOf()) } ']' -> { val from = indices.removeLast() val items = values.removeLast() // Non-empty list val substr = line.substring( (maxOf(from, lastGroupClose) + 1) until i ) items.addAll(extractNums(substr)) lastGroupClose = i if (values.isEmpty()) { // println("Parsed $items") return Lst(items) } else { values.last().add(Lst(items)) } } else -> continue } } throw Error("Did not terminate properly") } return when (line.first()) { '[' -> parseLst() else -> Num(line.toInt(10)) } } private sealed interface Item : Comparable<Item> private data class Num(val value: Int) : Item { override fun compareTo(other: Item): Int { return when (other) { is Num -> value.compareTo(other.value) is Lst -> Lst(listOf(this)).compareTo(other) } } } private data class Lst(val value: List<Item>) : Item { override fun compareTo(other: Item): Int { return when (other) { is Num -> compareTo(Lst(listOf(other))) is Lst -> { for (i in value.indices) { if (i >= other.value.size) { return 1 } val cmp = value[i].compareTo(other.value[i]) if (cmp != 0) { return cmp } } return value.size.compareTo(other.value.size) } } } } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Packets.class", "javap": "Compiled from \"Packets.kt\"\nfinal class Packets {\n public static final Packets INSTANCE;\n\n private Packets();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
alebedev__aoc2022__d6ba46b/src/main/kotlin/DirWalk.kt
fun main() { DirWalk.solve() } private object DirWalk { fun solve() { val tree = buildTree(readInput()) val sizes = getDirSizes(tree) // for (size in sizes) { // println("${size.key.name} ${size.value}") // } val smallDirsTotal = sizes.filter { it.value <= 100_000 }.values.sum() println("Small dirs total: $smallDirsTotal") val totalSpace = 70_000_000 val targetFreeSpace = 30_000_000 val spaceToFree = targetFreeSpace - (totalSpace - sizes.getValue(tree)) println("Space to free: $spaceToFree") val sortedDirs = sizes.toList().sortedBy { it.second } val smallestToDelete = sortedDirs.find { it.second >= spaceToFree } println("Delete dir ${smallestToDelete?.first?.name}, size: ${smallestToDelete?.second}") } private fun readInput(): Sequence<Input> { return generateSequence(::readLine).map(::parseLine) } private fun buildTree(input: Sequence<Input>): Dir { val root = Dir("/", mutableListOf<Node>()) var dir: Dir = root val stack = mutableListOf<Dir>() for (item in input) { when (item) { is CommandCd -> { when (item.path) { "/" -> { dir = root stack.clear() stack.add(dir) } ".." -> { stack.removeLast() dir = stack.last() } else -> { dir = dir.items.find { if (it is Dir) it.name == item.path else false } as Dir stack.add(dir) } } } is CommandLs -> {} is File -> dir.items.add(item) is Dir -> dir.items.add(item) } } return root } private fun parseLine(line: String): Input { return when { line == "$ ls" -> CommandLs() line.startsWith("$ cd") -> CommandCd(line.substringAfter("$ cd ")) line.startsWith("dir") -> Dir(line.substringAfter("dir ")) else -> { val parts = line.split(" ") val size = parts[0].toInt(10) File(parts[1],size) } } } private fun getDirSizes(root: Dir): Map<Dir, Int> { val result = mutableMapOf<Dir, Int>() fun walk(dir: Dir) { var current = 0 for (item in dir.items) { current += when (item) { is File -> item.size is Dir -> { walk(item) result.getValue(item) } } } result[dir] = current } walk(root) return result } sealed interface Input data class CommandCd(val path: String) : Input data class CommandLs(val path: String = ""): Input sealed interface Node data class File(val name: String, val size: Int): Node, Input data class Dir(val name: String, val items: MutableList<Node> = mutableListOf()): Node, Input }
[ { "class_path": "alebedev__aoc2022__d6ba46b/DirWalk$CommandLs.class", "javap": "Compiled from \"DirWalk.kt\"\npublic final class DirWalk$CommandLs implements DirWalk$Input {\n private final java.lang.String path;\n\n public DirWalk$CommandLs(java.lang.String);\n Code:\n 0: aload_1\n 1: ldc ...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Blizzards.kt
import java.util.* import kotlin.math.abs fun main() = Blizzards.solve() private object Blizzards { fun solve() { var board = readInput() val start = Pos(1, 0) val target = Pos(board.cells.last().indexOfFirst { it is Space }, board.cells.size - 1) val initialPath = Path( start, target, 0 ) val bestFwd = findPath(initialPath, board) println("Best path S->F takes $bestFwd steps") (1..bestFwd).forEach { board = board.next() } val backPath = Path(target, start, 0) val bestBack = findPath(backPath, board) println("Best path F->S takes $bestBack steps") (1..bestBack).forEach { board = board.next() } val bestBackAgain = findPath(initialPath, board) println("Best path S->F (again) takes $bestBackAgain steps") println("Total: ${bestFwd + bestBack + bestBackAgain}") } private fun findPath(initialPath: Path, initialBoard: Board): Int { val boards = mutableListOf(initialBoard) val queue = PriorityQueue<Path>() val visited = mutableSetOf<Path>() queue.add(initialPath) while (queue.isNotEmpty()) { val path = queue.remove() if (path.pos == path.target) { return path.turn } if (path in visited) continue else visited.add(path) val nextTurn = path.turn + 1 // println("$nextTurn $path") if (boards.size == nextTurn) { boards.add(boards.last().next()) } val nextBoard = boards[nextTurn] val nextPositions = listOf( path.pos, Pos(path.pos.x - 1, path.pos.y), Pos(path.pos.x + 1, path.pos.y), Pos(path.pos.x, path.pos.y - 1), Pos(path.pos.x, path.pos.y + 1) ).filter { pos -> (nextBoard.cells.getOrNull(pos.y)?.getOrNull(pos.x) as? Space)?.winds?.isEmpty() ?: false } nextPositions.forEach { pos -> queue.add(Path(pos, path.target, nextTurn)) } } return -1 } private fun readInput(): Board { val cells = generateSequence(::readLine).map { line -> line.toCharArray().map { char -> when (char) { '#' -> Wall '.' -> Space(mutableListOf()) '^' -> Space(mutableListOf(Wind.North)) '>' -> Space(mutableListOf(Wind.East)) '<' -> Space(mutableListOf(Wind.West)) 'v' -> Space(mutableListOf(Wind.South)) else -> throw Error("Failed to parse char $char") } } }.toList() return Board(cells) } data class Board(val cells: List<List<Cell>>) { fun visualize() { for (line in cells) { for (cell in line) { val char = when (cell) { Wall -> '#' is Space -> { if (cell.winds.isEmpty()) { '.' } else if (cell.winds.size == 1) { when (cell.winds.first()) { Wind.North -> '^' Wind.East -> '>' Wind.South -> 'v' Wind.West -> '<' } } else { cell.winds.size } } } print(char) } println() } println() } fun next(): Board { val nextCells = cells.map { it.map { cell -> when (cell) { Wall -> Wall is Space -> Space(mutableListOf()) } } } cells.forEachIndexed { y, line -> line.forEachIndexed { x, cell -> when (cell) { Wall -> {} is Space -> { cell.winds.forEach { wind -> val nextPos = nextWindPos(wind, Pos(x, y)) val nextCell = nextCells[nextPos.y][nextPos.x] require(nextCell is Space) nextCell.winds.add(wind) } } } } } return Board(nextCells) } private fun nextWindPos(wind: Wind, pos: Pos): Pos { var nextX = pos.x + wind.dx var nextY = pos.y + wind.dy // Simplified wrapping, assumes walls are always in outer row if (nextX == 0) { nextX = width() - 2 } else if (nextX >= width() - 1) { nextX = 1 } if (nextY == 0) { nextY = height() - 2 } else if (nextY >= height() - 1) { nextY = 1 } return Pos(nextX, nextY) } private fun width(): Int = cells.first().size private fun height(): Int = cells.size } sealed interface Cell object Wall : Cell data class Space(val winds: MutableList<Wind>) : Cell enum class Wind(val dx: Int, val dy: Int) { West(-1, 0), North(0, -1), East(1, 0), South(0, 1) } data class Pos(val x: Int, val y: Int) data class Path(val pos: Pos, val target: Pos, val turn: Int) : Comparable<Path> { override fun compareTo(other: Path): Int = minTurnsToTarget().compareTo(other.minTurnsToTarget()) private fun minTurnsToTarget() = abs(target.x - pos.x) + abs(target.y - pos.y) + turn } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Blizzards$readInput$cells$1.class", "javap": "Compiled from \"Blizzards.kt\"\nfinal class Blizzards$readInput$cells$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Blizzards$r...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Tetris.kt
import kotlin.streams.toList fun main() = Tetris.solve() private object Tetris { private const val width = 7 private val winds = mutableListOf<Int>() private var fallingRock: FallingRock? = null private val cells = mutableListOf( // Floor MutableList(width) { i -> Cell.StableRock } ) private var rocks = 0 private var turn = 0 private var highestRock = 0 fun solve() { winds.clear() winds.addAll(readInput()) val cache = mutableMapOf<Int, Triple<Int, Int, List<Int>>>() var cycleSize = Int.MAX_VALUE var cycleHeight = 0 val target = 1_000_000_000_000 var cycles = 0L var currentTarget = target while (rocks < currentTarget) { if (cycleSize == Int.MAX_VALUE) { if (fallingRock == null && rocks > 0 && rocks % 5 == 0) { // println("Rock cycle, round $turn, ${turn % winds.size}") val heights = heights() val minHeight = heights().min() val dHeights = heights.map { it - minHeight } val (cachedRocks, cachedMinHeight, cachedDh) = cache.getOrDefault( turn % winds.size, Triple(0, 0, listOf<Int>()) ) if (dHeights == cachedDh) { cycleSize = rocks - cachedRocks cycleHeight = minHeight - cachedMinHeight println("Cycle rocks=${cycleSize} height=$cycleHeight $dHeights") currentTarget = rocks + ((target - rocks) % cycleSize) cycles = (target - rocks) / cycleSize println("Setting new target $currentTarget") } else { cache.put(turn % winds.size, Triple(rocks, minHeight, dHeights)) } //println("$dHeights ${turn % winds.size}") } } tick() } println("Total height: shortcut=$highestRock ${highestRock + cycleHeight * cycles}") } fun heights(): List<Int> { return (0 until width).map { x -> (highestRock downTo 0).first { y -> cells[y][x] == Cell.StableRock } } } private fun tick() { addRockOrFall() blowAtFallingRock() maybeStabilizeFallenRock() turn += 1 } private fun addRockOrFall() { if (fallingRock == null) { val pos = Pos(2, highestRock + 4) fallingRock = FallingRock(rockTypes[rocks % rockTypes.size], pos) extendCells(fallingRock!!.cells().maxOf { it.y }) } else { moveFalling(0, -1) } } private fun moveFalling(dx: Int, dy: Int): Boolean { val initialPos = fallingRock!!.pos val nextRock = FallingRock(fallingRock!!.type, Pos(initialPos.x + dx, initialPos.y + dy)) val moved = !nextRock.cells().any { it.x !in 0 until width || cells[it.y][it.x] == Cell.StableRock } if (moved) { fallingRock = nextRock } return moved } private fun maybeStabilizeFallenRock() { val rockCells = fallingRock!!.cells() val isStable = rockCells.any { cells[it.y - 1][it.x] == Cell.StableRock } if (isStable) { rockCells.forEach { cells[it.y][it.x] = Cell.StableRock } highestRock = maxOf(highestRock, rockCells.maxOf { it.y }) rocks += 1 fallingRock = null } } private fun extendCells(maxY: Int) { while (maxY >= cells.size) { cells.add(MutableList(width) { i -> Cell.Empty }) } } private fun blowAtFallingRock() { moveFalling(winds[turn % winds.size], 0) } private fun visualize() { println("turn $turn") val rockCells = fallingRock?.cells()?.toSet() ?: setOf() for (y in cells.indices.reversed()) { print('|') for (x in cells[y].indices) { if (Pos(x, y) in rockCells) { print('@') } else if (cells[y][x] == Cell.StableRock) { print(if (y > 0) '#' else '-') } else { print('.') } } println('|') } } private fun readInput(): List<Int> = readLine()!!.chars().map { when (it) { '<'.code -> -1 '>'.code -> 1 else -> throw Error("Invalid char $it") } }.toList() private data class Pos(val x: Int, val y: Int) private enum class Cell { Empty, StableRock, } private enum class RockType(val cells: List<Pos>) { HLine(listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(3, 0))), Cross(listOf(Pos(1, 0), Pos(0, 1), Pos(1, 1), Pos(2, 1), Pos(1, 2))), RightAngle(listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(2, 1), Pos(2, 2))), VLine(listOf(Pos(0, 0), Pos(0, 1), Pos(0, 2), Pos(0, 3))), Square(listOf(Pos(0, 0), Pos(1, 0), Pos(0, 1), Pos(1, 1))) } private data class FallingRock(val type: RockType, val pos: Pos) { fun cells() = type.cells.map { Pos(pos.x + it.x, pos.y + it.y) } } private val rockTypes = listOf(RockType.HLine, RockType.Cross, RockType.RightAngle, RockType.VLine, RockType.Square) }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Tetris$Pos.class", "javap": "Compiled from \"Tetris.kt\"\nfinal class Tetris$Pos {\n private final int x;\n\n private final int y;\n\n public Tetris$Pos(int, int);\n Code:\n 0: aload_0\n 1: invokespecial #9 // Method java/lang/Ob...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Rucksack.kt
import java.lang.RuntimeException fun main() { var result = 0 for (group in readRucksack()) { result += charScore(findGroupBadge(group)) } println("Total score: $result") } private typealias Group = MutableList<String> private fun readRucksack(): Iterable<Group> { val result = mutableListOf<Group>() var group: Group generateSequence(::readLine).forEachIndexed { i, line -> if (i % 3 == 0) { group = mutableListOf() result.add(group) } else { group = result.last() } group.add(line) } return result.toList() } private fun findGroupBadge(group: Group): Char { val sets = group.map { it.toSet() } val commonChars = sets.reduce {chars, lineChars -> chars.intersect(lineChars)} if (commonChars.size != 1) { throw Error("Expected to find exactly one unique char") } return commonChars.first() } private fun charScore(char: Char) = when (char) { in 'a'..'z' -> { char.code - 'a'.code + 1 } in 'A'..'Z' -> { char.code - 'A'.code + 27 } else -> throw RuntimeException("Unexpected char $char") }
[ { "class_path": "alebedev__aoc2022__d6ba46b/RucksackKt.class", "javap": "Compiled from \"Rucksack.kt\"\npublic final class RucksackKt {\n public static final void main();\n Code:\n 0: iconst_0\n 1: istore_0\n 2: invokestatic #10 // Method readRucksack:()Ljava/lang/Iter...
alebedev__aoc2022__d6ba46b/src/main/kotlin/RPS.kt
import java.lang.RuntimeException fun main() { RPS.solve() } private object RPS { // Day 2 fun solve() { val input = readInput() var result = 0 for (pair in input) { val myMove = when(pair.second) { Result.Draw -> pair.first Result.Win -> when(pair.first) { Move.Rock -> Move.Paper Move.Paper -> Move.Scissors Move.Scissors -> Move.Rock } Result.Lose -> when(pair.first) { Move.Rock -> Move.Scissors Move.Paper -> Move.Rock Move.Scissors -> Move.Paper } } val game = Pair(pair.first, myMove) result += getScore(game) } println("Total score: $result") } private fun readInput(): Iterable<Pair<Move, Result>> { val result = mutableListOf<Pair<Move, Result>>() val lines = generateSequence(::readLine) for (line in lines) { val parts = line.split(" ") val first = when (parts[0]) { "A" -> Move.Rock "B" -> Move.Paper "C" -> Move.Scissors else -> throw RuntimeException("Invalid first char") } val second = when (parts[1]) { "X" -> Result.Lose "Y" -> Result.Draw "Z" -> Result.Win else -> throw RuntimeException("Invalid second char") } result.add(Pair(first, second)) } return result } private fun getScore(game: Pair<Move, Move>): Int { val my = game.second val other = game.first var score = when (my) { Move.Rock -> 1 Move.Paper -> 2 Move.Scissors -> 3 } score += when { my == other -> 3 my == Move.Rock && other == Move.Scissors -> 6 my == Move.Paper && other == Move.Rock -> 6 my == Move.Scissors && other == Move.Paper -> 6 else -> 0 } return score } private enum class Move { Rock, Paper, Scissors } private enum class Result { Lose, Draw, Win } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/RPS.class", "javap": "Compiled from \"RPS.kt\"\nfinal class RPS {\n public static final RPS INSTANCE;\n\n private RPS();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n p...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Monkeys.kt
import java.math.BigInteger fun main() = Monkeys.solve() object Monkeys { private var inspectedBy = mutableListOf<Int>() fun solve() { val input = readInput() for (monkey in input) { inspectedBy.add(monkey.id, 0) } for (turn in 1..10000) { runTurn(input) // println("After turn $turn, items by monkey ${input.map { it.items }}") } val inspected = inspectedBy.sorted().takeLast(2) println("Inspected: $inspected, score: ${inspected.first().toBigInteger() * inspected.last().toBigInteger()}") } private fun readInput(): List<Monkey> { var id = 0 var items = mutableListOf<BigInteger>() var operation: Operation? = null var testDiv = 0 var ifTrue = 0 var ifFalse = 0 val result = mutableListOf<Monkey>() fun addMonkey() { if (operation == null) { throw Error("Invalid input, no operation before empty line") } else { val test = Test(testDiv, ifTrue, ifFalse) result.add(id, Monkey(id, items, operation!!, test)) } } generateSequence(::readLine).forEach { when { it.startsWith(monkeyPrefix) -> { id = it.substringAfter(monkeyPrefix).substringBefore(":").toInt(10) items = mutableListOf<BigInteger>() testDiv = 0 ifTrue = 0 ifFalse = 0 } it.startsWith(itemsPrefix) -> { items = it.substringAfter(itemsPrefix).split(", ").map { it.toBigInteger(10) }.toMutableList() } it.startsWith(operationPrefix) -> { operation = parseOperation(it) } it.startsWith(testPrefix) -> { testDiv = it.substringAfter(testPrefix).toInt(10) } it.startsWith(ifTruePrefix) -> { ifTrue = it.substringAfter(ifTruePrefix).toInt(10) } it.startsWith(ifFalsePrefix) -> { ifFalse = it.substringAfter(ifFalsePrefix).toInt(10) } (it == "") -> { addMonkey() } } } addMonkey() return result } private fun runTurn(input: List<Monkey>) { for (monkey in input) { runRound(input, monkey) // println("round ${monkey.id} ends") } } private fun runRound(input: List<Monkey>, monkey: Monkey) { val base = input.map { it.test.testDiv }.reduce {acc, x -> x * acc}.toBigInteger() for (item in monkey.items) { val worry = monkey.operation.exec(item).mod(base) inspectedBy[monkey.id] += 1 // println("Item $item, worry after inspection $worry") val target = if (worry.mod(monkey.test.testDiv.toBigInteger()) == BigInteger.ZERO) { input[monkey.test.ifTrue] } else { input[monkey.test.ifFalse] } target.items.add(worry) // println("Passing to monkey ${target.id}") } monkey.items.clear() } } val monkeyPrefix = "Monkey " val itemsPrefix = " Starting items: " val operationPrefix = " Operation: new = " val testPrefix = " Test: divisible by " val ifTruePrefix = " If true: throw to monkey " val ifFalsePrefix = " If false: throw to monkey " private data class Monkey(val id: Int, val items: MutableList<BigInteger>, val operation: Operation, val test: Test) sealed interface OpInput object Old : OpInput data class Just(val value: BigInteger): OpInput enum class Op { Plus, Mul } data class Operation(val a: OpInput, val b: OpInput, val op: Op) { fun exec(input: BigInteger): BigInteger { val x = when (a) { Old -> input is Just -> a.value } val y = when (b) { Old -> input is Just -> b.value } return when (op) { Op.Plus -> x + y Op.Mul -> x * y } } } private fun parseOperation(line: String): Operation { val match = "(\\w+) ([+*]) (\\w+)".toRegex().matchEntire(line.substringAfter(operationPrefix)) val op = when (match!!.groupValues[2]) { "*" -> Op.Mul "+" -> Op.Plus else -> throw Error("Unexpected op") } val a = parseOpInput(match.groupValues[1]) val b = parseOpInput(match.groupValues[3]) return Operation(a, b, op) } private fun parseOpInput(string: String): OpInput = when (string) { "old" -> Old else -> Just(string.toBigInteger(10)) } private data class Test(val testDiv: Int, val ifTrue: Int, val ifFalse: Int)
[ { "class_path": "alebedev__aoc2022__d6ba46b/Monkeys$readInput$1.class", "javap": "Compiled from \"Monkeys.kt\"\nfinal class Monkeys$readInput$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Monkeys$readInput$1 INSTANCE;...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Fuel.kt
fun main() = Fuel.solve() private object Fuel { fun solve() { println("${fromSnafu("1=11-2")}") println("-> ${toSnafu(12345)}") val nums = readInput() println("$nums") val sum = nums.sum() println("Sum: $sum, SNAFU: ${toSnafu(sum)}") } private fun readInput(): List<Long> = generateSequence(::readLine).map { fromSnafu(it) }.toList() private fun fromSnafu(snafu: String): Long { val ordinals = mutableListOf<Int>() for (char in snafu.toCharArray()) { val num = snafuChars.getOrElse(char) { throw Error("Unexpected char $char") } if (num < 0) { ordinals[ordinals.lastIndex] -= 1 ordinals.add(5 + num) } else { ordinals.add(num) } // println("$char $num $ordinals") } var result = 0L for (ord in ordinals) { if (result > 0) { result *= 5 } result += ord } return result } private fun toSnafu(snafu: Long): String { val chars = mutableListOf<Char>() var next = snafu while (next > 0) { val cur = (next % 5) chars.add( 0, when (cur) { 0L -> '0' 1L -> '1' 2L -> '2' 3L -> '=' 4L -> '-' else -> throw Error("!!!") } ) next /= 5 if (cur > 2) { next += 1 } } return chars.joinToString("") } private val snafuChars = buildMap { put('1', 1) put('2', 2) put('0', 0) put('-', -1) put('=', -2) } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Fuel$readInput$1.class", "javap": "Compiled from \"Fuel.kt\"\nfinal class Fuel$readInput$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Fuel$readInput$1 INSTANCE;\n\n Fuel$r...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Valves.kt
fun main() = Valves.solve() private object Valves { fun solve() { val nodes = readInput() val maxPressure = findMaxPressureRelease(nodes, "AA", 26) println("Max releasable pressure: ${maxPressure}") } private fun readInput(): Map<String, Node> = buildMap<String, Node> { generateSequence(::readLine).forEach { val groupValues = "Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? ([\\w ,]+)".toRegex() .matchEntire(it)!!.groupValues val node = Node( groupValues[1], groupValues[2].toInt(10), groupValues[3].split(", ").toList() ) put(node.label, node) } } private fun findMaxPressureRelease(nodes: Map<String, Node>, startPos: String, remainingTime: Int): Int { val distances = mutableMapOf<String, Int>() fun distanceKey(a: String, b: String) = listOf(a, b).sorted().joinToString("") fun distanceBetween(a: String, b: String): Int { if (a == b) { return 0 } if (distanceKey(a, b) in distances) { return distances[distanceKey(a, b)]!! } val queue = mutableListOf(a) while (queue.isNotEmpty()) { val item = queue.removeFirst() if (item == b) { return distances[distanceKey(a, item)]!! } val dist = distanceBetween(a, item) for (edge in nodes[item]!!.edges) { if (distanceKey(a, edge) !in distances) { distances[distanceKey(a, edge)] = dist + 1 } if (edge !in queue) { queue.add(edge) } } } throw Error("Path not found $a->$b") } fun pathTime(path: List<String>): Int { var result = 0 var prev = startPos for (item in path) { result += distanceBetween(prev, item) + 1 prev = item } return result } fun pathFlowPair(first: List<String>, second: List<String>): Int { var result = 0 var flow = 0 val openValves = mutableSetOf<String>() fun openValve(valve: String) { if (valve in openValves) return openValves.add(valve) flow += nodes[valve]!!.pressure } val pathA = first.toMutableList() val pathB = second.toMutableList() var a = startPos var b = startPos var timeA = 0 var timeB = 0 var nextA: String? = null var nextB: String? = null for (i in 0..remainingTime) { result += flow if (i == timeA) { if (i > 0 && nextA != null) { a = nextA openValve(a) } nextA = pathA.removeFirstOrNull() if (nextA != null) { timeA += distanceBetween(a, nextA) + 1 } } if (i == timeB) { if (i > 0 && nextB != null) { b = nextB openValve(b) } nextB = pathB.removeFirstOrNull() if (nextB != null) { timeB += distanceBetween(b, nextB) + 1 } } } return result } val paths = mutableSetOf<List<String>>(listOf()) val valves = nodes.keys.filter { nodes[it]!!.pressure > 0 } for (level in 0..valves.size) { println("$level") val newItems = mutableSetOf<List<String>>() for (valve in valves) { for (prefix in paths) { if (valve in prefix) { continue } val path = prefix.plus(valve) if (path in paths) { continue } // println("$valve $prefix") if (pathTime(path) < remainingTime) { newItems.add(path) } } } if (!paths.addAll(newItems)) { break } else { //println("NI ${newItems.size}") } } println("Number of paths ${paths.size}") var max = 0 var i = 0 for (a in paths) { for (b in paths) { if (a != b) { max = maxOf(max, pathFlowPair(a, b)) } } i += 1 println("$i") } // println("Distance ${distanceBetween("BB", "JJ")}") // val bestPath = paths.sortedBy { pathFlow(it) }.last() // println("Best path $bestPath") return max } data class Node(val label: String, val pressure: Int, val edges: List<String>) }
[ { "class_path": "alebedev__aoc2022__d6ba46b/Valves$readInput$1$1.class", "javap": "Compiled from \"Valves.kt\"\nfinal class Valves$readInput$1$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<java.lang.String> {\n public static final Valves$readInput$1$1 INSTANC...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Seeding.kt
import kotlin.math.abs fun main() = Seeding.solve() private object Seeding { fun solve() { var board = Board(readInput()) println("Initial") board.visualize() var i = 0 while (true) { println("$i") val direction = Direction.values()[i % 4] val (nextBoard, moved) = board.next(direction) if (moved == 0) { println("Stable after turn ${i + 1}") break } board = nextBoard i += 1 } // for (i in 0 until 10) { // board = board.next(direction) // println("after turn ${i + 1}") // board.visualize() // } // board.visualize() // println("Empty cells after 10 rounds: ${board.emptyCells()}") } private fun readInput(): Set<Pos> { val result = mutableSetOf<Pos>() generateSequence(::readLine).forEachIndexed { y, line -> line.toCharArray().forEachIndexed { x, char -> if (char == '#') result.add(Pos(x, y)) } } return result } class Board(val elves: Set<Pos>) { fun visualize() { val (xRange, yRange) = getBoundingRect() for (y in yRange) { for (x in xRange) { print(if (Pos(x, y) in elves) '#' else '.') } println() } println() } fun next(firstLook: Direction): Pair<Board, Int> { val firstLookIndex = Direction.values().indexOf(firstLook) val lookDirections = Direction.values().toList().subList(firstLookIndex, Direction.values().size) .plus(Direction.values().sliceArray(0 until firstLookIndex)) require(lookDirections.size == Direction.values().size && lookDirections.first() == firstLook) // println("Look directions: $lookDirections") val moves = mutableMapOf<Pos, Pos>() for (elf in elves) { var nextPos = elf if (elf.neighbours().any { elves.contains(it) }) { for (dir in lookDirections) { if (elf.directionNeighbours(dir.delta.x, dir.delta.y).none { pos -> elves.contains(pos) }) { nextPos = Pos(elf.x + dir.delta.x, elf.y + dir.delta.y) break } } // println("Move $elf -> $nextPos") } moves[elf] = nextPos } val targets = mutableSetOf<Pos>() val conflictingTargets = mutableSetOf<Pos>() for (move in moves.values) { if (move in targets) { conflictingTargets.add(move) } else { targets.add(move) } } val nextElves = moves.map { move -> if (move.value in conflictingTargets) { move.key } else { move.value } }.toSet() val moveCount = nextElves.count { it !in elves } return Pair(Board(nextElves), moveCount) } fun emptyCells(): Int { val (xRange, yRange) = getBoundingRect() return (1 + xRange.last - xRange.first) * (1 + yRange.last - yRange.first) - elves.size } private fun getBoundingRect(): Pair<IntRange, IntRange> { val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } return Pair( minX..maxX, minY..maxY ) } } enum class Direction(val delta: Pos) { North(Pos(0, -1)), South(Pos(0, 1)), West(Pos(-1, 0)), East(Pos(1, 0)), } data class Pos(val x: Int, val y: Int) { fun neighbours(): List<Pos> = listOf( Pos(x - 1, y - 1), Pos(x, y - 1), Pos(x + 1, y - 1), Pos(x - 1, y), Pos(x + 1, y), Pos(x - 1, y + 1), Pos(x, y + 1), Pos(x + 1, y + 1) ) fun directionNeighbours(dx: Int, dy: Int): List<Pos> { require(abs(dx) <= 1 && abs(dy) <= 1 && abs(dx) + abs(dy) == 1) return if (dx != 0) { listOf(Pos(x + dx, y + dx), Pos(x + dx, y), Pos(x + dx, y - dx)) } else { listOf(Pos(x + dy, y + dy), Pos(x, y + dy), Pos(x - dy, y + dy)) } } } }
[ { "class_path": "alebedev__aoc2022__d6ba46b/SeedingKt.class", "javap": "Compiled from \"Seeding.kt\"\npublic final class SeedingKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field Seeding.INSTANCE:LSeeding;\n 3: invokevirtual #15 //...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Forest.kt
fun main() { Forest.solve() } private object Forest { fun solve() { val grid = readInput() println("Visible trees: ${countVisible(grid)}") println("Max scenic score: ${maxScenicScore(grid)}") } private fun readInput(): Grid { return generateSequence(::readLine).map { it.split("").filterNot { it.isEmpty() }.map { it.toInt(10) } }.toList() } private fun maxScenicScore(trees: Grid): Int { var result = 0 trees.forEachIndexed { i, line -> line.forEachIndexed { j, tree -> var leftView = 0 for (left in (j - 1) downTo 0) { leftView += 1 if (trees[i][left] >= tree) break } var rightView = 0 for (right in (j + 1) until line.size) { rightView += 1 if (trees[i][right] >= tree) break } var topView = 0 for (top in (i - 1) downTo 0) { topView += 1 if (trees[top][j] >= tree) break } var bottomView = 0 for (bottom in (i + 1) until trees.size) { bottomView += 1 if (trees[bottom][j] >= tree) break } result = maxOf(result, leftView * rightView * topView * bottomView) } } return result } private fun countVisible(trees: Grid): Int { var result = 0 trees.forEachIndexed { i, line -> line.forEachIndexed { j, item -> if (i == 0 || j == 0 || i == trees.size - 1 || j == line.size - 1) { result += 1 } else if (line.subList(0, j).max() < item) { result += 1 } else if (line.subList(j + 1, line.size).max() < item) { result += 1 } else { var topVisible = true var bottomVisible = true for (z in trees.indices) { if (z == i) continue if (topVisible && z < i) { topVisible = trees[z][j] < item } if (bottomVisible && z > i) { bottomVisible = trees[z][j] < item } } if (topVisible || bottomVisible) result += 1 } } } return result } } private typealias Grid = List<List<Int>>
[ { "class_path": "alebedev__aoc2022__d6ba46b/Forest.class", "javap": "Compiled from \"Forest.kt\"\nfinal class Forest {\n public static final Forest INSTANCE;\n\n private Forest();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Rope.kt
import kotlin.math.abs import kotlin.math.sign fun main() { Rope.solve() } private object Rope { fun solve() { val moves = readInput() println("tail visited ${getTailPath(moves, 10).toSet().size}") } private fun readInput(): Sequence<Move> { return generateSequence(::readLine).map { val parts = it.split(" ") val direction = when (parts[0]) { "U" -> Direction.Up "D" -> Direction.Down "L" -> Direction.Left "R" -> Direction.Right else -> throw Error("Unexpected direction ${parts[0]}") } val length = parts[1].toInt(10) Move(direction, length) } } private fun getTailPath(moves: Sequence<Move>, ropeSize: Int): List<Pos> { var head = Pos(0, 0) var rope = Array<Pos>(ropeSize) { head } val path = mutableListOf<Pos>() moves.forEach { println("Move $it") for (i in 0 until it.length) { head = when (it.direction) { Direction.Up -> Pos(head.x, head.y + 1) Direction.Down -> Pos(head.x, head.y - 1) Direction.Left -> Pos(head.x - 1, head.y) Direction.Right -> Pos(head.x + 1, head.y) } var prev = head rope = Array<Pos>(ropeSize) { j -> if (i == 0) head else { val pos = nextTailPos(prev, rope[j]) prev = pos pos } } path.add(rope.last()) } } return path } private fun nextTailPos(headPos: Pos, tailPos: Pos): Pos { val dx = headPos.x - tailPos.x val dy = headPos.y - tailPos.y if (abs(dx) > 1 || abs(dy) > 1) { var (x, y) = tailPos x += sign(dx.toDouble()).toInt() y += sign(dy.toDouble()).toInt() return Pos(x, y) } return tailPos } } private data class Pos(val x: Int, val y: Int) private enum class Direction { Up, Down, Left, Right, } private data class Move(val direction: Direction, val length: Int)
[ { "class_path": "alebedev__aoc2022__d6ba46b/Rope.class", "javap": "Compiled from \"Rope.kt\"\nfinal class Rope {\n public static final Rope INSTANCE;\n\n private Rope();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Map.kt
import kotlin.math.abs fun main() = AocMap.solve() private object AocMap { fun solve() { val (board, moves) = readInput() println("$moves") // board.print() // val pos = applyMoves(board, moves) println("Board size ${board.cells.size}x${board.cells.first().size}") println("Cube size ${board.cubeSize()}") // Hardcoded for input shape val cubeRegions = listOf( Pair(0, 1), Pair(0, 2), Pair(1, 1), Pair(2, 0), Pair(2, 1), Pair(3, 0) ) // println("After moves: $pos ${getScore(pos)}") } private fun applyMoves(board: Board, moves: List<Move>): State { var state = board.findInitialState() println("Initial state: $state") for (move in moves) { state = board.applyMove(state, move) println("$move $state") } return state } private fun getScore(state: State): Int { return (state.y + 1) * 1000 + (state.x + 1) * 4 + when (state.facing) { Facing.Right -> 0 Facing.Down -> 1 Facing.Left -> 2 Facing.Up -> 3 } } fun readInput(): Pair<Board, List<Move>> { val rows = mutableListOf<List<Cell>>() var inMapSection = true var maxWidth = 0 for (line in generateSequence(::readLine)) { if (inMapSection) { if (line == "") { inMapSection = false continue } val cells = line.toCharArray().map { when (it) { ' ' -> Cell.None '.' -> Cell.Empty '#' -> Cell.Wall else -> throw Error("Unexpected char") } }.toMutableList() maxWidth = maxOf(maxWidth, cells.size) if (cells.size < maxWidth) { cells.addAll((1..maxWidth - cells.size).map { Cell.None }) } rows.add(cells) } else { val moves = "(\\d+)(L|R|$)".toRegex().findAll(line).map { match -> var rotateRight = 0 if (match.groupValues[2] == "L") { rotateRight = -1 } else if (match.groupValues[2] == "R") { rotateRight = 1 } Move(match.groupValues[1].toInt(10), rotateRight) }.toList() return Pair(Board(rows), moves) } } val moves = listOf<Move>() return Pair(Board(rows), moves) } enum class Facing { Right, Down, Left, Up; fun rotate(rotateRight: Int): Facing { var i = this.ordinal + rotateRight if (i == -1) { i = Facing.values().size - 1 } else if (i >= Facing.values().size) { i = 0 } return Facing.values()[i] } } data class Move(val len: Int, val rotateRight: Int) data class Board(val cells: List<List<Cell>>) { fun cubeSize(): Int { return cells.first().count { it != Cell.None } / 2 } fun findInitialState(): State { return State(cells.first().indexOfFirst { it == Cell.Empty }, 0, Facing.Right) } fun applyMove(state: State, move: Move): State { var x = state.x var y = state.y when (state.facing) { Facing.Right -> x = moveX(state, move.len) Facing.Down -> y = moveY(state, move.len) Facing.Left -> x = moveX(state, -move.len) Facing.Up -> y = moveY(state, -move.len) } val facing = state.facing.rotate(move.rotateRight) return State(x, y, facing) } private fun moveX(state: State, dx: Int): Int { val range = 1..abs(dx) val step = dx / abs(dx) var x = state.x for (i in range) { var nextX = x + step if (nextX == cells.first().size) { nextX = 0 } else if (nextX < 0) { nextX = cells.first().size - 1 } while (cells[state.y][nextX] == Cell.None) { nextX += step if (nextX == cells.first().size) { nextX = 0 } else if (nextX < 0) { nextX = cells.first().size - 1 } } if (cells[state.y][nextX] == Cell.Wall) { return x } else { x = nextX } } return x } private fun moveY(state: State, dy: Int): Int { val range = 1..abs(dy) val step = dy / abs(dy) var y = state.y for (i in range) { var next = y + step if (next == cells.size) { next = 0 } else if (next < 0) { next = cells.size - 1 } while (cells[next][state.x] == Cell.None) { next += step if (next == cells.size) { next = 0 } else if (next < 0) { next = cells.size - 1 } } if (cells[next][state.x] == Cell.Wall) { return y } else { y = next } } return y } fun print() { for (row in cells) { println(row.map { when (it) { Cell.None -> ' ' Cell.Empty -> '.' Cell.Wall -> '#' } }.joinToString("")) } } } enum class Cell { None, Empty, Wall } data class State(val x: Int, val y: Int, val facing: Facing) }
[ { "class_path": "alebedev__aoc2022__d6ba46b/MapKt.class", "javap": "Compiled from \"Map.kt\"\npublic final class MapKt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field AocMap.INSTANCE:LAocMap;\n 3: invokevirtual #15 // Method AocMap...
alebedev__aoc2022__d6ba46b/src/main/kotlin/Cleanup.kt
// Day4 fun main() { val sections = readInput() val fullyContained = sections.count { fullyContains(it.first, it.second) || fullyContains(it.second, it.first) } val overlapping = sections.count { overlaps(it.first, it.second) } println("# of fully contained ${fullyContained}") println("# of overlapping ${overlapping}") } private fun readInput(): Iterable<Section> { val result = mutableListOf<Section>() generateSequence(::readLine).forEach { val segments = it.split(',').map(::parsePair) result.add(Pair(segments[0], segments[1])) } return result } private typealias Segment = Pair<Int, Int> private typealias Section = Pair<Segment, Segment> private fun parsePair(string: String) : Pair<Int, Int> { val parts = string.split('-') return Pair(parts[0].toInt(10), parts[1].toInt(10)) } private fun fullyContains(a: Segment, b: Segment) = a.first <= b.first && a.second >= b.second private fun overlaps(a: Segment, b: Segment) = (a.first <= b.first && a.second >= b.first) || (a.first <= b.second && a.second >= b.first)
[ { "class_path": "alebedev__aoc2022__d6ba46b/CleanupKt.class", "javap": "Compiled from \"Cleanup.kt\"\npublic final class CleanupKt {\n public static final void main();\n Code:\n 0: invokestatic #10 // Method readInput:()Ljava/lang/Iterable;\n 3: astore_0\n 4: aload_0\n...
shengmin__coding-problem__08e6554/hackerrank/journey-to-the-moon/Solution.kt
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the journeyToMoon function below. fun journeyToMoon(n: Int, pairs: Array<Array<Int>>): Long { val nodeEdges = kotlin.arrayOfNulls<MutableList<Int>>(n) for (pair in pairs) { val (a, b) = pair val aNodeEdges = nodeEdges[a] ?: mutableListOf<Int>() val bNodeEdges = nodeEdges[b] ?: mutableListOf<Int>() aNodeEdges.add(b) bNodeEdges.add(a) nodeEdges[a] = aNodeEdges nodeEdges[b] = bNodeEdges } val visitedNodes = BooleanArray(n) fun countNodes(node: Int): Int { if (visitedNodes[node]) { return 0 } visitedNodes[node] = true var nodeCount = 1 val nextNodes = nodeEdges[node] if (nextNodes == null) { return 1 } for (nextNode in nextNodes) { nodeCount += countNodes(nextNode) } return nodeCount } val countries = mutableListOf<Int>() var countryWithSingleNodeCount = 0 for (node in 0 until n) { val nodeCount = countNodes(node) if (nodeCount == 0) { continue } if (nodeCount == 1) { countryWithSingleNodeCount++ } else { countries.add(nodeCount) } } var totalCount = 0L for (i in 0 until countries.size) { for (j in i + 1 until countries.size) { totalCount += countries[i].toLong() * countries[j].toLong() } } // pair single node with multiple nodes for (countryCount in countries) { totalCount += countryCount * countryWithSingleNodeCount.toLong() } // pair single node with single node totalCount += (countryWithSingleNodeCount) * (countryWithSingleNodeCount.toLong() - 1) / 2 return totalCount } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val np = scan.nextLine().split(" ") val n = np[0].trim().toInt() val p = np[1].trim().toInt() val astronaut = Array<Array<Int>>(p, { Array<Int>(2, { 0 }) }) for (i in 0 until p) { astronaut[i] = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray() } val result = journeyToMoon(n, astronaut) println(result) }
[ { "class_path": "shengmin__coding-problem__08e6554/SolutionKt.class", "javap": "Compiled from \"Solution.kt\"\npublic final class SolutionKt {\n public static final long journeyToMoon(int, java.lang.Integer[][]);\n Code:\n 0: aload_1\n 1: ldc #9 // String pairs\n ...
Davio__rosalind__f5350b0/src/nl/davefranken/rosalind/P4FIB.kt
import java.io.File import java.math.BigInteger import java.util.stream.Stream /** * Problem A sequence is an ordered collection of objects (usually numbers), which are allowed to repeat. Sequences can be finite or infinite. Two examples are the finite sequence (π,−2–√,0,π)(π,−2,0,π) and the infinite sequence of odd numbers (1,3,5,7,9,…)(1,3,5,7,9,…). We use the notation anan to represent the nn-th term of a sequence. A recurrence relation is a way of defining the terms of a sequence with respect to the values of previous terms. In the case of Fibonacci's rabbits from the introduction, any given month will contain the rabbits that were alive the previous month, plus any new offspring. A key observation is that the number of offspring in any month is equal to the number of rabbits that were alive two months prior. As a result, if FnFn represents the number of rabbit pairs alive after the nn-th month, then we obtain the Fibonacci sequence having terms FnFn that are defined by the recurrence relation Fn=Fn−1+Fn−2Fn=Fn−1+Fn−2 (with F1=F2=1F1=F2=1 to initiate the sequence). Although the sequence bears Fibonacci's name, it was known to Indian mathematicians over two millennia ago. When finding the nn-th term of a sequence defined by a recurrence relation, we can simply use the recurrence relation to generate terms for progressively larger values of nn. This problem introduces us to the computational technique of dynamic programming, which successively builds up solutions by using the answers to smaller cases. Given: Positive integers n≤40n≤40 and k≤5k≤5. Return: The total number of rabbit pairs that will be present after nn months, if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of kk rabbit pairs (instead of only 1 pair). */ fun main(args: Array<String>) { val fib = File("rosalind_fib.txt").readLines()[0]; val list = fib.split(" ") val n = list[0].toLong() val k = BigInteger(list[1]) Stream.iterate(Pair(BigInteger.ONE, BigInteger.ZERO), { pair -> Pair(pair.second * k, pair.first + pair.second) }) .skip(n - 1L) .findFirst() .ifPresent{pair -> println(pair.first + pair.second)} }
[ { "class_path": "Davio__rosalind__f5350b0/P4FIBKt.class", "javap": "Compiled from \"P4FIB.kt\"\npublic final class P4FIBKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic #15 ...
laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/pracexam1problem3/TwoStringMasks.kt
class TwoStringMasks { private val IMPOSSIBLE: String = "impossible" private fun String.trim(b: Int): String { var i = b while (this[i] != '*') ++i return removeRange(i, i + 1) } private fun String.combine(b1: Int, e1: Int, other: String, b2: Int, e2: Int): String { val nb2 = b2 + 1 var tb1 = b1 var l1 = e1 - tb1 val l2 = e2 - nb2 + 1 if (l1 > l2) { tb1 += l1 - l2 l1 = l2 } while (tb1 < e1 && subSequence(tb1, tb1 + l1) != other.subSequence(nb2, nb2 + l1)) { ++tb1 --l1 } val sb = StringBuilder(tb1 + other.length - b2) sb.append(this, 0, tb1) sb.append(other, nb2, other.length) return sb.toString() } fun shortestCommon(s1: String, s2: String): String { var b1 = 0 var b2 = 0 var c1 = s1[b1] var c2 = s2[b2] while (c1 != '*' && c2 != '*') { if (c1 != c2) return IMPOSSIBLE c1 = s1[++b1] c2 = s2[++b2] } var e1 = s1.length - 1 var e2 = s2.length - 1 c1 = s1[e1] c2 = s2[e2] while (c1 != '*' && c2 != '*') { if (c1 != c2) return IMPOSSIBLE c1 = s1[--e1] c2 = s2[--e2] } return when { b1 == e1 -> s2.trim(b2) b2 == e2 -> s1.trim(b1) s1[e1] == '*' -> s1.combine(b1, e1, s2, b2, e2) else -> s2.combine(b2, e2, s1, b1, e1) } } }
[ { "class_path": "laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/TwoStringMasks.class", "javap": "Compiled from \"TwoStringMasks.kt\"\npublic final class TwoStringMasks {\n private final java.lang.String IMPOSSIBLE;\n\n public TwoStringMasks();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/week11familytravel/FamilyTravel.kt
import java.util.PriorityQueue class FamilyTravel { data class Stop(@JvmField val dist: Int, @JvmField val prevDist: Int, @JvmField val src: Int) : Comparable<Stop> { override fun compareTo(other: Stop): Int = dist - other.dist } fun shortest(edges: Array<String>): Int { val m = edges.first().length val converted = Array(edges.size) { i -> val s = edges[i] IntArray(m) { j -> when (val c = s[j]) { in 'a' .. 'z' -> c - 'a' + 1 in 'A' .. 'Z' -> c - 'A' + 27 else -> 53 } } } val q = PriorityQueue<Stop>() q.add(Stop(0, 52, 0)) val md = Array(m) { val re = IntArray(54) re.fill(Int.MAX_VALUE) re } md[0][53] = 0 while (q.isNotEmpty()) { val (d, pd, src) = q.poll() if (src == 1) return d converted[src].forEachIndexed { index, i -> if (i <= pd) { val nd = d + i if (nd < md[index][i]) { md[index][i] = nd q.add(Stop(nd, i, index)) } } } } return -1 } }
[ { "class_path": "laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/FamilyTravel.class", "javap": "Compiled from \"FamilyTravel.kt\"\npublic final class FamilyTravel {\n public FamilyTravel();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/week7fewestfactors/FewestFactors.kt
class FewestFactors { private fun IntArray.swap(l: Int, r: Int) { val tmp = this[l] this[l] = this[r] this[r] = tmp } private val IntArray.number: Int get() = fold(0) { acc, it -> 10 * acc + it } private val Int.factors: Int get() { var nf = 0 var f = 1 while (f * f < this) { if (this % f == 0) nf += 2 ++f } if (f * f == this) ++nf return nf } fun number(digits: IntArray): Int { var mn = digits.number var mnf = mn.factors val s = digits.size val weights = IntArray(s) var i = 1 while (i < s) { if (weights[i] < i) { digits.swap(i, if (i % 2 == 0) 0 else weights[i]) val n = digits.number val nf = n.factors if (nf < mnf) { mnf = nf mn = n } else if (nf == mnf && n < mn) mn = n ++weights[i] i = 1 } else { weights[i] = 0 ++i } } return mn } }
[ { "class_path": "laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/FewestFactors.class", "javap": "Compiled from \"FewestFactors.kt\"\npublic final class FewestFactors {\n public FewestFactors();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\...
laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/week7matchnumberseasy/MatchNumbersEasy.kt
class MatchNumbersEasy { private fun compare(sb1: StringBuilder, sb2: StringBuilder): Int { if (sb1.isEmpty() || sb2.isEmpty()) return sb1.length - sb2.length var nz1 = sb1.indexOfFirst { c -> c != '0' } if (nz1 == -1) nz1 = sb1.length - 1 var nz2 = sb2.indexOfFirst { c -> c != '0' } if (nz2 == -1) nz2 = sb2.length - 1 val l1 = sb1.length - nz1 val l2 = sb2.length - nz2 var cr = l1 - l2 if (cr != 0) return cr for (i in 0 until Math.min(l1, l2)) { cr = sb1[nz1 + i] - sb2[nz2 + i] if (cr != 0) return cr } return 0 } fun maxNumber(matches: IntArray, n: Int): String { val record = Array(n + 1) { StringBuilder(n) } var sb = StringBuilder(n) for (m in 1 .. n) { matches.forEachIndexed { i, match -> for (j in match .. m) { val prev = record[j - match] if (prev.isEmpty() || prev.first() <= '0' + i) { sb.append(i) sb.append(prev) } else { sb.append(prev) sb.append(i) } val curr = record[m] if (compare(sb, curr) > 0) { record[m] = sb sb = curr } sb.setLength(0) } } } sb.setLength(0) return record.foldRight(sb) { acc, isb -> if (compare(isb, acc) > 0) isb else acc }.toString() } }
[ { "class_path": "laitingsheng__2020S1-COMP-SCI-7007__2fc3e7a/MatchNumbersEasy.class", "javap": "Compiled from \"MatchNumbersEasy.kt\"\npublic final class MatchNumbersEasy {\n public MatchNumbersEasy();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<...
bejohi__UiB_INF237__7e34663/src/8ExponentialTimeAlgorithms/MapColouring.kt
import java.util.* val resultList = mutableListOf<String>() var done = false // Solution for https://open.kattis.com/problems/mapcolouring // With help from https://github.com/amartop fun main(args: Array<String>){ val input = Scanner(System.`in`) val numberOfTestCases = input.nextInt() for(testCase in 1..numberOfTestCases){ val countries = input.nextInt() val borders = input.nextInt() val adjMatrix = Array(countries+1,{IntArray(countries+1)}) var coloredArr = IntArray(countries+1, { _ -> 1}) for(border in 0 until borders){ val c1 = input.nextInt() val c2 = input.nextInt() adjMatrix[c1][c2] = 1 adjMatrix[c2][c1] = 1 } if(borders == 0){ resultList.add("1") continue } done = false for(i in 1..countries+1){ solve(i,adjMatrix,0,coloredArr) } } resultList.forEach {println(it)} } fun solve(numberOfColors: Int, adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray){ if(done){ return } val colorOk = checkColor(adjMatrix,currentVertex,vertColored) if(!colorOk){ return } if(numberOfColors+1 > 4){ resultList.add("many") done = true return } if(currentVertex == adjMatrix.size-1){ resultList.add((numberOfColors+1).toString()) done = true return } for(i in 1..numberOfColors+1) { vertColored[currentVertex+1] = i solve(numberOfColors,adjMatrix,currentVertex+1,vertColored) } return } fun checkColor(adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray): Boolean { for(i in 0 until currentVertex){ if(adjMatrix[i][currentVertex] != 0 && vertColored[i] == vertColored[currentVertex]){ return false; } } return true }
[ { "class_path": "bejohi__UiB_INF237__7e34663/MapColouringKt.class", "javap": "Compiled from \"MapColouring.kt\"\npublic final class MapColouringKt {\n private static final java.util.List<java.lang.String> resultList;\n\n private static boolean done;\n\n public static final java.util.List<java.lang.String...
bejohi__UiB_INF237__7e34663/src/9DynamicProgramming2/TheCitrusIntern.kt
import java.util.* // Solution for https://open.kattis.com/problems/citrusintern // With help from https://github.com/amartop var numberOfEmployees = 0 var input = Scanner(System.`in`) var costs = mutableListOf<Int>() var inL = arrayOf<Long>() var outUpL = arrayOf<Long>() var outDownL = arrayOf<Long>() var root = -1 fun init() : Array<MutableList<Int>>{ numberOfEmployees = input.nextInt() val adjList = Array(numberOfEmployees,{ _ -> mutableListOf<Int>()}) val rootList = BooleanArray(numberOfEmployees,{_ -> true}) for(i in 0 until numberOfEmployees){ costs.add(input.nextInt()) val childs = input.nextInt() for(x in 0 until childs){ val currentChild = input.nextInt() adjList[i].add(currentChild) rootList[currentChild] = false } } for(i in 0 until numberOfEmployees){ if(rootList[i]){ root = i break } } return adjList } fun solve(adjList: Array<MutableList<Int>>){ inL = Array<Long>(numberOfEmployees,{ _ -> 0}) // Init to weight for(i in 0 until costs.size){ inL[i] = costs[i].toLong() } outDownL = Array<Long>(numberOfEmployees,{ _ -> 0}) outUpL = Array<Long>(numberOfEmployees,{ _ -> 0}) fillTable2(root,adjList) println(Math.min(outDownL[root],inL[root])) } fun fillTable2(currentVertex: Int, adjList: Array<MutableList<Int>>){ if(adjList[currentVertex].isEmpty()){ outDownL[currentVertex] = Long.MAX_VALUE return } var delta: Long = Long.MAX_VALUE for(neighbour in adjList[currentVertex]){ fillTable2(neighbour,adjList) inL[currentVertex] += outUpL[neighbour] outUpL[currentVertex] += Math.min(inL[neighbour], outDownL[neighbour]) outDownL[currentVertex] += Math.min(inL[neighbour], outDownL[neighbour]) delta = Math.min(Math.max(inL[neighbour]- outDownL[neighbour],0),delta) } outDownL[currentVertex] += delta } fun main(args: Array<String>){ val adjList = init() solve(adjList) }
[ { "class_path": "bejohi__UiB_INF237__7e34663/TheCitrusInternKt.class", "javap": "Compiled from \"TheCitrusIntern.kt\"\npublic final class TheCitrusInternKt {\n private static int numberOfEmployees;\n\n private static java.util.Scanner input;\n\n private static java.util.List<java.lang.Integer> costs;\n\n...
bejohi__UiB_INF237__7e34663/src/8ExponentialTimeAlgorithms/ColoringGraphs.kt
import java.util.* import kotlin.system.exitProcess // Solution for https://open.kattis.com/problems/coloring // With help from https://github.com/amartop fun main(args: Array<String>){ val input = Scanner(System.`in`) val vertices = input.nextLine().toInt() val adjMatrix = Array(vertices,{IntArray(vertices)}) var coloredArr = IntArray(vertices, { x -> 1}) for(vert in 0 until vertices){ val line = input.nextLine() val numberList = line.split(" ").map { x -> x.toInt() } for(number in numberList){ adjMatrix[vert][number] = 1 adjMatrix[number][vert] = 1 } } for(i in 1..vertices+1){ recursiveSolve(i,adjMatrix,0,coloredArr) } } fun recursiveSolve(numberOfColors: Int, adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray){ // 1. Verify valid color. val colorOk = colorOk(adjMatrix,currentVertex,vertColored) if(!colorOk){ return } if(currentVertex == adjMatrix.size-1){ println(numberOfColors+1) exitProcess(0) } for(i in 1..numberOfColors+1) { vertColored[currentVertex+1] = i // new color recursiveSolve(numberOfColors,adjMatrix,currentVertex+1,vertColored) } } fun colorOk(adjMatrix: Array<IntArray>, currentVertex: Int, vertColored: IntArray): Boolean { for(i in 0..currentVertex-1){ if(adjMatrix[i][currentVertex] != 0 && vertColored[i] == vertColored[currentVertex]){ return false; } } /*for(i in 0 until adjMatrix.size){ if(i == currentVertex){ continue } if(adjMatrix[currentVertex][i] != 0){ // Has neighbour? if(vertColored[i] == vertColored[currentVertex]){ // Same color? return false } } }*/ return true } fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
[ { "class_path": "bejohi__UiB_INF237__7e34663/ColoringGraphsKt.class", "javap": "Compiled from \"ColoringGraphs.kt\"\npublic final class ColoringGraphsKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3...
frango9000__advent-of-code-22__62e91dd/src/Day04.kt
fun main() { val input = readInput("Day04") println(Day04.part1(input)) println(Day04.part2(input)) } class Day04 { companion object { fun part1(input: List<String>): Int { return input.filter { it: String -> val (a1, a2, b1, b2) = it.split(",") .map { it.split("-").map { point -> point.toInt() } }.flatten() a1 in b1..b2 || b2 in a1..a2 }.size } fun part2(input: List<String>): Int { return input.filter { it: String -> val (a1, a2, b1, b2) = it.split(",") .map { it.split("-").map { point -> point.toInt() } }.flatten() a1 in b1..b2 || b1 in a1..a2 }.size } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day04$Companion.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04$Companion {\n private Day04$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
frango9000__advent-of-code-22__62e91dd/src/Day15.kt
import kotlin.math.absoluteValue fun main() { val input = readInput("Day15") printTime { print(Day15.part1(input, 2_000_000)) } printTime { print(Day15.part2(input, 4_000_000)) } } class Day15 { companion object { fun part1(input: List<String>, targetY: Int): Int { val sensorsAndBeacons = input.map { it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } } .map { (x, y) -> Point(x, y) } } val blockedRanges: List<IntRange> = sensorsAndBeacons.mapNotNull { scannerRangeOnRow(it, targetY) }.merge() val blockedXsInYTarget = sensorsAndBeacons.flatten().filter { it.y == targetY }.map { it.x }.toSet() return blockedRanges.sumOf { it.size } - blockedXsInYTarget.size } fun part2(input: List<String>, side: Int): Long { val sensorsAndBeacons = input.map { it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } } .map { (x, y) -> Point(x, y) } } val validRange = 0..side for (y in validRange) { val blockedRanges: List<IntRange> = sensorsAndBeacons.mapNotNull { scannerRangeOnRow(it, y) } val unblocked = validRange.subtract(blockedRanges) if (unblocked.isNotEmpty()) { return unblocked.first().first * 4_000_000L + y } } error("Not Found") } private fun scannerRangeOnRow(points: List<Point>, targetY: Int): IntRange? { val (sensor, beacon) = points val sensorCoverage = sensor.rectilinearDistanceTo(beacon) val yDistanceToYTarget = (targetY - sensor.y).absoluteValue val yOverlapBy = sensorCoverage - yDistanceToYTarget return if (yOverlapBy <= 0) null else (sensor.x - yOverlapBy..sensor.x + yOverlapBy) } // fun part1withArray(input: List<String>, targetY: Int): Int { // val sensorsAndBeacons = input.map { // it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } } // .map { (x, y) -> Point(x, y) } // } // // val offset = sensorsAndBeacons.maxOf { it[0].rectilinearDistanceTo(it[1]) } * 2 // val beaconMaxX = sensorsAndBeacons.maxOf { it[1].x } // val blockedXsInTargetY = BooleanArray(beaconMaxX + offset) // // for ((sensor, beacon) in sensorsAndBeacons) { // val sensorCoverage = sensor.rectilinearDistanceTo(beacon) // val yDistanceToYTarget = (targetY - sensor.y).absoluteValue // val yOverlapBy = sensorCoverage - yDistanceToYTarget // if (yOverlapBy > 0) { // for (x in (sensor.x - (yOverlapBy)) towards (sensor.x + (yOverlapBy))) { // blockedXsInTargetY[x + offset] = true // } // } // } // // val beaconXsInYTarget = sensorsAndBeacons.map { it[1] }.filter { it.y == targetY }.map { it.x } // for (beaconX in beaconXsInYTarget) { // blockedXsInTargetY[beaconX + offset] = false // } // // return blockedXsInTargetY.count { it } // } // // fun part2WithArray(input: List<String>, side: Int): Int { // val sensorsAndBeacons = input.map { // it.substring(10).split(": closest beacon is at ").map { it.split(", ").map { it.substring(2).toInt() } } // .map { (x, y) -> Point(x, y) } // } // val validRange = 0..side // // for (y in validRange) { // val blockedXsInTargetY = BooleanArray(side + 1) // for ((sensor, beacon) in sensorsAndBeacons) { // val sensorCoverage = sensor.rectilinearDistanceTo(beacon) // val yDistanceToYTarget = (y - sensor.y).absoluteValue // val yOverlapBy = sensorCoverage - yDistanceToYTarget // if (yOverlapBy > 0) { // for (x in (sensor.x - (yOverlapBy)) towards (sensor.x + (yOverlapBy))) { // if (x in validRange && y in validRange) blockedXsInTargetY[x] = true // } // } // } // if (blockedXsInTargetY.any { !it }) return blockedXsInTargetY.indexOfFirst { !it } * 4_000_000 + y // } // error("Not Found") // } } class Point(var x: Int = 0, var y: Int = 0) { fun rectilinearDistanceTo(point: Point): Int { return (this.x - point.x).absoluteValue + (this.y - point.y).absoluteValue } override fun toString(): String { return "Point(x=$x, y=$y)" } operator fun component1() = x operator fun component2() = y } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day15.class", "javap": "Compiled from \"Day15.kt\"\npublic final class Day15 {\n public static final Day15$Companion Companion;\n\n public Day15();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Utils.kt
import java.io.File import java.math.BigInteger import java.security.MessageDigest import java.util.function.Predicate import kotlin.math.absoluteValue import kotlin.system.measureNanoTime /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Reads lines from the given input txt file. */ fun readTestInput(name: String) = File("test/kotlin", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16).padStart(32, '0') /** * partitions the given list by a given predicate is true */ fun <E> List<E>.partitionWhen(partitionWhen: Predicate<E>): List<List<E>> { return this.fold(arrayListOf(arrayListOf<E>())) { acc: ArrayList<ArrayList<E>>, curr: E -> if (partitionWhen.test(curr)) { acc.add(arrayListOf()) } else if (acc.lastIndex >= 0) { acc[acc.lastIndex].add(curr) } acc } } /** * partitions the given list by the provided value */ fun <E> List<E>.partitionOnElement(by: E): List<List<E>> { return this.partitionWhen { by?.equals(it) == true } } data class Coordinate(var x: Int = 0, var y: Int = 0) fun printTime(pre: String = "\n[", post: String = "]\n\n", function: () -> Unit) { print("$pre${measureNanoTime { function() }.toFloat() / 1000000}ms$post") } fun Iterable<Int>.product() = this.reduce { acc, i -> acc * i } fun Iterable<Long>.product() = this.reduce { acc, i -> acc * i } infix fun Int.isDivisibleBy(divisor: Int) = this % divisor == 0 infix fun Long.isDivisibleBy(divisor: Long) = this % divisor == 0L /** * Euclid's algorithm for finding the greatest common divisor of a and b. */ fun gcd(a: Long, b: Long): Long = if (b == 0L) a.absoluteValue else gcd(b, a % b) /** * Find the least common multiple of a and b using the gcd of a and b. */ fun lcm(a: Long, b: Long) = (a * b) / gcd(a, b) fun Iterable<Long>.lcm(): Long = reduce(::lcm) fun <R, T> List<List<T>>.mapMatrix(mapper: (T) -> R): List<List<R>> { return this.map { it.map { mapper(it) } } } fun <R, T> List<List<T>>.mapMatrixIndexed(mapper: (Int, Int, T) -> R): List<List<R>> { return this.mapIndexed { i, row -> row.mapIndexed { j, item -> mapper(i, j, item) } } } fun <R, T> List<List<T>>.matrixForEach(mapper: (T) -> R): Unit { return this.forEach { it.forEach { mapper(it) } } } fun <R, T> List<List<T>>.matrixForEachIndexed(mapper: (Int, Int, T) -> R): Unit { return this.forEachIndexed { i, row -> row.forEachIndexed { j, item -> mapper(i, j, item) } } } infix fun Int.towards(to: Int): IntProgression { val step = if (this > to) -1 else 1 return IntProgression.fromClosedRange(this, to, step) } fun Iterable<IntRange>.merge(): List<IntRange> { val sorted = this.filter { !it.isEmpty() }.sortedBy { it.first } sorted.isNotEmpty() || return emptyList() val stack = ArrayDeque<IntRange>() stack.add(sorted.first()) sorted.drop(1).forEach { current -> if (current.last <= stack.last().last) { // } else if (current.first > stack.last().last + 1) { stack.add(current) } else { stack.add(stack.removeLast().first..current.last) } } return stack } val IntRange.size get() = (last - first + 1).coerceAtLeast(0) fun IntRange.subtract(others: Iterable<IntRange>): List<IntRange> { val relevant = others.merge().filter { it overlaps this } if (relevant.isEmpty()) return listOf(this) return buildList { var includeFrom = first relevant.forEach { minus -> if (minus.first > includeFrom) add(includeFrom until minus.first.coerceAtMost(last)) includeFrom = minus.last + 1 } if (includeFrom <= last) add(includeFrom..last) } } infix fun <T : Comparable<T>> ClosedRange<T>.overlaps(other: ClosedRange<T>): Boolean { if (isEmpty() || other.isEmpty()) return false return !(this.endInclusive < other.start || this.start > other.endInclusive) }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String...
frango9000__advent-of-code-22__62e91dd/src/Day14.kt
fun main() { val input = readInput("Day14") printTime { println(Day14.part1(input)) } printTime { println(Day14.part2(input)) } } class Day14 { companion object { fun part1(input: List<String>): Int { val pointMatrix = input.map { it.split(" -> ").map(::Point) } val points = pointMatrix.flatten() val minX = points.minOf { it.x } val maxX = points.maxOf { it.x } val maxY = points.maxOf { it.y } points.forEach { it.x -= minX } val lines = pointMatrix.map { it.windowed(2).map { (start, end) -> Line(start, end) } }.flatten() val map = (0..maxY).map { (minX..maxX).map { "." }.toTypedArray() }.toTypedArray() for (line in lines) { for (y in (line.start.y towards line.end.y)) { for (x in (line.start.x towards line.end.x)) { map[y][x] = "#" } } } map[0][500 - minX] = "+" // map.print() val quickSand = mutableListOf(Point(500 - minX, 0)) val stuckSand = mutableListOf<Point>() while (true) { try { for (sandIndex in (quickSand.lastIndex downTo 0)) { val sand = quickSand[sandIndex] while (true) { if (ifIsEmpty(map, sand.y + 1, sand.x)) { map[sand.y][sand.x] = "." map[++sand.y][sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x - 1)) { map[sand.y][sand.x] = "." map[++sand.y][--sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x + 1)) { map[sand.y][sand.x] = "." map[++sand.y][++sand.x] = "o" } else { stuckSand.add(sand) break } } } } catch (e: ArrayIndexOutOfBoundsException) { break } if (!quickSand.removeAll(stuckSand)) break quickSand.add(Point(500 - minX, 0)) } // map.print() return stuckSand.size } fun part2(input: List<String>): Int { val pointMatrix = input.map { it.split(" -> ").map(::Point) } val points = pointMatrix.flatten() val maxY = points.maxOf { it.y } val base = maxY + 2 val lines = pointMatrix.map { it.windowed(2).map { (start, end) -> Line(start, end) } }.flatten() val map = (0..base).map { (0..700).map { "." }.toTypedArray() }.toTypedArray() for (line in lines) { for (y in (line.start.y towards line.end.y)) { for (x in (line.start.x towards line.end.x)) { map[y][x] = "#" } } } map[base].fill("#") map[0][500] = "+" val quickSand = mutableListOf(Point(500, 0)) val stuckSand = mutableListOf<Point>() while (true) { try { for (sandIndex in (quickSand.lastIndex downTo 0)) { val sand = quickSand[sandIndex] while (true) { if (ifIsEmpty(map, sand.y + 1, sand.x)) { map[sand.y][sand.x] = "." map[++sand.y][sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x - 1)) { map[sand.y][sand.x] = "." map[++sand.y][--sand.x] = "o" } else if (ifIsEmpty(map, sand.y + 1, sand.x + 1)) { map[sand.y][sand.x] = "." map[++sand.y][++sand.x] = "o" } else { stuckSand.add(sand) if (sand.y == 0) { map[0][sand.x] = "o" throw ArrayIndexOutOfBoundsException() } break } } } quickSand.removeAll(stuckSand) } catch (e: ArrayIndexOutOfBoundsException) { break } quickSand.add(Point(500, 0)) } // map.print() return stuckSand.size } private fun ifIsEmpty(map: Array<Array<String>>, y: Int = 0, x: Int = 0) = map[y][x] == "." } data class Point(var x: Int = 0, var y: Int = 0) { constructor(input: String) : this() { val (x, y) = input.split(',').map { it.toInt() } this.x = x this.y = y } } data class Line(val start: Point, val end: Point) } private fun <T> Array<Array<T>>.print() { this.forEach { it.forEach { print(it) }; println() }; println() }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class Day14Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day14\n 2: invokestatic #14 // Method UtilsK...
frango9000__advent-of-code-22__62e91dd/src/Day12.kt
fun main() { val input = readInput("Day12") printTime { println(Day12.part1(input)) } printTime { println(Day12.part2(input)) } } class Day12 { companion object { fun part1(input: List<String>): Int { val (end, start) = input.toHeightGraph() return end.getShortestPathBfs { it == start } } fun part2(input: List<String>): Int { val (end) = input.toHeightGraph() return end.getShortestPathBfs { it.height == 0 } } } } class Node(val height: Int, val neighbors: MutableList<Node> = mutableListOf()) { var distance = 0 fun getShortestPathBfs(isDestination: (Node) -> Boolean): Int { val queue: ArrayDeque<Node> = ArrayDeque() val visited = mutableSetOf(this) queue.add(this) while (queue.isNotEmpty()) { val node = queue.removeFirst() if (isDestination(node)) return node.distance node.neighbors.filter { it.height >= node.height - 1 }.filter { it !in visited }.forEach { it.distance = node.distance + 1 queue.add(it) visited.add(it) } } throw IllegalStateException("Could not find a path to the target node") } //private fun getShortestPathDfs(from: Node, to: Node, path: List<Node> = listOf()): Long { // if (from == to) { // return 0L // } // val validPaths = from.neighbors.filter { !path.contains(it) } // if (validPaths.isNotEmpty()) { // return validPaths.minOf { 1L + getShortestPathDfs(it, to, listOf(*path.toTypedArray(), from)) } // } // return Int.MAX_VALUE.toLong() //} } fun List<String>.toHeightGraph(): List<Node> { var start = Node(0) var end = Node(0) val nodes: List<List<Node>> = this.map { it.toCharArray().map { height -> val newNode: Node when (height) { 'S' -> { newNode = Node(0) start = newNode } 'E' -> { newNode = Node('z' - 'a') end = newNode } else -> newNode = Node(height - 'a') } newNode } } nodes.matrixForEachIndexed { i, j, _ -> if (i > 0) { nodes[i][j].neighbors.add(nodes[i - 1][j]) } if (i < nodes.lastIndex) { nodes[i][j].neighbors.add(nodes[i + 1][j]) } if (j > 0) { nodes[i][j].neighbors.add(nodes[i][j - 1]) } if (j < nodes[i].lastIndex) { nodes[i][j].neighbors.add(nodes[i][j + 1]) } } return listOf(end, start) }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day12$Companion.class", "javap": "Compiled from \"Day12.kt\"\npublic final class Day12$Companion {\n private Day12$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
frango9000__advent-of-code-22__62e91dd/src/Day13.kt
import kotlin.math.max fun main() { val input = readInput("Day13") printTime { println(Day13.part1(input)) } printTime { println(Day13.part2(input)) } } class Day13 { companion object { fun part1(input: List<String>): Int { val packetPairs = input.partitionOnElement("").map { it.map { parsePacket(it.substring(1, it.lastIndex)) } } val packetComparisons: List<Int> = packetPairs.map { (first, second) -> comparePackets(first, second) } return packetComparisons.withIndex().filter { it.value <= 0 }.sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val packet2 = parsePacket("[2]") val packet6 = parsePacket("[6]") val packets = input.filter { it != "" } .map { parsePacket(it.substring(1, it.lastIndex)) }.toMutableList().apply { add(packet2); add(packet6) } val sortedPackets = packets.sortedWith { p0, p1 -> comparePackets(p0, p1) } return sortedPackets.withIndex() .filter { comparePackets(packet2, it.value) == 0 || comparePackets(packet6, it.value) == 0 } .map { it.index + 1 }.product() } private fun comparePackets(first: Any, second: Any): Int { if (first is List<*> && second is List<*>) { for (index in 0..max(first.lastIndex, second.lastIndex)) { if (first.lastIndex < index) return -1 if (second.lastIndex < index) return 1 val packetComparison = comparePackets(first[index]!!, second[index]!!) if (packetComparison == 0) continue else return packetComparison } return 0 } if (first is List<*>) return comparePackets(first, listOf(second)) if (second is List<*>) return comparePackets(listOf(first), second) return (first as Int) - (second as Int) } private fun parsePacket(substring: String): List<Any> { val root = mutableListOf<Any>() val stack: ArrayDeque<MutableList<Any>> = ArrayDeque() stack.add(root) var index = 0 while (index < substring.length) { when (substring[index]) { '[' -> { val newStack = mutableListOf<Any>() stack.last().add(newStack) stack.addLast(newStack) index++ } ']' -> { stack.removeLast() index++ } ',' -> index++ else -> { val fromNumber = substring.substring(index) var indexOfNextClose = fromNumber.indexOfFirst { it == ']' || it == ',' } if (indexOfNextClose < 0) indexOfNextClose = fromNumber.length val number = fromNumber.substring(0, indexOfNextClose).toInt() stack.last().add(number) index += indexOfNextClose } } } return root } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day13.class", "javap": "Compiled from \"Day13.kt\"\npublic final class Day13 {\n public static final Day13$Companion Companion;\n\n public Day13();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Day16.kt
import kotlin.math.max fun main() { val input = readInput("Day16") printTime { print(Day16.part1(input)) } printTime { print(Day16.part2(input)) } } class Day16 { companion object { fun part1(input: List<String>): Int { val valves = input.map { it.split( "Valve ", " has flow rate=", "; tunnel leads to valve ", "; tunnels lead to valves " ).drop(1) }.map { Valve(it[0], it[1].toInt(), it[2].split(", ").toSet()) } for (valve in valves) { valve.tunnels.addAll(valve.tunnelsTo.map { to -> valves.find { it.name == to }!! }) } val valvesMap: Map<Valve, Map<Valve, Int>> = valves.filter { origin -> origin.rate > 0 || origin.name == "AA" }.associateWith { origin -> valves.filter { it !== origin && it.rate > 0 }.associateWith { target -> bfs(origin, target) } } val valvesIndexes: Map<Valve, Int> = valvesMap.keys.withIndex().associateWith { it.index }.mapKeys { it.key.value } return dfs(valves.find { it.name == "AA" }!!, valvesMap, valvesIndexes) } private fun bfs(from: Valve, target: Valve): Int { val queue = ArrayDeque<Pair<Valve, Int>>() queue.add(from to 0) val visited = mutableSetOf<Valve>() while (queue.isNotEmpty()) { val next = queue.removeFirst() if (visited.contains(next.first)) continue visited.add(next.first) if (target == next.first) { return next.second } queue.addAll(next.first.tunnels.map { it to next.second + 1 }) } error("No Path Found") } private fun dfs( start: Valve, valvesMap: Map<Valve, Map<Valve, Int>>, valvesIndexes: Map<Valve, Int>, timeLeft: Int = 30, valvesState: Int = 0 ): Int { var maxPressure = 0 for ((neighbor, distance) in valvesMap[start]!!.entries) { val bit = 1 shl valvesIndexes[neighbor]!! if (valvesState and bit > 0) continue val newTimeLeft = timeLeft - distance - 1 if (newTimeLeft <= 0)//try 1 continue maxPressure = max( maxPressure, dfs( neighbor, valvesMap, valvesIndexes, newTimeLeft, valvesState or bit ) + neighbor.rate * newTimeLeft ) } return maxPressure } private fun dfs_v1(path: List<Valve>, valvesMap: Map<Valve, Map<Valve, Int>>, timeLeft: Int = 30): Int { if (timeLeft <= 1) { return 0 } val current = path.last() val timeInCurrentCave = if (current.rate > 0) 1 else 0 val valveTotalPressure = current.rate * (timeLeft - timeInCurrentCave) val openValves = valvesMap[current]!!.filter { !path.contains(it.key) } if (openValves.isEmpty()) { return valveTotalPressure } return valveTotalPressure + (openValves.maxOfOrNull { (target, distance) -> dfs_v1(listOf(*path.toTypedArray(), target), valvesMap, timeLeft - (timeInCurrentCave + distance)) } ?: 0) } fun part2(input: List<String>): Int { val valves = input.map { it.split( "Valve ", " has flow rate=", "; tunnel leads to valve ", "; tunnels lead to valves " ).drop(1) }.map { Valve(it[0], it[1].toInt(), it[2].split(", ").toSet()) } for (valve in valves) { valve.tunnels.addAll(valve.tunnelsTo.map { to -> valves.find { it.name == to }!! }) } val valvesMap: Map<Valve, Map<Valve, Int>> = valves.filter { origin -> origin.rate > 0 || origin.name == "AA" }.associateWith { origin -> valves.filter { it !== origin && it.rate > 0 }.associateWith { target -> bfs(origin, target) } } val valvesIndexes: Map<Valve, Int> = valvesMap.keys.withIndex().associateWith { it.index }.mapKeys { it.key.value } val start = valves.find { it.name == "AA" }!! val mask = (1 shl valvesIndexes.size) - 1 var max = 0 for (i in 0..(mask / 2)) { max = max( max, dfs(start, valvesMap, valvesIndexes, 26, i) + dfs(start, valvesMap, valvesIndexes, 26, mask xor i) ) } return max } } class Valve(val name: String, val rate: Int, val tunnelsTo: Set<String>) { val tunnels: MutableSet<Valve> = mutableSetOf() override fun toString(): String { return "Valve(name='$name', rate=$rate)" } override fun equals(other: Any?): Boolean { return name == (other as Valve).name } override fun hashCode(): Int { return name.hashCode() } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day16$Valve.class", "javap": "Compiled from \"Day16.kt\"\npublic final class Day16$Valve {\n private final java.lang.String name;\n\n private final int rate;\n\n private final java.util.Set<java.lang.String> tunnelsTo;\n\n private final java.util.S...
frango9000__advent-of-code-22__62e91dd/src/Day08.kt
fun main() { val input = readInput("Day08") println(Day08.part1(input)) println(Day08.part2(input)) } class Day08 { companion object { fun part1(input: List<String>): Int { val forest = input.map { it.split("").filter { c -> c.isNotEmpty() }.map { character -> character.toInt() } } val visibilityForest = input.map { it.map { false }.toMutableList() } for (i in forest.indices) { var currentTop = -1 for (j in forest[i].indices) { if (forest[i][j] > currentTop) { currentTop = forest[i][j] visibilityForest[i][j] = true } } currentTop = -1 for (j in forest[i].indices.reversed()) { if (forest[i][j] > currentTop) { currentTop = forest[i][j] visibilityForest[i][j] = true } } } for (j in forest.first().indices) { var currentTop = -1 for (i in forest.indices) { if (forest[i][j] > currentTop) { currentTop = forest[i][j] visibilityForest[i][j] = true } } currentTop = -1 for (i in forest.indices.reversed()) { if (forest[i][j] > currentTop) { currentTop = forest[i][j] visibilityForest[i][j] = true } } } return visibilityForest.flatten().count { it } } fun part2(input: List<String>): Int { val forest = input.map { it.split("").filter { c -> c.isNotEmpty() }.map { character -> character.toInt() } } val forestOfScores = input.map { it.map { 0 }.toMutableList() } for (i in forest.indices) { if (i == 0 || i == forest.size - 1) continue for (j in forest[i].indices) { if (j == 0 || j == forest[i].size - 1) continue var leftDistance = 0 for (j2 in (j - 1 downTo 0)) { leftDistance++ if (forest[i][j2] >= forest[i][j]) { break } } if (leftDistance == 0) continue var rightDistance = 0 for (j2 in (j + 1 until forest[i].size)) { rightDistance++ if (forest[i][j2] >= forest[i][j]) { break } } if (rightDistance == 0) continue var topDistance = 0 for (i2 in (i - 1 downTo 0)) { topDistance++ if (forest[i2][j] >= forest[i][j]) { break } } if (topDistance == 0) continue var botDistance = 0 for (i2 in (i + 1 until forest.size)) { botDistance++ if (forest[i2][j] >= forest[i][j]) { break } } if (botDistance == 0) continue forestOfScores[i][j] = leftDistance * rightDistance * topDistance * botDistance } } return forestOfScores.flatten().max() } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day08.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08 {\n public static final Day08$Companion Companion;\n\n public Day08();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Day05.kt
fun main() { val input = readInput("Day05") println(Day05.part1(input)) println(Day05.part2(input)) } data class Move(val size: Int, val from: Int, val to: Int) class Day05 { companion object { fun part1(input: List<String>): String { val (initial, rawActions) = input.partitionOnElement("") val numberOfStacks = initial.maxOf { it.length } / 3 val stacks: List<ArrayDeque<Char>> = (1..numberOfStacks).toList().map { ArrayDeque<Char>(initial.size * 2) } val initialReversed = initial.dropLast(1).reversed() for (level in initialReversed) { for (i in 1..numberOfStacks) { val value = level.getOrNull((4 * i) - 3) if (value != null && value != ' ') { stacks[i - 1].addLast(value) } } } val actions = rawActions.map { it.split("move ", " from ", " to ").subList(1, 4).map { v -> v.toInt() } } .map { (size, from, to) -> Move(size, from, to) } for (action in actions) { for (i in 0 until action.size) { stacks[action.to - 1].addLast(stacks[action.from - 1].removeLast()) } } return stacks.mapNotNull { it.removeLastOrNull() }.joinToString("") } fun part2(input: List<String>): String { val (initial, rawActions) = input.partitionOnElement("") val numberOfStacks = initial.maxOf { it.length } / 3 val stacks: MutableList<ArrayDeque<Char>> = (1..numberOfStacks).toList().map { ArrayDeque<Char>(initial.size * 2) }.toMutableList() val initialReversed = initial.dropLast(1).reversed() for (level in initialReversed) { for (i in 1..numberOfStacks) { val value = level.getOrNull((4 * i) - 3) if (value != null && value != ' ') { stacks[i - 1].addLast(value) } } } val actions = rawActions.map { it.split("move ", " from ", " to ").subList(1, 4).map { v -> v.toInt() } } .map { (size, from, to) -> Move(size, from, to) } for (action in actions) { val splitPoint = stacks[action.from - 1].size - action.size val newFrom = stacks[action.from - 1].subList(0, splitPoint) val swap = stacks[action.from - 1].subList(splitPoint, stacks[action.from - 1].size) stacks[action.from - 1] = ArrayDeque(newFrom) stacks[action.to - 1].addAll(swap) } return stacks.mapNotNull { it.removeLastOrNull() }.joinToString("") } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day05Kt.class", "javap": "Compiled from \"Day05.kt\"\npublic final class Day05Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day05\n 2: invokestatic #14 // Method UtilsK...
frango9000__advent-of-code-22__62e91dd/src/Day03.kt
fun main() { val input = readInput("Day03") println(Day03.part1(input)) println(Day03.part2(input)) } class Day03 { companion object { fun part1(input: List<String>): Int { return input.map { it.chunked(it.length / 2) } .map { it[0].filter { x -> it[1].contains(x) }.toCharArray().first() } .sumOf { it.code - if (it.isUpperCase()) 38 else 96 } } fun part2(input: List<String>): Int { return input.chunked(3).map { it[0].filter { x -> it[1].contains(x) && it[2].contains(x) }.toCharArray().first() }.sumOf { it.code - if (it.isUpperCase()) 38 else 96 } } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day03$Companion.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03$Companion {\n private Day03$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
frango9000__advent-of-code-22__62e91dd/src/Day11.kt
fun main() { val input = readInput("Day11") printTime { println(Day11.part1(input)) } printTime { println(Day11.part2(input)) } } class Day11 { companion object { fun part1(input: List<String>): Long { val monkeys = input.toMonkeys() monkeys.playKeepAway { it.floorDiv(3) } return monkeys.getMonkeyBusiness() } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val commonMod = monkeys.map { it.divideBy }.lcm().toInt() monkeys.playKeepAway(10000) { it % commonMod } return monkeys.getMonkeyBusiness() } } } data class Monkey( val divideBy: Long, val trueTo: Int, val falseTo: Int, val items: MutableList<Long> = mutableListOf(), val operation: (Long) -> Long ) { var inspections = 0L } fun Long.doOperation(charOperator: Char, x: Long) = when (charOperator) { '+' -> this + x '*' -> this * x else -> throw IllegalArgumentException("Not supported") } fun List<String>.toMonkeys(): List<Monkey> { return this.chunked(7).map { val items: MutableList<Long> = it[1].substring(18).split(", ").map { item -> item.toLong() }.toMutableList() val (operator, operand) = it[2].substring(23).split(" ") val operation: (Long) -> Long = { old: Long -> old.doOperation( operator.toCharArray().first(), if (operand == "old") old else operand.toLong() ) } val divideBy = it[3].substring(21).toLong() val trueTo = it[4].substring(29).toInt() val falseTo = it[5].substring(30).toInt() Monkey(divideBy, trueTo, falseTo, items, operation) } } fun List<Monkey>.playKeepAway(rounds: Int = 20, escalationPrevention: (Long) -> Long) { repeat(rounds) { for (monkey in this) { for (item in monkey.items) { monkey.inspections++ val worry = escalationPrevention(monkey.operation(item)) val toMonkey = if (worry isDivisibleBy monkey.divideBy) monkey.trueTo else monkey.falseTo this[toMonkey].items.add(worry) } monkey.items.clear() } } } fun List<Monkey>.getMonkeyBusiness() = this.map { it.inspections }.sortedDescending().take(2).product()
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day11.class", "javap": "Compiled from \"Day11.kt\"\npublic final class Day11 {\n public static final Day11$Companion Companion;\n\n public Day11();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Day02.kt
fun main() { val input = readInput("Day02") println(Day02.part1(input)) println(Day02.part2(input)) } class Day02 { companion object { private fun checkGuessRound(it: String): Int { val (a, b) = it.split(" ").map { it.toCharArray().first() } val selectionPoints = b.code - 87 val score = when (selectionPoints == a.code - 64) { true -> 1 false -> when (b) { 'X' -> when (a) { 'C' -> 2 else -> 0 } 'Y' -> when (a) { 'A' -> 2 else -> 0 } 'Z' -> when (a) { 'B' -> 2 else -> 0 } else -> 0 } } return selectionPoints + (score * 3) } fun part1(input: List<String>): Int { return input.sumOf { checkGuessRound(it) } } private fun checkExpectedRound(it: String): Int { val (a, b) = it.split(" ").map { it.toCharArray().first() } val score = (b.code - 88) val selectionPoints = when (score) { 0 -> when (a) { 'A' -> 3 'B' -> 1 else -> 2 } 1 -> when (a) { 'A' -> 1 'B' -> 2 else -> 3 } 2 -> when (a) { 'A' -> 2 'B' -> 3 else -> 1 } else -> 0 } return selectionPoints + (score * 3) } fun part2(input: List<String>): Int { return input.sumOf { checkExpectedRound(it) } } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day02$Companion.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02$Companion {\n private Day02$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
frango9000__advent-of-code-22__62e91dd/src/Day07.kt
fun main() { val input = readInput("Day07") println(Day07.part1(input)) println(Day07.part2(input)) } class Day07 { companion object { fun getFolderSizes(input: List<String>): MutableMap<String, Int> { val folders: MutableMap<String, Int> = mutableMapOf() val stack: ArrayDeque<String> = ArrayDeque() input.filterNot { it == "$ ls" || it.startsWith("dir") }.forEach { if (it.startsWith("$ cd")) { val cdParam = it.subSequence(5, it.length).toString() if (cdParam == "..") { stack.removeLast() } else { val folderRoute = stack.joinToString("/") + "/$cdParam" stack.addLast(folderRoute) if (!folders.containsKey(folderRoute)) { folders[folderRoute] = 0 } } } else { val fileSize = it.split(" ").first().toInt() for (parent in stack) { folders[parent] = folders[parent]?.plus(fileSize) ?: fileSize } } } return folders } fun part1(input: List<String>): Int { val folders: MutableMap<String, Int> = getFolderSizes(input) return folders.values.filter { it <= 100000 }.sum() } fun part2(input: List<String>): Int { val folders: MutableMap<String, Int> = getFolderSizes(input) val totalSize = folders["//"] val requiredCleanup = -40000000 + totalSize!! return folders.values.sorted().first { it >= requiredCleanup } } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day07\n 2: invokestatic #14 // Method UtilsK...
frango9000__advent-of-code-22__62e91dd/src/Day09.kt
fun main() { val input = readInput("Day09") println(Day09.part1(input)) println(Day09.part2(input)) } data class HeadMovement(val direction: Direction, val steps: Int) enum class Direction { U, R, D, L, } class Day09 { companion object { fun part1(input: List<String>): Int { return getTailPositions(input, 2) } fun part2(input: List<String>): Int { return getTailPositions(input, 10) } fun getTailPositions(input: List<String>, numOfKnots: Int): Int { val moves = input.map { it.split(" ") }.map { HeadMovement(Direction.valueOf(it[0]), it[1].toInt()) } val knots = (1..numOfKnots.coerceAtLeast(2)).toList().map { Coordinate(0, 0) } val tailPositions = mutableSetOf<String>("0,0") val head = knots.first() val tail = knots.last() for (move in moves) { for (step in (1..move.steps)) { when (move.direction) { Direction.R -> head.x++ Direction.U -> head.y-- Direction.D -> head.y++ Direction.L -> head.x-- } for (index in (1 until knots.size)) { val lead = knots[index - 1] val current = knots[index] if (current.x in (lead.x - 1..lead.x + 1) && current.y in (lead.y - 1..lead.y + 1)) break if (lead.x > current.x) current.x++ else if (lead.x < current.x) current.x-- if (lead.y > current.y) current.y++ else if (lead.y < current.y) current.y-- } tailPositions.add("${tail.x},${tail.y}") } } return tailPositions.size } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day09.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09 {\n public static final Day09$Companion Companion;\n\n public Day09();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Day10.kt
fun main() { val input = readInput("Day10") printTime { println(Day10.part1(input)) } printTime { println(Day10.part2(input)) } } class Day10 { companion object { fun part1(input: List<String>): Int { var signalStrength = 0 var x = 1 var cycle = 1 for (command in input) { cycle++ if ((cycle - 20) % 40 == 0) { signalStrength += cycle * x } if (command != "noop") { x += command.substring(5).toInt() cycle++ if ((cycle - 20) % 40 == 0) { signalStrength += cycle * x } } } return signalStrength } fun part2(input: List<String>): String { var crt = "" var x = 1 var cycle = 1 for (command in input) { val lineOffset = (cycle / 40) * 40 crt += if (cycle - lineOffset - 1 in (x + -1..x + 1)) "▓" else "░" cycle++ if (command != "noop") { crt += if (cycle - lineOffset - 1 in (x - 1..x + 1)) "▓" else "░" x += command.substring(5).toInt() cycle++ } } return crt.chunked(40).joinToString("\n") } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day10.class", "javap": "Compiled from \"Day10.kt\"\npublic final class Day10 {\n public static final Day10$Companion Companion;\n\n public Day10();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
frango9000__advent-of-code-22__62e91dd/src/Day18.kt
import javax.swing.JOptionPane fun main() { val input = readInput("Day18") printTime { print(Day18.part1(input)) } printTime { print(Day18.part1Bitwise(input)) } printTime { print(Day18.part2(input)) } } class Day18 { companion object { fun part1(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.getNumberOfSidesArrayImpl() } fun part1Bitwise(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.getNumberOfSides() } fun part2(input: List<String>): Int { val cubes = input.map { it.split(",").map { it.toInt() } }.map { (x, y, z) -> Position(x, y, z) } return cubes.withoutBubbles().getNumberOfSides() } } } private fun List<Position>.withoutBubbles(): List<Position> { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val occupiedArea = Array(maxX + 1) { Array(maxY + 1) { Array(maxZ + 1) { false } } } for ((x, y, z) in this) { occupiedArea[x][y][z] = true } // showSlice(occupiedArea) val floodedArea = Array(maxX + 1) { Array(maxY + 1) { Array(maxZ + 1) { false } } } val queue = ArrayDeque<Position>() queue.add(Position(0, 0, 0)) while (queue.isNotEmpty()) { val (x, y, z) = queue.removeFirst() if (!floodedArea[x][y][z] && !occupiedArea[x][y][z]) { floodedArea[x][y][z] = true if (x > 0) { queue.add(Position(x - 1, y, z)) } if (x < maxX) { queue.add(Position(x + 1, y, z)) } if (y > 0) { queue.add(Position(x, y - 1, z)) } if (y < maxY) { queue.add(Position(x, y + 1, z)) } if (z > 0) { queue.add(Position(x, y, z - 1)) } if (z < maxZ) { queue.add(Position(x, y, z + 1)) } } } // showSlice(floodedArea) return floodedArea.mapIndexed { x, table -> table.mapIndexed { y, row -> row.mapIndexed { z, flooded -> if (flooded) null else Position( x, y, z ) } } }.flatten().flatten().filterNotNull() } data class Position(val x: Int, val y: Int, val z: Int) fun List<Position>.getNumberOfSides(): Int { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val sideX = (0..maxY).map { (0..maxZ).map { 0 }.toMutableList() } val sideY = (0..maxZ).map { (0..maxX).map { 0 }.toMutableList() } val sideZ = (0..maxX).map { (0..maxY).map { 0 }.toMutableList() } for (cube in this) { sideX[cube.y][cube.z] = sideX[cube.y][cube.z] xor (1 shl cube.x) sideX[cube.y][cube.z] = sideX[cube.y][cube.z] xor (1 shl cube.x + 1) sideY[cube.z][cube.x] = sideY[cube.z][cube.x] xor (1 shl cube.y) sideY[cube.z][cube.x] = sideY[cube.z][cube.x] xor (1 shl cube.y + 1) sideZ[cube.x][cube.y] = sideZ[cube.x][cube.y] xor (1 shl cube.z) sideZ[cube.x][cube.y] = sideZ[cube.x][cube.y] xor (1 shl cube.z + 1) } val numOfSidesX = sideX.sumOf { it.sumOf { Integer.bitCount(it) } } val numOfSidesY = sideY.sumOf { it.sumOf { Integer.bitCount(it) } } val numOfSidesZ = sideZ.sumOf { it.sumOf { Integer.bitCount(it) } } return numOfSidesX + numOfSidesY + numOfSidesZ } fun List<Position>.getNumberOfSidesArrayImpl(): Int { val maxX = maxOf { it.x } val maxY = maxOf { it.y } val maxZ = maxOf { it.z } val sideX = (0..maxY).map { (0..maxZ).map { (0..maxX + 1).map { false }.toMutableList() } } val sideY = (0..maxZ).map { (0..maxX).map { (0..maxY + 1).map { false }.toMutableList() } } val sideZ = (0..maxX).map { (0..maxY).map { (0..maxZ + 1).map { false }.toMutableList() } } for (cube in this) { sideX[cube.y][cube.z][cube.x] = !sideX[cube.y][cube.z][cube.x] sideX[cube.y][cube.z][cube.x + 1] = !sideX[cube.y][cube.z][cube.x + 1] sideY[cube.z][cube.x][cube.y] = !sideY[cube.z][cube.x][cube.y] sideY[cube.z][cube.x][cube.y + 1] = !sideY[cube.z][cube.x][cube.y + 1] sideZ[cube.x][cube.y][cube.z] = !sideZ[cube.x][cube.y][cube.z] sideZ[cube.x][cube.y][cube.z + 1] = !sideZ[cube.x][cube.y][cube.z + 1] } val numOfSidesX = sideX.sumOf { it.sumOf { it.filter { it }.count() } } val numOfSidesY = sideY.sumOf { it.sumOf { it.filter { it }.count() } } val numOfSidesZ = sideZ.sumOf { it.sumOf { it.filter { it }.count() } } return numOfSidesX + numOfSidesY + numOfSidesZ } fun showSlice(area: Array<Array<Array<Boolean>>>) { var x = 0 var result: Int = -1 while (true) { val slice = area[x].map { it.map { if (it) "_" else "#" }.joinToString("") }.joinToString("\n") result = JOptionPane.showConfirmDialog(null, "$x \n\n$slice\n\n Next Slice?") when (result) { JOptionPane.YES_OPTION -> if (x > 0) x-- JOptionPane.NO_OPTION -> if (x < area.lastIndex) x++ JOptionPane.CANCEL_OPTION -> break } } }
[ { "class_path": "frango9000__advent-of-code-22__62e91dd/Day18.class", "javap": "Compiled from \"Day18.kt\"\npublic final class Day18 {\n public static final Day18$Companion Companion;\n\n public Day18();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object....
davidwhitney__Aoc2023__7989c1b/day2-kotlin/src/main/kotlin/GameRequirements.kt
import java.util.stream.Stream class GameRequirements(val gameId: Int, private val requirements: HashMap<String, Int>) { val power: Int get() { return requirements["red"]!! * requirements["green"]!! * requirements["blue"]!!; } fun isViable(red: Int, green: Int, blue: Int): Boolean { return (requirements["red"]!! <= red && requirements["green"]!! <= green && requirements["blue"]!! <= blue); } override fun toString(): String { return this.gameId.toString() + " " + this.requirements.toString() + " Power: " + power.toString(); } companion object { fun fromLine(line: String): GameRequirements { val parts = line.split(": ", "; "); val rounds = parts.slice(1..<parts.size); val gameId = parts[0].replace("Game ", "").toInt(); val highestRankMap = hashMapOf<String, Int>(); highestRankMap["red"] = 0; highestRankMap["blue"] = 0; highestRankMap["green"] = 0; for (set in rounds) { val counts = set.split(", "); for (item in counts) { val itemParts = item.split(" "); val type = itemParts[1]; val count = itemParts[0].toInt(); val previous = highestRankMap[type]!!; if (count > previous) { highestRankMap[type] = count; } } } return GameRequirements(gameId, highestRankMap); } } } fun List<String>.toGameRequirementsStream(): Stream<GameRequirements> { return this.stream().map{ GameRequirements.fromLine(it) }; } fun Stream<GameRequirements>.viableGames(red: Int, green: Int, blue: Int): Stream<GameRequirements> { return this.filter{ it.isViable(red, green, blue)}; } fun Stream<GameRequirements>.sumOfIds(): Int { return this.mapToInt { it.gameId }.sum(); }
[ { "class_path": "davidwhitney__Aoc2023__7989c1b/GameRequirements$Companion.class", "javap": "Compiled from \"GameRequirements.kt\"\npublic final class GameRequirements$Companion {\n private GameRequirements$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method ja...
Abijeet123__KotlinAlgorithmsImplementations__902adc3/Graph.kt
import java.util.* private fun readLn() = readLine()!! // string line private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles var n : Int = 1024 var visited = BooleanArray(n) { false } var adj = Array(n) { mutableListOf<Pair<Int,Int>>() } fun toLeaf(root : Int) : Int { if(adj[root].size == 0) return 0 var max = 0 for (i in adj[root]){ max = maxOf(max, 1 + toLeaf(i.first)) } return max } fun diameter() : Int{ var dia = 0 for (i in 0 until n){ var max1 = 0 var max2 = 0 for (j in adj[0]){ var t = 1 + toLeaf(j.first) if (t > max1){ max2 = max1 max1 = t } dia = maxOf(dia, max1 + max2) } } return dia } fun dfs(root : Int){ if (visited[root]) return visited[root] = true println(root) for(i in adj[root]){ dfs(i.first) } } fun dikstra(root : Int) : Array<Int> { var distance = Array(n) { Int.MAX_VALUE } var processed = BooleanArray(n) { false } distance[root] = 0 val compareByDistance: Comparator<Pair<Int,Int>> = compareBy { it.first } var Pq = PriorityQueue<Pair<Int,Int>>(compareByDistance) Pq.add(Pair(0,root)) while (Pq.isNotEmpty()){ var a = Pq.peek().second Pq.remove() if(processed[a]) continue processed[a] = true for( u in adj[a]){ var b = u.first var w = u.second if(distance[a] + w < distance[b]){ distance[b] = distance[a] + w Pq.add(Pair(-distance[b],b)) } } } return distance } fun main(){ n = readInt() var q = readInt() for (i in 0 until q){ val (a,b,c) = readInts() adj[a - 1].add(Pair(b - 1,c)) //adj[b - 1].add(Pair(a-1,c)) } // val distance = dikstra(0) // for (i in distance) // println(i) println(diameter()) }
[ { "class_path": "Abijeet123__KotlinAlgorithmsImplementations__902adc3/GraphKt$dikstra$$inlined$compareBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class GraphKt$dikstra$$inlined$compareBy$1<T> implements java.util.Comparator {\n public GraphKt$dikstra$$inlined$compareBy$1();\n C...
drochecsp2017__special_pots_shop__20727dd/special_shop.kt
import kotlin.math.round; class Parabola(potCount: Long, xMult: Long, yMult: Long) { private val coeffA = xMult + yMult; private val coeffB = -2 * yMult * potCount; private val coeffC = potCount * potCount * yMult; fun minXCoord(): Long { val numerator = -1.0 * coeffB; val denominator = coeffA * 2.0; val result = round(numerator / denominator); return result.toLong(); } fun solveAt(xCoord: Double): Long { val termA = xCoord * xCoord * coeffA; val termB = xCoord * coeffB; val termC = coeffC.toDouble(); val realResult = termA + termB + termC; return realResult.toLong(); } } fun solveCase(potCount: Long, xMult: Long, yMult: Long): Long { val eq = Parabola(potCount, xMult, yMult); val optimal_a_pots: Long = eq.minXCoord(); val soln: Long = eq.solveAt(optimal_a_pots.toDouble()); return soln; } fun parseTestCase(): Unit { val caseParams = readLine()!!.split(" "); val potsToBuy = caseParams[0].toLong(); val xCost = caseParams[1].toLong(); val yCost = caseParams[2].toLong(); val result = solveCase(potsToBuy, xCost, yCost); println(result); } fun main() { val caseCount = readLine()!!.toInt(); for (i in 1..caseCount) { parseTestCase(); } }
[ { "class_path": "drochecsp2017__special_pots_shop__20727dd/Special_shopKt.class", "javap": "Compiled from \"special_shop.kt\"\npublic final class Special_shopKt {\n public static final long solveCase(long, long, long);\n Code:\n 0: new #8 // class Parabola\n 3: dup...
jorander__advent-of-code-2022__1681218/src/Utils.kt
import java.io.File import java.math.BigInteger import java.security.MessageDigest /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt").readLines() /** * Converts string to md5 hash. */ fun String.md5(): String = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())).toString(16) /** * From Day 1 solution. * Chunks a list by the entry that matches the given predicate. */ fun <E> List<E>.chunked(predicate: (E) -> Boolean): List<List<E>> { tailrec fun <E> List<E>.accumulatedChunked(acc: List<List<E>>, predicate: (E) -> Boolean): List<List<E>> = if (this.isEmpty()) { acc } else { val firstList = this.takeWhile { !predicate(it) } val rest = this.dropWhile { !predicate(it) }.dropWhile(predicate) rest.accumulatedChunked(acc + listOf(firstList), predicate) } return this.accumulatedChunked(emptyList(), predicate) } /** * Creates pairs with all combinations of elements in the two collections. */ infix fun <E> Collection<E>.cartesianProduct(r2: Collection<E>): List<Pair<E, E>> { return flatMap { x -> r2.map { y -> x to y } } } /** * Some classes and methods to handle positions and movements in a 2D-space. */ data class Position2D(val x: Int, val y: Int) { infix operator fun plus(movement: Movement2D) = Position2D(this.x + movement.dx, this.y + movement.dy) infix operator fun minus(other: Position2D) = Movement2D(this.x - other.x, this.y - other.y) fun isOnOuterEdgeIn(grid: Grid2D<*>) = (x == 0) || (x == grid.width - 1) || (y == 0) || (y == grid.height - 1) companion object { fun from(p: Pair<Int, Int>) = Position2D(p.first, p.second) } } /** * A zero-indexed 2D-space where (0,0) is in the top left corner. */ interface Grid2D<out E> { val height: Int val width: Int val allPositions: List<Position2D> companion object { @JvmName("from1") fun from(data: List<CharSequence>): Grid2D<Char> = ListCharSequenceGrid2D(data) @JvmName("from2") fun <E> from(data: List<List<E>>): Grid2D<E> = ListGrid2D(data) } operator fun get(position: Position2D): E } data class ListGrid2D<out E>(private val data: List<List<E>>) : Grid2D<E> { override val height: Int get() = data.size override val width: Int get() = data[0].size override val allPositions: List<Position2D> get() = ((data[0].indices).toList() cartesianProduct data.indices.toList()).map(Position2D::from) override fun get(position: Position2D): E = data[position.y][position.x] } data class ListCharSequenceGrid2D(private val data: List<CharSequence>) : Grid2D<Char> { override val height: Int get() = data.size override val width: Int get() = data[0].length override val allPositions: List<Position2D> get() = ((0 until data[0].length).toList() cartesianProduct (data.indices.toList())).map(Position2D::from) override fun get(position: Position2D) = data[position.y][position.x] } data class Movement2D(val dx: Int, val dy: Int)
[ { "class_path": "jorander__advent-of-code-2022__1681218/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String...
jorander__advent-of-code-2022__1681218/src/Day04.kt
fun main() { val day = "Day04" fun assignmentsAsIntRanges(assignments: String) = assignments.split(",") .map { it.split("-") } .map { (firstSection, lastSection) -> firstSection.toInt()..lastSection.toInt() } fun part1(input: List<String>): Int { return input.map(::assignmentsAsIntRanges) .count { (firstAssignment, secondAssignment) -> (firstAssignment - secondAssignment).isEmpty() || (secondAssignment - firstAssignment).isEmpty() } } fun part2(input: List<String>): Int { return input.map(::assignmentsAsIntRanges) .count { (firstAssignment, secondAssignment) -> (firstAssignment intersect secondAssignment).isNotEmpty() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 2) val result1 = part1(input) println(result1) check(result1 == 518) check(part2(testInput) == 4) val result2 = part2(input) println(result2) check(result2 == 909) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day04\n 2: astore_0\n 3: new #10 ...
jorander__advent-of-code-2022__1681218/src/Day05.kt
import java.util.Stack fun main() { val day = "Day05" // Some utility functions for Pair fun <A, B, R> Pair<A, B>.mapFirst(operation: (A) -> R) = operation(first) to second fun <A, B, R> Pair<A, B>.mapSecond(operation: (B) -> R) = first to operation(second) fun <A, B, R> Pair<Iterable<A>, B>.foldFirst(initial: R, operation: (acc: R, A) -> R): Pair<R, B> = first.fold(initial, operation) to second fun <A, B, R> Pair<A, Iterable<B>>.foldSecond(initial: R, operation: (acc: R, B) -> R): Pair<A, R> = first to second.fold(initial, operation) fun <E> List<E>.chunkedAsPairs() = chunked(2).map { list -> list[0] to list[1] } fun List<String>.parse(): Pair<Array<Stack<Char>>, List<String>> { val startingStacksAndRearrangementInstructions = chunked(String::isEmpty).chunkedAsPairs().first() return startingStacksAndRearrangementInstructions.mapFirst { startingStacks -> val numberOfStacks = startingStacks.last().split(" ").last().toInt() val emptyStacks = Array(numberOfStacks) { Stack<Char>() } startingStacks.dropLast(1).reversed() .fold(emptyStacks) { stacks, crates -> ("$crates ").chunked(4).foldIndexed(stacks) { index, acc, crate -> if (crate.isNotBlank()) { acc[index].push(crate.substring(1..2).first()) } acc } stacks } } } fun Pair<Array<Stack<Char>>, List<String>>.rearrangeWithMoveStrategy(moveStrategy: (Stack<Char>, Stack<Char>) -> List<Stack<Char>>) = foldSecond(first) { stacks, rearrangeInstruction -> val (_, numberOf, _, from, _, to) = rearrangeInstruction.split((" ")) moveStrategy(stacks[from.toInt() - 1], stacks[to.toInt() - 1]).windowed(2) .forEach { (from, to) -> repeat(numberOf.toInt()) { to.push(from.pop()) } } stacks }.first fun Array<Stack<Char>>.collectTopCrates() = map(Stack<Char>::pop).joinToString("") fun part1(input: List<String>): String { return input.parse() .rearrangeWithMoveStrategy { from, to -> listOf(from, to) } .collectTopCrates() } fun part2(input: List<String>): String { return input.parse() .rearrangeWithMoveStrategy { from, to -> listOf(from, Stack(), to) } .collectTopCrates() } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == "CMZ") val result1 = part1(input) println(result1) check(result1 == "GFTNRBZPF") check(part2(testInput) == "MCD") val result2 = part2(input) println(result2) check(result2 == "VRQWPDSGP") } private operator fun <E> List<E>.component6() = this[5]
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day05Kt$main$parse$startingStacksAndRearrangementInstructions$1.class", "javap": "Compiled from \"Day05.kt\"\nfinal class Day05Kt$main$parse$startingStacksAndRearrangementInstructions$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotli...
jorander__advent-of-code-2022__1681218/src/Day11.kt
private data class Item(val worryLevel: Long) { fun relieved(): Item { return Item(worryLevel / 3L) } } private data class TestedItem(val item: Item, val action: (Item, Array<Monkey>) -> Unit) private data class Monkey( val items: List<Item>, val operation: (Item) -> Item, val testValue: Long, val ifTrue: (Item, Array<Monkey>) -> Unit, val ifFalse: (Item, Array<Monkey>) -> Unit ) { fun takeTurn(afterInspection: (Item) -> Item) = items.size to items .map(::inspect) .map(afterInspection) .map(::testItem) .map(::throwItem) private fun inspect(item: Item): Item { return operation(item) } private fun testItem(item: Item) = TestedItem( item, if (item.worryLevel % testValue == 0L) { ifTrue } else { ifFalse } ) private fun throwItem(testedItem: TestedItem): (Array<Monkey>) -> Unit = { monkeys: Array<Monkey> -> testedItem.action(testedItem.item, monkeys) } fun receive(item: Item) = this.copy(items = items + item) fun leaveItem() = this.copy(items= items.drop(1)) } private fun List<String>.toMonkeys() = chunked(String::isEmpty) .mapIndexed{ index, monkeyConfiguration -> Monkey( items = monkeyConfiguration[1].removePrefix(" Starting items: ").split(", ").map { Item(it.toLong()) }, operation = monkeyConfiguration[2].removePrefix(" Operation: new = old ").split(" ").let { val (operation, valueStr) = it val value = if (valueStr != "old") valueStr.toLong() else 0 when (operation) { "*" -> { item: Item -> Item(item.worryLevel * if (valueStr == "old") item.worryLevel else value) } "+" -> { item: Item -> Item(item.worryLevel + if (valueStr == "old") item.worryLevel else value) } else -> { throw IllegalArgumentException("Unknown operation $operation") } } }, testValue = monkeyConfiguration[3].removePrefix(" Test: divisible by ").toLong(), ifTrue = monkeyConfiguration[4].removePrefix(" If true: throw to monkey ").toInt().let { { item: Item, monkeys: Array<Monkey> -> monkeys[index] = monkeys[index].leaveItem(); monkeys[it] = monkeys[it].receive(item) } }, ifFalse = monkeyConfiguration[5].removePrefix(" If false: throw to monkey ").toInt().let { { item: Item, monkeys: Array<Monkey> -> monkeys[index] = monkeys[index].leaveItem(); monkeys[it] = monkeys[it].receive(item) } } ) }.toTypedArray() fun main() { val day = "Day11" fun IntRange.run(monkeys: Array<Monkey>, afterInspection: (Item) -> Item): Long { val afterExecution = fold(List(monkeys.size) { 0L }) { numberOfItemsInspected, _ -> val numberOfItemsInspectedInRound = monkeys .map { monkey -> val (numberOfItems, throwsToExecute) = monkey.takeTurn(afterInspection) throwsToExecute.forEach { it(monkeys) } numberOfItems } numberOfItemsInspected.zip(numberOfItemsInspectedInRound) .map { (i1, i2) -> i1 + i2 } } return afterExecution.sortedDescending().take(2).reduce(Long::times) } fun part1(input: List<String>): Long { val monkeys = input.toMonkeys() val rounds = 1..20 return rounds.run(monkeys,Item::relieved) } fun part2(input: List<String>): Long { val monkeys = input.toMonkeys() val rounds = 1..10000 return rounds.run(monkeys) { item: Item -> Item(item.worryLevel % monkeys.map { it.testValue }.reduce(Long::times)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 10605L) val result1 = part1(input) println(result1) check(result1 == 121450L) check(part2(testInput) == 2713310158L) val result2 = part2(input) println(result2) check(result2 == 28244037010L) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day11Kt$main$part1$1.class", "javap": "Compiled from \"Day11.kt\"\nfinal class Day11Kt$main$part1$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<Item, Item> {\n public static final Day11Kt$main$part1$1 IN...
jorander__advent-of-code-2022__1681218/src/Day07.kt
import java.util.* import kotlin.collections.ArrayList fun main() { val day = "Day07" data class Directory(val name: String, var size: Int = 0) fun parseDirectorySizes(input: List<String>): List<Directory> { fun String.toFileSize() = split(" ")[0].toInt() data class State(val path: Stack<Directory>, val total: MutableList<Directory>) { fun addFile(fileSize: Int) { path.peek().size += fileSize } fun moveInto(name: String) { path.push( Directory( if (path.isEmpty()) { name } else { "${path.peek().name.dropLastWhile { it == '/' }}/$name" } ) ) } fun moveUp() { val currentDir = path.pop() total.add(currentDir) if (path.isNotEmpty()) { path.peek().size += currentDir.size } } fun moveToRoot() { while (path.isNotEmpty()) { moveUp() } } } return input .filter { !it.startsWith("dir") } .filter { !it.startsWith("$ ls") } .fold(State(Stack(), ArrayList())) { state, s -> if (s == "$ cd ..") { state.apply { moveUp() } } else if (s.startsWith("$ cd ")) { state.apply { moveInto(s.removePrefix("$ cd ")) } } else { state.apply { addFile(s.toFileSize()) } } }.apply { moveToRoot() }.total } fun part1(input: List<String>): Int { return parseDirectorySizes(input) .filter { it.size <= 100000 } .sumOf(Directory::size) } fun part2(input: List<String>): Int { val directories = parseDirectorySizes(input) val usedSpace = directories.first { it.name == "/" }.size val freeSpace = 70000000 - usedSpace val spaceNeeded = 30000000 - freeSpace return directories .filter { it.size >= spaceNeeded } .minBy { it.size } .size } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 95437) val result1 = part1(input) println(result1) check(result1 == 1908462) check(part2(testInput) == 24933642) val result2 = part2(input) println(result2) check(result2 == 3979145) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day07Kt.class", "javap": "Compiled from \"Day07.kt\"\npublic final class Day07Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day07\n 2: astore_0\n 3: new #10 ...
jorander__advent-of-code-2022__1681218/src/Day06.kt
fun main() { val day = "Day06" fun String.toNumberOfCharsBeforeUniqeSetOfSize(size: Int) = windowed(size) .mapIndexed { index, s -> index + size to s } .first { (_, s) -> s.toSet().size == size }.first fun part1(input: String): Int { return input.toNumberOfCharsBeforeUniqeSetOfSize(4) } fun part2(input: String): Int { return input.toNumberOfCharsBeforeUniqeSetOfSize(14) } // test if implementation meets criteria from the description, like: val input = readInput(day) check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) val result1 = part1(input.first()) println(result1) check(result1 == 1779) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val result2 = part2(input.first()) println(result2) check(result2 == 2635) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day06Kt.class", "javap": "Compiled from \"Day06.kt\"\npublic final class Day06Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day06\n 2: astore_0\n 3: aload_0\n 4: invokestati...
jorander__advent-of-code-2022__1681218/src/Day03.kt
fun main() { val day = "Day03" fun List<String>.findCommonChar() = this.drop(1).fold(this.first().toSet()) { acc, s -> s.toSet().intersect(acc) }.first() fun calculatePriority(badge: Char) = if (badge.isLowerCase()) { badge - 'a' + 1 } else { badge - 'A' + 27 } fun part1(input: List<String>): Int { return input.map { rucksack -> rucksack.chunked(rucksack.length / 2) .findCommonChar() }.map(::calculatePriority).sum() } fun part2(input: List<String>): Int { return input.chunked(3) .map(List<String>::findCommonChar) .map(::calculatePriority).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 157) val result1 = part1(input) println(result1) check(result1 == 7997) check(part2(testInput) == 70) val result2 = part2(input) println(result2) check(result2 == 2545) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day03\n 2: astore_0\n 3: new #10 ...
jorander__advent-of-code-2022__1681218/src/Day02.kt
import Outcome.* import Outcome.Companion.outcome import Shape.Companion.myShape import Shape.Companion.opponentShape enum class Shape(val opponentCode: String, val myCode: String, val score: Int, val winsOver: Int) { ROCK("A", "X", 1, 2), PAPER("B", "Y", 2, 0), SCISSORS("C", "Z", 3, 1); companion object { fun opponentShape(opponentCode: String) = values().find { it.opponentCode == opponentCode }!! fun myShape(myCode: String) = values().find { it.myCode == myCode }!! fun winsOver(shape: Shape) = values().find { it.winsOver == shape.ordinal }!! fun loosesTo(shape: Shape) = values().find { it.ordinal == shape.winsOver }!! } } enum class Outcome(val code: String) { WIN("Z"), DRAW("Y"), LOOSE("X"); companion object { fun outcome(code: String) = values().find { it.code == code }!! } } fun main() { val day = "Day02" fun calculateScore(opponentShape: Shape, myShape: Shape) = myShape.score + when { myShape.winsOver == opponentShape.ordinal -> 6 myShape == opponentShape -> 3 else -> 0 } fun part1(input: List<String>): Int { return input.map { inputRow -> val (opponentCode, myCode) = inputRow.split(" ") opponentShape(opponentCode) to myShape(myCode) }.sumOf { (opponentShape, myShape) -> calculateScore(opponentShape, myShape) } } fun part2(input: List<String>): Int { fun findMyShape(outcome: Outcome, opponentShape: Shape) = when (outcome) { WIN -> Shape.winsOver(opponentShape) DRAW -> opponentShape LOOSE -> Shape.loosesTo(opponentShape) } return input.map { inputRow -> val (opponentCode, outcomeCode) = inputRow.split(" ") opponentShape(opponentCode) to outcome(outcomeCode) } .map { (opponentShape, outcome) -> opponentShape to findMyShape(outcome, opponentShape) } .sumOf { (opponentShape, myShape) -> calculateScore(opponentShape, myShape) } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 15) val result1 = part1(input) println(result1) check(result1 == 14264) check(part2(testInput) == 12) val result2 = part2(input) println(result2) check(result2 == 12382) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day02\n 2: astore_0\n 3: new #10 ...
jorander__advent-of-code-2022__1681218/src/Day09.kt
import kotlin.math.abs typealias Knot = Position2D private fun Knot.isCloseTo(other: Knot) = (this - other).run { abs(dx) <= 1 && abs(dy) <= 1 } fun main() { val day = "Day09" data class Simulation( val numberOfExtraKnots: Int = 0, val head: Knot = Knot(0, 0), val knots: List<Knot> = List(numberOfExtraKnots) { _ -> head }, val tail: Knot = head, val placesVisitedByTail: Set<Knot> = setOf(tail) ) { fun moveHead(direction: String): Simulation { val newHeadPosition = calculateNewHeadPosition(direction) val newKnotPositions = calculateKnotPositions(newHeadPosition) val newTailPosition = tail.calculateNewPosition(if (numberOfExtraKnots > 0) newKnotPositions.last() else newHeadPosition) return this.copy( head = newHeadPosition, knots = newKnotPositions, tail = newTailPosition, placesVisitedByTail = placesVisitedByTail + newTailPosition ) } private fun calculateNewHeadPosition(direction: String) = head + when (direction) { "U" -> Movement2D(0, 1) "L" -> Movement2D(-1, 0) "D" -> Movement2D(0, -1) "R" -> Movement2D(1, 0) else -> { throw IllegalArgumentException("Unknown input: $direction") } } private fun calculateKnotPositions(head: Knot) = knots.runningFold(head) { prev, tail -> tail.calculateNewPosition(prev) }.drop(1) private fun Knot.calculateNewPosition(head: Knot): Knot { val tail = this return if (tail.isCloseTo(head)) { tail } else { tail + Movement2D((head.x - tail.x).coerceIn(-1, 1), (head.y - tail.y).coerceIn(-1, 1)) } } } fun List<String>.simulate(simulation: Simulation) = this.flatMap { val (direction, steps) = it.split(" ") List(steps.toInt()) { _ -> direction } }.fold(simulation) { runningSimulation, direction -> runningSimulation.moveHead(direction) } fun part1(input: List<String>): Int { return input.simulate(Simulation()) .placesVisitedByTail.size } fun part2(input: List<String>): Int { return input.simulate(Simulation(numberOfExtraKnots = 8)) .placesVisitedByTail.size } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val testInput2 = readInput("${day}_test2") val input = readInput(day) check(part1(testInput) == 13) val result1 = part1(input) println(result1) check(result1 == 6090) check(part2(testInput) == 1) check(part2(testInput2) == 36) val result2 = part2(input) println(result2) check(result2 == 2566) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day09Kt.class", "javap": "Compiled from \"Day09.kt\"\npublic final class Day09Kt {\n private static final boolean isCloseTo(Position2D, Position2D);\n Code:\n 0: aload_0\n 1: aload_1\n 2: invokevirtual #12 // Metho...
jorander__advent-of-code-2022__1681218/src/Day08.kt
typealias Trees = Grid2D<Char> typealias TreePosition = Position2D typealias Direction = (TreePosition, Trees) -> List<TreePosition> fun main() { val day = "Day08" val up: Direction = { tp: TreePosition, _: Trees -> (0 until tp.y).map { TreePosition(tp.x, it) }.reversed() } val down: Direction = { tp: TreePosition, trees: Trees -> (tp.y + 1 until trees.height).map { TreePosition(tp.x, it) } } val left: Direction = { tp: TreePosition, _: Trees -> (0 until tp.x).map { TreePosition(it, tp.y) }.reversed() } val right: Direction = { tp: TreePosition, trees: Trees -> (tp.x + 1 until trees.width).map { TreePosition(it, tp.y) } } val directions = listOf(up, down, left, right) fun part1(input: List<String>): Int { val trees = Trees.from(input) fun TreePosition.canBeSeenFrom(direction: Direction) = direction(this, trees).none { (trees[this]) <= trees[it] } fun TreePosition.isVisibleFromAnyDirection() = directions.any { this.canBeSeenFrom(it) } fun TreePosition.isOnOuterEdge() = isOnOuterEdgeIn(trees) fun Trees.numberOfTreesOnOuterEdge() = allPositions.filter { it.isOnOuterEdge() }.size return (trees.allPositions .filter { !it.isOnOuterEdge() } .count { it.isVisibleFromAnyDirection() } + trees.numberOfTreesOnOuterEdge()) } fun part2(input: List<String>): Int { val trees = Trees.from(input) fun List<TreePosition>.thatCanBeSeenFrom(treePosition: TreePosition): Int { fun addViewOfTreeThatCantBeSeenPassed(numberOfLowerTreesCounted: Int) = if (isNotEmpty() && numberOfLowerTreesCounted < size) 1 else 0 return takeWhile { (trees[treePosition] > trees[it]) } .count().let { it + addViewOfTreeThatCantBeSeenPassed(it) } } fun TreePosition.numberOfTreesInViewPerDirection() = directions.map { direction -> val treesInDirection = direction(this, trees) treesInDirection.thatCanBeSeenFrom(this) } fun TreePosition.scenicValue() = numberOfTreesInViewPerDirection() .reduce(Int::times) return trees.allPositions .maxOf { it.scenicValue() } } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") val input = readInput(day) check(part1(testInput) == 21) val result1 = part1(input) println(result1) check(result1 == 1717) check(part2(testInput) == 8) val result2 = part2(input) println(result2) check(result2 == 321975) }
[ { "class_path": "jorander__advent-of-code-2022__1681218/Day08Kt.class", "javap": "Compiled from \"Day08.kt\"\npublic final class Day08Kt {\n public static final void main();\n Code:\n 0: ldc #8 // String Day08\n 2: astore_0\n 3: invokedynamic #27, 0 ...
d1snin__aoc-2023__8b5b34c/src/main/kotlin/Day1.kt
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ private const val INPUT = """ """ private val lines get() = INPUT.lines() .map { it.trim() } .filter { it.isNotEmpty() } private val digitMap = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" ) fun day1() { println("Running AoC Day 1 (1st part)...") firstPart() println() println("Running AoC Day 1 (2nd part)...") secondPart() } private fun firstPart() { val res = lines.sumOfDigits() println("res: $res") } private fun secondPart() { val res = lines.transformWords().sumOfDigits() println("res: $res") } private fun List<String>.sumOfDigits() = sumOf { line -> val digits = line.filter { it.isDigit() } digits.singleOrNull()?.let { numberOf(it, it) } ?: numberOf(digits.first(), digits.last()) } private fun List<String>.transformWords() = map { line -> var transformedLine = line var limit = 0 var reverse = false while (limit <= line.length) { val batch = if (reverse) transformedLine.takeLast(limit) else transformedLine.take(limit) var transformedBatch = batch digitMap.forEach { (word, digit) -> transformedBatch = transformedBatch.replace(word, digit) } val newTransformedLine = transformedLine.replace(batch, transformedBatch) val transformed = transformedLine != newTransformedLine if ((transformed || batch.contains("\\d".toRegex())) && !reverse) { reverse = true limit = 0 } else { limit += 1 } transformedLine = newTransformedLine } transformedLine } private fun numberOf(first: Char, second: Char) = String(charArrayOf(first, second)).toInt()
[ { "class_path": "d1snin__aoc-2023__8b5b34c/Day1Kt.class", "javap": "Compiled from \"Day1.kt\"\npublic final class Day1Kt {\n private static final java.lang.String INPUT;\n\n private static final java.util.Map<java.lang.String, java.lang.String> digitMap;\n\n private static final java.util.List<java.lang....
d1snin__aoc-2023__8b5b34c/src/main/kotlin/Day3.kt
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ private const val INPUT = """ """ private data class Num( val line: String, val lineIndex: Int, val at: Int, val data: Int ) private data class Boundary( val line: String, val lineIndex: Int, val start: Int, val end: Int, val data: String ) private data class Gear( val at: Pair<Int, Int>, val first: Num, var second: Num? = null ) private val lines = INPUT.lines() .map { it.trim() } .filter { it.isNotEmpty() } private val gears = mutableListOf<Gear>() fun day3() { println("Running AoC Day 3 (1st part)...") firstPart() println() println("Running AoC Day 3 (2nd part)...") secondPart() } private fun firstPart() { val res = lines.numbers().sumOf { if (it.isAdjacentToSymbol()) it.data else 0 } println("res: $res") } private fun secondPart() { lines.numbers().forEach { it.gears() } val res = gears .filter { it.second != null } .sumOf { it.first.data * requireNotNull(it.second?.data) } println("res: $res") } private fun List<String>.numbers() = flatMapIndexed { lineIndex, line -> line.numbers(lineIndex) } private fun String.numbers(lineIndex: Int): List<Num> = buildList { var numString: String? = null var at: Int? = null this@numbers.forEachIndexed { index, char -> val isDigit = char.isDigit() if (isDigit) { numString = (numString ?: "") + char at = at ?: index } if (!isDigit || index == (length - 1)) { numString?.let { numStringNotNull -> at?.let { atNotNull -> val number = numStringNotNull.toInt() val num = Num( line = this@numbers, lineIndex = lineIndex, at = atNotNull, data = number ) add(num) numString = null at = null } } } } } private fun Num.isAdjacentToSymbol() = getBoundaries().any { boundary -> boundary.data.containsSymbol() } private fun Num.gears() { getBoundaries(excludeInt = false).forEach { boundary -> boundary.data.forEachIndexed { index, char -> if (char == '*') { val coords = boundary.lineIndex to (boundary.start + index) getOrPutGear(coords, this@gears) } } } } private fun Num.getBoundaries(excludeInt: Boolean = true): List<Boundary> { val length = data.toString().length val range = getBoundaryRange(length) fun String.substring(excludeInt: Boolean = false) = substring(range).let { substring -> if (excludeInt) substring.filterNot { it.isDigit() } else substring } val topLineIndex = lineIndex - 1 val topLineSub = lines.getOrNull(topLineIndex)?.substring() val currentLineSub = line.substring(excludeInt = excludeInt) val bottomLineIndex = lineIndex + 1 val bottomLineSub = lines.getOrNull(bottomLineIndex)?.substring() return listOfNotNull( topLineSub?.to(topLineIndex), currentLineSub to lineIndex, bottomLineSub?.to(bottomLineIndex) ).map { (data, dataLineIndex) -> Boundary( line = line, lineIndex = dataLineIndex, start = range.first, end = range.last, data = data ) } } private fun Num.getBoundaryRange(length: Int): IntRange { val start = if (at < 1) 0 else at - 1 val endCandidate = at + length val end = if (line.length <= endCandidate) endCandidate - 1 else endCandidate return start..end } private fun String.containsSymbol() = this.contains("[^\\d.]".toRegex()) private fun getOrPutGear(at: Pair<Int, Int>, num: Num): Gear { val foundGear = gears.find { it.at == at } foundGear?.second = num return foundGear ?: Gear(at, first = num).also { gears.add(it) } }
[ { "class_path": "d1snin__aoc-2023__8b5b34c/Day3Kt.class", "javap": "Compiled from \"Day3.kt\"\npublic final class Day3Kt {\n private static final java.lang.String INPUT;\n\n private static final java.util.List<java.lang.String> lines;\n\n private static final java.util.List<Gear> gears;\n\n public stati...
d1snin__aoc-2023__8b5b34c/src/main/kotlin/Day2.kt
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ private const val INPUT = """ """ private const val RED_LIMIT = 12 private const val GREEN_LIMIT = 13 private const val BLUE_LIMIT = 14 private data class Game( val id: Int, val handfuls: List<Handful> ) private data class Handful( val red: Int, val green: Int, val blue: Int ) private val lines get() = INPUT.lines() .map { it.trim() } .filter { it.isNotEmpty() } fun day2() { println("Running AoC Day 2 (1st part)...") firstPart() println() println("Running AoC Day 2 (2nd part)...") secondPart() } private fun firstPart() { val games = lines.parseGames() val res = games.sumOf { game -> val beyondLimit = game.handfuls.any { it.isBeyondLimit() } if (beyondLimit) 0 else game.id } println("res: $res") } private fun secondPart() { val games = lines.parseGames() val res = games.sumOf { game -> val handfuls = game.handfuls val minRed = handfuls.maxOf { it.red } val minGreen = handfuls.maxOf { it.green } val minBlue = handfuls.maxOf { it.blue } minRed * minGreen * minBlue } println("res: $res") } private fun List<String>.parseGames() = map { it.parseGame() } private fun String.parseGame(): Game { val id = findId() val handfuls = findHandfulsString() .findHandfulDeclarations() .map { handfulString -> var red = 0 var green = 0 var blue = 0 handfulString.findCubeStrings().forEach { cubeString -> val countAndColor = cubeString.split(" ") val count = countAndColor.first().toInt() val color = countAndColor.last() when (color) { "red" -> red += count "green" -> green += count "blue" -> blue += count } } Handful(red, green, blue) } return Game(id, handfuls) } private fun String.findId() = requireNotNull("(?<=Game\\s)\\d+".toRegex().find(this)).value.toInt() private fun String.findHandfulsString() = replace("Game\\s\\d+:\\s".toRegex(), "") private fun String.findHandfulDeclarations() = split("; ") private fun String.findCubeStrings() = split(", ") private fun Handful.isBeyondLimit() = red > RED_LIMIT || green > GREEN_LIMIT || blue > BLUE_LIMIT
[ { "class_path": "d1snin__aoc-2023__8b5b34c/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class Day2Kt {\n private static final java.lang.String INPUT;\n\n private static final int RED_LIMIT;\n\n private static final int GREEN_LIMIT;\n\n private static final int BLUE_LIMIT;\n\n privat...
d1snin__aoc-2023__8b5b34c/src/main/kotlin/Day4.kt
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ private const val INPUT = """ """ private data class Card( val id: Int, val winning: List<Int>, val given: List<Int> ) private val lines = INPUT.lines() .map { it.trim() } .filter { it.isNotEmpty() } fun day4() { println("Running AoC Day 4 (1st part)...") firstPart() println() println("Running AoC Day 4 (2nd part)...") secondPart() } private fun firstPart() { val res = lines.parseCards() .sumOf { it.points() } println("res: $res") } private fun secondPart() { val res = lines .parseCards() .populate() .count() println("res: $res") } private fun List<String>.parseCards() = map { it.parseCard() } private fun String.parseCard(): Card { val cardId = extractCardId() val winning = extractWinningNumbers() val given = extractGivenNumbers() return Card(cardId, winning, given) } private fun Card.points(): Int { var points = 0 given.forEach { if (it in winning) { if (points == 0) { points = 1 } else { points *= 2 } } } return points } private fun List<Card>.populate(): List<Card> { val copies = associate { it to mutableListOf<Card>() }.toMutableMap() forEachIndexed { index, card -> val count = card.count() (1..count).forEach { currentCount -> val cardToCopy = getOrNull(index + currentCount) ?: return@forEach val currentCardCopies = copies[card] ?: return@forEach repeat(currentCardCopies.size + 1) { copies[cardToCopy]?.add(cardToCopy) } } } val cards = copies.flatMap { (card, copies) -> listOf(card, *copies.toTypedArray()) } return cards } private fun Card.count() = given.count { it in winning } private fun String.extractCardId() = removePrefix( find("Card\\s+".toRegex()) ).removeSuffix( find(":.*".toRegex()) ).toInt() private fun String.extractWinningNumbers() = extractNumbers().first private fun String.extractGivenNumbers() = extractNumbers().second private fun String.extractNumbers(): Pair<List<Int>, List<Int>> = extractNumbersString().let { numbersString -> "[\\d\\s]+".toRegex().findAll(numbersString).map { part -> part.value.trim().split("\\s+".toRegex()).map { it.toInt() } }.let { it.first() to it.last() } } private fun String.extractNumbersString() = removePrefix( find("Card\\s+\\d+:\\s+".toRegex()) ) private fun String.find(regex: Regex) = requireNotNull( regex.find(this)?.value )
[ { "class_path": "d1snin__aoc-2023__8b5b34c/Day4Kt.class", "javap": "Compiled from \"Day4.kt\"\npublic final class Day4Kt {\n private static final java.lang.String INPUT;\n\n private static final java.util.List<java.lang.String> lines;\n\n public static final void day4();\n Code:\n 0: ldc ...
rolf-rosenbaum__aoc-2022__59cd426/src/main/Utils.kt
import java.io.File import kotlin.math.abs /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() fun <T> List<T>.second() = this[1] fun <T, R> Pair<T, R>.reverse() = second to first data class Point(val x: Int, val y: Int) { fun neighbours(includeCenter: Boolean = false): List<Point> = if (includeCenter) listOf(Point(x, y + 1), Point(x + 1, y), this, Point(x, y - 1), Point(x - 1, y)) else listOf(Point(x, y + 1), Point(x + 1, y), Point(x, y - 1), Point(x - 1, y)) fun allNeighbours(): Set<Point> = setOf( Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1), Point(x - 1, y), Point(x + 1, y), Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1) ) fun distanceTo(other: Point) = abs(x - other.x) + abs(y - other.y) operator fun plus(other: Point) = Point(x + other.x, y + other.y) } fun IntRange.fullyContains(other: IntRange) = contains(other.first) && contains(other.last) fun IntRange.overlapsWith(other: IntRange) = contains(other.first) || contains(other.last) fun IntRange.union(other: IntRange): IntRange? { return if (overlapsWith(other)) IntRange(minOf(first, other.first), maxOf(last, other.last)) else null } fun List<Int>.findPattern(startIndex: Int = 1): Pair<Int, Int> { (startIndex..size / 2).forEach { windowSize -> print("$windowSize\r") val tmp = this.windowed(windowSize) tmp.forEachIndexed { index, intList -> if (index + windowSize >= tmp.size) return@forEachIndexed if (intList == tmp[index + windowSize]) return index + 1 to windowSize } } error("no pattern") }
[ { "class_path": "rolf-rosenbaum__aoc-2022__59cd426/UtilsKt.class", "javap": "Compiled from \"Utils.kt\"\npublic final class UtilsKt {\n public static final java.util.List<java.lang.String> readInput(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 // String name...
Hotkeyyy__advent-of-code-2022__dfb20f1/src/Day04.kt
import java.io.File fun main() { fun part1(input: String) { val pairs = input.split("\n").map { val parts = it.split(",") Pair(parts[0].split("-").map { it.toInt() }, parts[1].split("-").map { it.toInt() }) } val count = pairs.count { val (a, b) = it (a[0] <= b[0] && a[1] >= b[1]) || (b[0] <= a[0] && b[1] >= a[1]) } println(count) } fun part2(input: String) { val pairs = input.split("\n").map { val parts = it.split(",") Pair(parts[0].split("-").map { it.toInt() }, parts[1].split("-").map { it.toInt() }) } val count = pairs.count { val (a, b) = it (a[0] <= b[1] && a[1] >= b[0]) || (b[0] <= a[1] && b[1] >= a[0]) } println(count) } val input = File("src/Day04.txt").readText() part1(input) part2(input) }
[ { "class_path": "Hotkeyyy__advent-of-code-2022__dfb20f1/Day04Kt.class", "javap": "Compiled from \"Day04.kt\"\npublic final class Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 ...
Hotkeyyy__advent-of-code-2022__dfb20f1/src/Day03.kt
import java.io.File fun main() { val lowerCase = ('a'..'z').toList() val upperCase = ('A'..'Z').toList() fun part1(input: String) { var result = 0 input.split("\r").map { it.trim() }.forEach { val firstCompartment = it.substring(0, it.length / 2) val secondCompartment = it.substring(it.length / 2, it.length) var sameCharacter = ' ' secondCompartment.forEach { c -> if (firstCompartment.contains(c)) sameCharacter = c } if (lowerCase.contains(sameCharacter)) result += (lowerCase.indexOf(sameCharacter) + 1) if (upperCase.contains(sameCharacter)) result += (upperCase.indexOf(sameCharacter) + 27) } println(result) } fun part2(input: String) { var result = 0 input.split("\r").map { it.trim() }.chunked(3).forEach { list -> var sameCharacter = ' ' list.first().forEach { c -> var lastContains = true list.forEach { if (lastContains && !it.contains(c)) lastContains = false } if (lastContains) sameCharacter = c } if (lowerCase.contains(sameCharacter)) result += (lowerCase.indexOf(sameCharacter) + 1) if (upperCase.contains(sameCharacter)) result += (upperCase.indexOf(sameCharacter) + 27) } println(result) } val input = File("src/Day03.txt").readText() part1(input) part2(input) }
[ { "class_path": "Hotkeyyy__advent-of-code-2022__dfb20f1/Day03Kt.class", "javap": "Compiled from \"Day03.kt\"\npublic final class Day03Kt {\n public static final void main();\n Code:\n 0: new #8 // class kotlin/ranges/CharRange\n 3: dup\n 4: bipush 97\n...
Hotkeyyy__advent-of-code-2022__dfb20f1/src/Day02.kt
import java.io.File val meL = "XYZ".toList() val opponentL = "ABC".toList() fun main() { fun part1(input: String) { val rounds = input.split("\r") var result = 0 rounds.forEach { val me = it.split(" ").last() val opponent = it.split(" ").first() val p = getPoints( Pair( meL.indexOf(me.trim().toCharArray().first()), opponentL.indexOf(opponent.trim().toCharArray().first()) ) ) result += p } println(result) } fun part2(input: String) { val rounds = input.split("\r") var result = 0 rounds.forEach { val type = it.split(" ").last() val opponent = it.split(" ").first() var character = "" when (type) { "X" -> character = opponent.trim().characterToLose "Y" -> character = opponent.trim().characterToDraw "Z" -> character = opponent.trim().characterToWin } val p = getPoints( Pair( meL.indexOf(character.trim().toCharArray().first()), opponentL.indexOf(opponent.trim().toCharArray().first()) ) ) result += p } println(result) } val input = File("src/Day02.txt").readText() part2(input) } val String.characterToWin: String get() { if (this == "A") return "Y" if (this == "B") return "Z" if (this == "C") return "X" return TODO("Provide the return value") } val String.characterToDraw: String get() { return meL[opponentL.indexOf(this.trim().toCharArray().first())].toString() } val String.characterToLose: String get() { if (this == "A") return "Z" if (this == "B") return "X" if (this == "C") return "Y" return TODO("Provide the return value") } fun getPoints(pair: Pair<Int, Int>): Int { val me = pair.first val opponent = pair.second var points = 0 if (me == opponent) points += 3 if (me == 0 && (opponent == 2)) points += 6 if (me == 1 && (opponent == 0)) points += 6 if (me == 2 && (opponent == 1)) points += 6 if (me == 0) points += 1 if (me == 1) points += 2 if (me == 2) points += 3 return points }
[ { "class_path": "Hotkeyyy__advent-of-code-2022__dfb20f1/Day02Kt.class", "javap": "Compiled from \"Day02.kt\"\npublic final class Day02Kt {\n private static final java.util.List<java.lang.Character> meL;\n\n private static final java.util.List<java.lang.Character> opponentL;\n\n public static final java.u...
netguru__CarLens-Android__321fa52/app/src/main/kotlin/co/netguru/android/carrecognition/common/MultimapExt.kt
typealias Multimap<K, V> = Map<K, List<V>> fun <K, V> Multimap<K, V>.partition( predicate: (V) -> Boolean ): Pair<Multimap<K, V>, Multimap<K, V>> { val first = mutableMapOf<K, List<V>>() val second = mutableMapOf<K, List<V>>() for (k in this.keys) { val (firstValuePartition, secondValuePartition) = this[k]!!.partition(predicate) first[k] = firstValuePartition second[k] = secondValuePartition } return Pair(first, second) } fun <K, V> Multimap<K, V>.toPairsList(): List<Pair<K, V>> = this.flatMap { (k, v) -> v.map { k to it } } fun <K, V> Multimap<K, V>.flattenValues() = this.values.flatten() operator fun <K, V> Multimap<K, V>.plus(pair: Pair<K, V>): Multimap<K, V> = if (this.isEmpty()) { mapOf(pair.first to listOf(pair.second)) } else { val mutableMap = this.toMutableMap() val keyValues = mutableMap[pair.first] if (keyValues == null) { mutableMap[pair.first] = listOf(pair.second) } else { mutableMap[pair.first] = keyValues + listOf(pair.second) } mutableMap.toMap() } operator fun <K, V> Multimap<K, V>.minus(pair: Pair<K, V>): Multimap<K, V> = if (this.isEmpty()) { emptyMap() } else { val valuesForKey = this[pair.first] ?.filter { it != pair.second } ?.let { if (it.isEmpty()) null else it } if (valuesForKey == null) { this.filterKeys { it == pair.first } } else { this.toMutableMap().apply { this[pair.first] = valuesForKey - pair.second } .toMap() } } fun <K, V> List<Pair<K, V>>.toMultiMap(): Multimap<K, V> { var result = mapOf<K, List<V>>() forEach { result += it } return result } fun <K, V, I> List<I>.toMultiMap(mapper: (I) -> Pair<K, V>): Multimap<K, V> { var result = mapOf<K, List<V>>() forEach { result += mapper(it) } return result }
[ { "class_path": "netguru__CarLens-Android__321fa52/MultimapExtKt.class", "javap": "Compiled from \"MultimapExt.kt\"\npublic final class MultimapExtKt {\n public static final <K, V> kotlin.Pair<java.util.Map<K, java.util.List<V>>, java.util.Map<K, java.util.List<V>>> partition(java.util.Map<K, ? extends jav...
funfunStudy__algorithm__a207e4d/kotlin/src/main/kotlin/LongestSubstringFromChanHo.kt
import kotlin.math.max fun main(args: Array<String>) { val problems = listOf("abcabcbb", "bbbbb", "pwwkew", "", "dvdf", "asjrgapa") val expected = listOf(3, 1, 3, 0, 3, 6) problems.mapIndexed { index, s -> Pair(solution(s), expected.get(index)) } .forEach { (result, expected) -> println("result = $result, expected = $expected") assert(result == expected) } } fun solution(str: String): Int { return maxLength(substring(str)) } fun substring(str: String): List<String> { return if (str.isEmpty()) listOf() else { str.fold(mutableListOf<String>()) { acc, ch -> if (acc.size == 0) { acc.add("$ch") } else { val tmp = acc[acc.size - 1] if (tmp.contains("$ch")) { acc.add("${tmp.drop(tmp.lastIndexOf(ch) + 1)}$ch") } else { acc[acc.size - 1] = "$tmp$ch" } } acc } } } fun maxLength(strs: List<String>): Int { return strs.map { it.length }.takeIf { it.size >= 2 }?.reduce { acc, i -> max(acc, i) }?: run { if (strs.isEmpty()) 0 else strs[0].length } }
[ { "class_path": "funfunStudy__algorithm__a207e4d/LongestSubstringFromChanHoKt.class", "javap": "Compiled from \"LongestSubstringFromChanHo.kt\"\npublic final class LongestSubstringFromChanHoKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ...
funfunStudy__algorithm__a207e4d/kotlin/src/main/kotlin/StreetRgb.kt
fun main(args: Array<String>) { val list: List<List<Int>> = listOf(listOf(26, 40, 83), listOf(49, 60, 57), listOf(13, 89, 99)) val list2: List<List<Int>> = listOf(listOf(1, 20, 30), listOf(50, 5, 6), listOf(9, 3, 7)) println(solve(list)) println(solve(list2)) } fun solve(list: List<List<Int>>, index: Int = 0, min: Int = 0): Int = when { list.isEmpty() || index == 3 -> min else -> solve(list, index + 1, findMin(list, index, 0, min)) } fun findMin(list: List<List<Int>>, index: Int, result: Int = 0, min: Int): Int = when { list.isEmpty() -> { if (min == 0) result else { if (min > result) { result } else { min } } } else -> { when (index) { 0 -> Math.min(//RED findMin(list.drop(1), 1, result + list.first()[index], min), findMin(list.drop(1), 2, result + list.first()[index], min)) 1 -> Math.min(//Green findMin(list.drop(1), 0, result + list.first()[index], min), findMin(list.drop(1), 2, result + list.first()[index], min)) 2 -> Math.min(//Blue findMin(list.drop(1), 0, result + list.first()[index], min), findMin(list.drop(1), 1, result + list.first()[index], min)) else -> { result } } } } /* 예제 입력 3 26 40 83 49 60 57 13 89 99 3 1 20 30 50 5 6 9 3 7 예제 출력 96 10 */
[ { "class_path": "funfunStudy__algorithm__a207e4d/StreetRgbKt.class", "javap": "Compiled from \"StreetRgb.kt\"\npublic final class StreetRgbKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokesta...
funfunStudy__algorithm__a207e4d/kotlin/src/main/kotlin/Saddlepoint.kt
fun main(args: Array<String>) { val test1 = listOf( listOf(9, 8, 7), listOf(5, 3, 2), listOf(6, 6, 7)) val test2 = listOf( listOf(1, 2, 3), listOf(3, 1, 2), listOf(2, 3, 1)) val test3 = listOf( listOf(4, 5, 4), listOf(3, 5, 5), listOf(1, 5, 4)) val test4 = listOf( listOf(8, 7, 9), listOf(6, 7, 6), listOf(3, 2, 5) ) println(solve(test1).filterNotNull()) println(solve(test2).filterNotNull()) println(solve(test3).filterNotNull()) println(solve(test4).filterNotNull()) } private fun solve(list: List<List<Int>>): List<Pair<Int, Int>?> { val xResult = list.map { it.max()!! }.min() val yResult = transfer(list, listOf()).map { it.min()!! }.max() return if (xResult == yResult) { list.foldIndexed(listOf()) { index, acc, lista -> acc.plus(lista.mapIndexed { indexa, i -> if(i == xResult) index to indexa else null }) } } else { listOf() } } tailrec fun transfer(list: List<List<Int>>, acc: List<List<Int>>): List<List<Int>> { return when { list.isEmpty() || list.first().isEmpty() -> acc else -> { transfer(list.map { it.drop(1) }, acc.plusElement(list.map { it.first() })) } } }
[ { "class_path": "funfunStudy__algorithm__a207e4d/SaddlepointKt.class", "javap": "Compiled from \"Saddlepoint.kt\"\npublic final class SaddlepointKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: inv...
funfunStudy__algorithm__a207e4d/kotlin/src/main/kotlin/RefreshRecord.kt
fun main(args: Array<String>) { solve(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1), 9) solve2(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1)) solve3(listOf(10, 5, 20, 20, 4, 5, 2, 25, 1)) solve3(listOf(3, 4, 21, 36, 10, 28, 35, 5, 24, 42)) } data class RecordedScore(val minScore: Int = 0, val maxScore: Int = 0, val min: Int = 0, val max: Int = 0) tailrec fun solve( scoreList: List<Int>, size: Int, minScore: Int = 0, maxScore: Int = 0, min: Int = 0, max: Int = 0 ) { when { scoreList.isEmpty() -> println("$max $min") scoreList.size == size -> { val score = scoreList.first() solve(scoreList.drop(1), 9, score, score) } scoreList.size != size -> { val score = scoreList.first() solve( scoreList.drop(1), size, if (score < minScore) score else minScore, if (score > maxScore) score else maxScore, if (score < minScore) min + 1 else min, if (score > maxScore) max + 1 else max ) } } } private tailrec fun solve2( scoreList: List<Int>, minScore: Int, maxScore: Int, min: Int = 0, max: Int = 0 ) { when (scoreList.isEmpty()) { true -> println("$max $min") false -> { val score = scoreList.first() val scoreLessThenMinScore = score < minScore val scoreGreaterThenMinScore = score > maxScore solve2( scoreList.drop(1), if (scoreLessThenMinScore) score else minScore, if (scoreGreaterThenMinScore) score else maxScore, if (scoreLessThenMinScore) min + 1 else min, if (scoreGreaterThenMinScore) max + 1 else max ) } } } fun solve2(scoreList: List<Int>) { val init = scoreList.first() solve2(scoreList.drop(1), init, init) } fun solve3(scoreList: List<Int>) = scoreList.foldIndexed(RecordedScore()) { i, record, score -> when (i) { 0 -> RecordedScore(score, score) else -> RecordedScore( Math.min(score, record.minScore), Math.max(score, record.maxScore), if (score < record.minScore) record.min + 1 else record.min, if (score > record.maxScore) record.max + 1 else record.max ) } }.also { println("${it.max} ${it.min}") }
[ { "class_path": "funfunStudy__algorithm__a207e4d/RefreshRecordKt.class", "javap": "Compiled from \"RefreshRecord.kt\"\npublic final class RefreshRecordKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n ...
mr-kaffee__aoc-2023__5cbd13d/day11/kotlin/RJPlog/day2311_1_2.kt
import java.io.File import kotlin.math.* fun day11(in1: Int): Long { var expansionValue = 1 if (in1 == 2) { expansionValue = 1000000 - 1 } var universe: String = "" var xDim = 0 var yDim = 0 var galaxyMap = mutableMapOf<Int, Pair<Int, Int>>() var galaxyCount = 1 File("day2311_puzzle_input.txt").forEachLine { universe += it xDim = it.length var line = it for (i in 0..line.length - 1) { if (line[i] == '#') { galaxyMap.put(galaxyCount, Pair(i, yDim)) galaxyCount += 1 } } yDim += 1 // expand universe in yDim: if (!line.contains('#')) { yDim += expansionValue } } // determine at which xDim the universe will expand: var xDimExpandCount = mutableListOf<Int>() for (i in 0..xDim - 1) { if (!universe.chunked(xDim).map { it[i] }.contains('#')) { xDimExpandCount.add(i) } } for (key in galaxyMap.keys) { for (i in xDimExpandCount.size - 1 downTo 0) { if (galaxyMap.getValue(key).first > xDimExpandCount[i]) { galaxyMap.put( key, Pair(galaxyMap.getValue(key).first + (expansionValue), galaxyMap.getValue(key).second) ) } } } var result = 0L for ((key, value) in galaxyMap) { for ((key2, value2) in galaxyMap) { if (key != key2) { result += (abs(value2.second - value.second) + abs(value2.first - value.first)).toLong() } } } return result / 2 } fun main() { var t1 = System.currentTimeMillis() var solution1 = day11(1) var solution2 = day11(2) // print solution for part 1 println("*******************************") println("--- Day 11: Cosmic Expansion ---") println("*******************************") println("Solution for part1") println(" $solution1 ") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 ") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2311_1_2Kt.class", "javap": "Compiled from \"day2311_1_2.kt\"\npublic final class Day2311_1_2Kt {\n public static final long day11(int);\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$IntRef\n 3: dup\n 4:...
mr-kaffee__aoc-2023__5cbd13d/day04/kotlin/RJPlog/day2304_1_2.kt
import java.io.File import kotlin.math.* fun scratchCard(): Int { var result = 0 val pattern = """(\d)+""".toRegex() File("day2304_puzzle_input.txt").forEachLine { var winningNumbers = pattern.findAll(it.substringAfter(": ").split(" | ")[0]).map { it.value }.toList() var numbersYouHave = pattern.findAll(it.substringAfter(": ").split(" | ")[1]).map { it.value }.toList() result += Math.pow( 2.0, ((winningNumbers + numbersYouHave).size - (winningNumbers + numbersYouHave).distinct().size).toDouble() - 1.0 ).toInt() } return result } fun scratchCardPart2(): Int { var puzzle_input = mutableListOf<String>() File("day2304_puzzle_input.txt").forEachLine { puzzle_input.add(it) } val pattern = """(\d)+""".toRegex() val wonCards = puzzle_input.toMutableList() val wonCardsIterator = wonCards.listIterator() while (wonCardsIterator.hasNext()) { var card = wonCardsIterator.next() var cardNumber = pattern.find(card.substringBefore(":"))!!.value.toInt() var winningNumbers = pattern.findAll(card.substringAfter(": ").split(" | ")[0]).map { it.value }.toList() var numbersYouHave = pattern.findAll(card.substringAfter(": ").split(" | ")[1]).map { it.value }.toList() var wins = (winningNumbers + numbersYouHave).size - (winningNumbers + numbersYouHave).distinct().size for (i in 0..wins - 1) { wonCardsIterator.add(puzzle_input[cardNumber + i]) wonCardsIterator.previous() } } return wonCards.size } fun main() { var t1 = System.currentTimeMillis() var solution1 = scratchCard() var solution2 = scratchCardPart2() // print solution for part 1 println("*******************************") println("--- Day 4: Scratchcards ---") println("*******************************") println("Solution for part1") println(" $solution1 points are they worth in total") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 total scratchcards do you end up with") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2304_1_2Kt.class", "javap": "Compiled from \"day2304_1_2.kt\"\npublic final class Day2304_1_2Kt {\n public static final int scratchCard();\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$IntRef\n 3: dup\n ...
mr-kaffee__aoc-2023__5cbd13d/day01/kotlin/RJPlog/day2301_1_2.kt
import java.io.File fun trebuchet(in1: Int): Int { var conMap = mutableMapOf("0" to 1, "1" to 1, "2" to 2, "3" to 3, "4" to 4, "5" to 5, "6" to 6, "7" to 7, "8" to 8, "9" to 9) var pattern = """\d""".toRegex() if (in1 == 2) { var conMap2 = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9) conMap = conMap.plus(conMap2).toMutableMap() pattern = """\d|one|two|three|four|five|six|seven|eight|nine""".toRegex() } var calibValues = mutableListOf<Int>() File("day2301_puzzle_input.txt").forEachLine { var firstDigit = pattern.find(it)!!.value var matches = pattern.findAll(it) var secondDigit = "" matches.forEach{ secondDigit = it.value } calibValues.add(conMap.getValue(firstDigit)*10 + conMap.getValue(secondDigit)) } return calibValues.sum() } fun main() { var t1 = System.currentTimeMillis() var solution1 = trebuchet(1) var solution2 = trebuchet(2) // print solution for part 1 println("*******************************") println("--- Day 1: Trebuchet?! ---") println("*******************************") println("Solution for part1") println(" $solution1 is the sum of all of the calibration values") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the sum of all of the calibration values") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2301_1_2Kt.class", "javap": "Compiled from \"day2301_1_2.kt\"\npublic final class Day2301_1_2Kt {\n public static final int trebuchet(int);\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n ...
mr-kaffee__aoc-2023__5cbd13d/day08/kotlin/RJPlog/day2308_1_2.kt
import java.io.File import kotlin.math.* fun wasteland(in1: Int): Int { var lines = File("day2308_puzzle_input.txt").readLines() var network = mutableMapOf<String, Pair<String, String>>() var instructions = lines[0] for (i in 2..lines.size - 1) { network.put( lines[i].substringBefore(" ="), Pair(lines[i].substringAfter("(").substringBefore(","), lines[i].substringAfter(", ").substringBefore(")")) ) } var position = "AAA" var count = 0 while (position != "ZZZ") { var nextStep = instructions[count % instructions.length] if (nextStep == 'R') { position = network.getValue(position).second } else { position = network.getValue(position).first } count += 1 if (position.takeLast(1) == "Z") { println("$position, $count") } } return count } fun wasteland2(in1: Int): Long { var lines = File("day2308_puzzle_input.txt").readLines() var network = mutableMapOf<String, Pair<String, String>>() var instructions = lines[0] for (i in 2..lines.size - 1) { network.put( lines[i].substringBefore(" ="), Pair(lines[i].substringAfter("(").substringBefore(","), lines[i].substringAfter(", ").substringBefore(")")) ) } var position = mutableListOf<String>() network.forEach { if(it.key.takeLast(1) == "A") { position.add(it.key) } } var count = 0L var instructionLength = instructions.length.toLong() println(position) while (position.map {it.last()}.distinct().size != 1 || position.map {it.takeLast(1)}.distinct()[0] != "Z") { var nextStep = instructions[(count % instructionLength).toInt()] for (i in 0..position.size-1) if (nextStep == 'R') { position[i] = network.getValue(position[i]).second } else { position[i] = network.getValue(position[i]).first } count += 1L //println("$nextStep: $position") } return count } fun main() { var t1 = System.currentTimeMillis() var solution1 = wasteland(1) var solution2 = wasteland2(2) //das läuft ewig. Wenn man nur jeweils einen Wert anschaut sieht man, dass man mit einem Eingangswert nur einen Ausgangswert erreicht, und das mit einer bestimmten Periode. //Berechnet man daraus das kleinste gemeinsame Vielfache, bekommt man die richtige Lösung. Aber ist das zwingend bei allen Inputs so - theoretisch könnte es mehrere Zielpunkte // geben mit unterschiedlichen Frequenzen und Offset? -> ich habe das hier nicht merh angepasst //AAA GPA VDA GTA BBA VSA //ZZZ CVZ STZ FPZ SKZ MKZ //17287 13771 23147 20803 19631 17873 -> KgV = 18625484023687 // print solution for part 1 println("*******************************") println("--- Day 8: Haunted Wasteland ---") println("*******************************") println("Solution for part1") println(" $solution1 steps are required to reach ZZZ") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 steps does it take before you're only on nodes that end with Z") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2308_1_2Kt.class", "javap": "Compiled from \"day2308_1_2.kt\"\npublic final class Day2308_1_2Kt {\n public static final int wasteland(int);\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc ...
mr-kaffee__aoc-2023__5cbd13d/day09/kotlin/RJPlog/day2309_1_2.kt
import java.io.File import kotlin.math.* fun day09(in1: Int): Long { var result = 0L var lines = File("day2309_puzzle_input.txt").readLines() lines.forEach { var line = it.split(" ").map { it.toLong() }.toList() var interpolationValues = mutableListOf<Long>() var diffList = mutableListOf<Long>() if (in1 == 1) { diffList = line.windowed(2).map { it[1] - it[0] }.toMutableList() interpolationValues.add(line.last()) interpolationValues.add(diffList.last()) } else { diffList = line.windowed(2).map { it[0] - it[1] }.toMutableList() interpolationValues.add(line.first()) interpolationValues.add(diffList.first()) } while (diffList.distinct().size > 1 || diffList[0] != 0L) { if (in1 == 1) { diffList = diffList.windowed(2).map { it[1] - it[0] }.toMutableList() interpolationValues.add(diffList.last()) } else { diffList = diffList.windowed(2).map { it[0] - it[1] }.toMutableList() interpolationValues.add(diffList.first()) } } result += interpolationValues.sum() } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = day09(1) var solution2 = day09(2) // print solution for part 1 println("*******************************") println("--- Day 9: Mirage Maintenance ---") println("*******************************") println("Solution for part1") println(" $solution1 ") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 ") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2309_1_2Kt.class", "javap": "Compiled from \"day2309_1_2.kt\"\npublic final class Day2309_1_2Kt {\n public static final long day09(int);\n Code:\n 0: lconst_0\n 1: lstore 21\n 3: new #8 // class java/io/...
mr-kaffee__aoc-2023__5cbd13d/day05/kotlin/RJPlog/day2305_1_2.kt
import java.io.File import kotlin.math.* fun fertilizer(): Long { var locationList = mutableListOf<Long>() var newLocationList = mutableListOf<Long>() File("day2305_puzzle_input.txt").forEachLine { if (it.contains("seeds: ")) { locationList = it.substringAfter("seeds: ").split(" ").map { it.toLong() }.toMutableList() newLocationList = it.substringAfter("seeds: ").split(" ").map { it.toLong() }.toMutableList() } if (it.length != 0 && it.first().isDigit()) { var convertInstruction = it.split(" ") var range = LongRange( convertInstruction[1].toLong(), convertInstruction[1].toLong() + convertInstruction[2].toLong() - 1 ) for (i in 0..locationList.size - 1) { if (range.contains(locationList[i])) { newLocationList[i] = locationList[i] - convertInstruction[1].toLong() + convertInstruction[0].toLong() } } } if (it.length == 0) { locationList.clear() locationList.addAll(newLocationList) //println (newLocationList) } } return newLocationList.min()!! } fun main() { var t1 = System.currentTimeMillis() var solution1 = fertilizer() // part 2 brutal force - takes 2 days var solution2: Long = -1 var instruction = File("day2305_puzzle_input.txt").readLines() var seeds = instruction[0] var seedRanges = seeds.substringAfter("seeds: ").split(" ").map { it.toLong() }.toList() seedRanges.chunked(2).forEach { var i: Long = 0 while (i < it.last()) { var location: Long = it.first() + i var newLocation: Long = location instruction.forEach { if (it.length != 0 && it.first().isDigit()) { var convertInstruction = it.split(" ") var range = LongRange( convertInstruction[1].toLong(), convertInstruction[1].toLong() + convertInstruction[2].toLong() - 1 ) if (range.contains(location)) { newLocation = location - convertInstruction[1].toLong() + convertInstruction[0].toLong() } } if (it.length == 0) { location = newLocation } } var x = newLocation if (x < solution2 || solution2 < 0) solution2 = x i += 1 } } // print solution for part 1 println("*******************************") println("--- Day 5: If You Give A Seed A Fertilizer ---") println("*******************************") println("Solution for part1") println(" $solution1 is the lowest location number that corresponds to any of the initial seed numbers") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the lowest location number that corresponds to any of the initial seed numbers") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2305_1_2Kt.class", "javap": "Compiled from \"day2305_1_2.kt\"\npublic final class Day2305_1_2Kt {\n public static final long fertilizer();\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$ObjectRef\n 3: dup\n ...
mr-kaffee__aoc-2023__5cbd13d/day06/kotlin/RJPlog/day2306_1_2.kt
import java.io.File fun waitForIt(in1: Int): Long { val pattern = """(\d)+""".toRegex() var lines = File("day2306_puzzle_input.txt").readLines() var line0 = pattern.findAll(lines[0]).map { it.value }.toList() var line1 = pattern.findAll(lines[1]).map { it.value }.toList() var time = mutableListOf<Pair<Long, Long>>() if (in1 == 1) { for (i in 0..line0.size - 1) { time.add(Pair(line0[i].toLong(), line1[i].toLong())) } } else { time.add(Pair(line0.joinToString("").toLong(), line1.joinToString("").toLong())) } var result = 1L time.forEach { var wins = 0L for (i in 0..it.first) { var dist = i * (it.first - i) if (dist > it.second) { wins += 1L } } result *= wins } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = waitForIt(1) var solution2 = waitForIt(2) // print solution for part 1 println("*******************************") println("--- Day 6: Wait For It ---") println("*******************************") println("Solution for part1") println(" $solution1 do you get if you multiply these numbers together") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 many ways can you beat the record in this one much longer race") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2306_1_2Kt.class", "javap": "Compiled from \"day2306_1_2.kt\"\npublic final class Day2306_1_2Kt {\n public static final long waitForIt(int);\n Code:\n 0: new #8 // class kotlin/text/Regex\n 3: dup\n 4: ldc ...
mr-kaffee__aoc-2023__5cbd13d/day03/kotlin/RJPlog/day2303_1_2.kt
import java.io.File import kotlin.math.* fun gearRatio(): Int { var result = 0 val patternSymbol = """\W""".toRegex() val patternPartNumber = """(\d)+""".toRegex() var y = 0 File("day2303_puzzle_input.txt").forEachLine { var matchSymbol = patternSymbol.findAll(it.replace(".", "a")) matchSymbol.forEach { var x = it.range.first //println("${it.value}: $y $x") var yPartNumber = 0 File("day2303_puzzle_input.txt").forEachLine { var matchPartNumber = patternPartNumber.findAll(it) matchPartNumber.forEach { //println(" ${it.value.toInt()}: $yPartNumber, ${it.range}") var rangeCheck = IntRange(it.range.first-1, it.range.last + 1) if (abs(y - yPartNumber) < 2 && rangeCheck.contains(x)) { //println(" -> ok") // if there are more than one symbols adjacent to a number, this has to be reworked. // (swich order, look for partNumber and check for adjacent symbols, break after // first symbol is found.) result += it.value.toInt() } } yPartNumber += 1 } } y += 1 } return result } fun gearRatioPart2(): Int { var result = 0 val patternSymbol = """\*""".toRegex() val patternPartNumber = """(\d)+""".toRegex() var y = 0 File("day2303_puzzle_input.txt").forEachLine { var matchSymbol = patternSymbol.findAll(it) matchSymbol.forEach { var gearRatio = 1 var gearCount = 0 var x = it.range.first var yPartNumber = 0 File("day2303_puzzle_input.txt").forEachLine { var matchPartNumber = patternPartNumber.findAll(it) matchPartNumber.forEach { var rangeCheck = IntRange(it.range.first-1, it.range.last + 1) if (abs(y - yPartNumber) < 2 && rangeCheck.contains(x)) { gearRatio *= it.value.toInt() gearCount += 1 } } yPartNumber += 1 } if (gearCount == 2) result += gearRatio } y += 1 } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = gearRatio() var solution2 = gearRatioPart2() // print solution for part 1 println("*******************************") println("--- Day 3: Gear Ratios ---") println("*******************************") println("Solution for part1") println(" $solution1 is the sum of all of the part numbers in the engine schematic") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the sum of all of the gear ratios in your engine schematic") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day2303_1_2Kt.class", "javap": "Compiled from \"day2303_1_2.kt\"\npublic final class Day2303_1_2Kt {\n public static final int gearRatio();\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$IntRef\n 3: dup\n 4:...
mr-kaffee__aoc-2023__5cbd13d/day02/kotlin/RJPlog/day02_1_2.kt
import java.io.File fun cube(in1: Int): Int { var result = 0 File("day2302_puzzle_input.txt").forEachLine { var gamePossible = true var maxRed = 0 var maxGreen = 0 var maxBlue = 0 var instruction = it.split(": ") var game = instruction[0].substringAfter("Game ").toInt() var results = instruction[1].split("; ") results.forEach{ var colours = it.split(", ") colours.forEach{ if (it.contains("green")) { if (it.substringBefore(" green").toInt() > 13) { gamePossible = false } maxGreen = maxOf(maxGreen, it.substringBefore(" green").toInt()) } if (it.contains("red")) { if (it.substringBefore(" red").toInt() > 12) { gamePossible = false } maxRed = maxOf(maxRed, it.substringBefore(" red").toInt()) } if (it.contains("blue")) { if (it.substringBefore(" blue").toInt() > 14) { gamePossible = false } maxBlue = maxOf(maxBlue, it.substringBefore(" blue").toInt()) } } } if (in1 == 1) { if (gamePossible) result += game } else { result += maxRed * maxGreen * maxBlue } } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = cube(1) var solution2 = cube(2) // print solution for part 1 println("*******************************") println("--- Day 2: Cube Conundrum ---") println("*******************************") println("Solution for part1") println(" $solution1 is the sum of the IDs of those games") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the sum of the power of these sets") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
[ { "class_path": "mr-kaffee__aoc-2023__5cbd13d/Day02_1_2Kt.class", "javap": "Compiled from \"day02_1_2.kt\"\npublic final class Day02_1_2Kt {\n public static final int cube(int);\n Code:\n 0: new #8 // class kotlin/jvm/internal/Ref$IntRef\n 3: dup\n 4: invokes...
Rxfa__kotlin-basics__5ba1a7e/DiagonalDifference.kt
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* /* * Hackerrank - Diagonal Difference * https://www.hackerrank.com/challenges/diagonal-difference/problem */ fun diagonalDifference(arr: Array<Array<Int>>): Int { var primaryDiagonal = 0 var secondaryDiagonal = 0 var counter = 0 for(line in 1..arr.size){ primaryDiagonal += arr[counter][counter] secondaryDiagonal += arr[counter][(arr.size - 1) - counter] counter++ } return Math.abs(primaryDiagonal - secondaryDiagonal) } fun main(args: Array<String>) { val n = readLine()!!.trim().toInt() val arr = Array<Array<Int>>(n, { Array<Int>(n, { 0 }) }) for (i in 0 until n) { arr[i] = readLine()!!.trimEnd().split(" ").map{ it.toInt() }.toTypedArray() } val result = diagonalDifference(arr) println(result) }
[ { "class_path": "Rxfa__kotlin-basics__5ba1a7e/DiagonalDifferenceKt.class", "javap": "Compiled from \"DiagonalDifference.kt\"\npublic final class DiagonalDifferenceKt {\n public static final int diagonalDifference(java.lang.Integer[][]);\n Code:\n 0: aload_0\n 1: ldc #9 ...
mike10004__adventofcode2017__977c5c1/advent08/src/Registers.kt
import java.io.File import java.io.FileReader import java.util.stream.Stream fun main(args: Array<String>) { FileReader(File("./input.txt")).buffered().use { main(it.lines()) } } fun doExample() { val lines = listOf( "b inc 5 if a > 1", "a inc 1 if b < 5", "c dec -10 if a >= 1", "c inc -20 if c == 10" ) main(lines.stream()) } fun main(instructionLines: Stream<String>) { val registers = HashMap<String, Int>() var overallMax = Int.MIN_VALUE instructionLines.forEach({ line -> parseInstruction(line).perform(registers) val currentMax = registers.values.max() ?: Int.MIN_VALUE if (currentMax > overallMax) { overallMax = currentMax } }) println(registers) val maxValue = registers.values.max() println("current max value is $maxValue") println("overall max value seen is $overallMax") } enum class Operator(val token : String) { GT(">"), LT("<"), GTE(">="), LTE("<="), EQ("=="), NE("!=") } fun parseOperator(token: String) : Operator { Operator.values() .filter { token == it.token } .forEach { return it } throw IllegalArgumentException("token does not represent an operator: " + token); } class Condition( val label : String, val operator : Operator, val reference : Int ) { fun evaluate(registers: Map<String, Int>) : Boolean { val query = registers.getOrDefault(label, 0) return when (operator) { Operator.GT -> query > reference Operator.GTE -> query >= reference Operator.LT -> query < reference Operator.LTE -> query <= reference Operator.EQ -> query == reference Operator.NE -> query != reference } } } class Instruction( val target: String, val delta: Int, val condition : Condition ) { fun perform(registers: MutableMap<String, Int>) { var value = registers.getOrDefault(target, 0) if (condition.evaluate(registers)) { value += delta } registers.put(target, value) } } fun parseInstruction(line: String): Instruction { val tokens = line.split(Regex("\\s+")) val delta = tokens[2].toInt() * (if ("inc" == tokens[1]) 1 else -1) val condition = Condition(tokens[4], parseOperator(tokens[5]), tokens[6].toInt()) return Instruction(tokens[0], delta, condition) }
[ { "class_path": "mike10004__adventofcode2017__977c5c1/RegistersKt.class", "javap": "Compiled from \"Registers.kt\"\npublic final class RegistersKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #11 // String args\n 3: invo...
codinasion__program__d8880e3/program/add-two-matrices/AddTwoMatrices.kt
fun main() { print("Enter the two matrices line separated: \n") val size = 3 val a = readMatrix(size) readln() val b = readMatrix(size) val c = addMatrices(a, b) println("Result of adding the matrices: \n") printMatrix(c) } // Takes number of rows and columns and reads the matrix from input fun readMatrix(rows : Int): ArrayList<ArrayList<Int>>{ val matrix = arrayListOf<ArrayList<Int>>() for(row in 0 until rows){ val line = readln().trim().split(' ') matrix.add(ArrayList()) for(number in line){ matrix[row].add(Integer.valueOf(number)) } } return matrix } // prints a matrix fun printMatrix(matrix : ArrayList<ArrayList<Int>>){ for (row in matrix){ for (cell in row){ print("$cell ") } println() } } // adds two matrices and return the result in a new matrix fun addMatrices(a : ArrayList<ArrayList<Int>>, b : ArrayList<ArrayList<Int>>) : ArrayList<ArrayList<Int>>{ val c = a.clone() as ArrayList<ArrayList<Int>> for(i in 0 until b.size){ for(j in 0 until b.size){ c[i][j] += b[i][j] } } return c }
[ { "class_path": "codinasion__program__d8880e3/AddTwoMatricesKt.class", "javap": "Compiled from \"AddTwoMatrices.kt\"\npublic final class AddTwoMatricesKt {\n public static final void main();\n Code:\n 0: ldc #8 // String Enter the two matrices line separated: \\n\n ...
mdenburger__aoc-2020__b965f46/src/main/kotlin/day11/Day11.kt
import java.io.File import java.lang.Integer.max import kotlin.math.absoluteValue fun main() { val seatLayout = File("src/main/kotlin/day11/day11-input.txt").readLines().map { it.toCharArray() } var current = seatLayout var currentHashCode = current.contentHashCode() val found = mutableSetOf<Int>() while (!found.contains(currentHashCode)) { found.add(currentHashCode) current = current.nextSeatLayout() currentHashCode = current.contentHashCode() } println("Answer 1: " + current.occupiedSeatCount()) } private fun List<CharArray>.contentHashCode(): Int = fold(0) { result, line -> result + 31 * line.contentHashCode() } private fun List<CharArray>.nextSeatLayout(): List<CharArray> { val next = toMutableList().map { it.clone() } for (row in 0 until size) { for (column in 0 until width()) { when (get(row)[column]) { 'L' -> if (noSeatsAround(row, column)) { next[row][column] = '#' } '#' -> if (atLeastFourSeatsAround(row, column)) { next[row][column] = 'L' } } } } return next } private fun List<CharArray>.width() = first().size private fun List<CharArray>.noSeatsAround(row: Int, column: Int) = forSeatsAround(row, column, true) { false } private fun List<CharArray>.atLeastFourSeatsAround(row: Int, column: Int): Boolean { var count = 0 return forSeatsAround(row, column, false) { count += 1 if (count == 4) true else null } } private fun List<CharArray>.forSeatsAround(row: Int, column: Int, default: Boolean, block: List<CharArray>.() -> Boolean?): Boolean { for (dx in -1..1) { for (dy in -1..1) { val x = column + dy val y = row + dx if (!(x == column && y == row) && x >= 0 && x < width() && y >= 0 && y < size && get(y)[x] == '#') { val result = block() if (result != null) { return result } } } } return default } private fun List<CharArray>.occupiedSeatCount() = map { row -> row.count { it == '#' } }.sum() fun List<CharArray>.print() { forEach { println(it.joinToString("")) } }
[ { "class_path": "mdenburger__aoc-2020__b965f46/Day11Kt.class", "javap": "Compiled from \"Day11.kt\"\npublic final class Day11Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: ldc #10 // S...