kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
Laomedeia__Java8InAction__0dcd843/src/main/java/leetcode/a167_twoSumInputSortArray_SIMPLE/Solution.kt
package leetcode.a167_twoSumInputSortArray_SIMPLE /** * 两数之和 II - 输入有序数组 * 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明: 返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 */ class Solution { /** * 解题思路: * https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/solution/shuang-zhi-zhen-on-shi-jian-fu-za-du-by-cyc2018/ 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。 如果两个指针指向元素的和 sum == targetsum==target,那么得到要求的结果; 如果 sum > targetsum>target,移动较大的元素,使 sumsum 变小一些; 如果 sum < targetsum<target,移动较小的元素,使 sumsum 变大一些。 数组中的元素最多遍历一次,时间复杂度为 O(N)O(N)。只使用了两个额外变量,空间复杂度为 O(1)O(1)。 */ fun twoSum(numbers: IntArray, target: Int): IntArray { if (numbers == null) return intArrayOf() var i = 0 var j = numbers.size - 1 while (i < j) { var sum = numbers[i] + numbers[j]; if (sum == target) { return intArrayOf(i + 1, j + 1) } else if (sum < target) { i++ } else { j-- } } return intArrayOf() } }
[ { "class_path": "Laomedeia__Java8InAction__0dcd843/leetcode/a167_twoSumInputSortArray_SIMPLE/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class leetcode.a167_twoSumInputSortArray_SIMPLE.Solution {\n public leetcode.a167_twoSumInputSortArray_SIMPLE.Solution();\n Code:\n 0:...
Laomedeia__Java8InAction__0dcd843/src/main/java/leetcode/a392_isSubSequence_HARD/Solution.kt
package leetcode.a392_isSubSequence_HARD /** * 判断子序列 * * 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 * 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 * * 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 * * 示例 1: * s = "abc", t = "ahbgdc" * 返回 true. * * 示例 2: * s = "axc", t = "ahbgdc" * 返回 false. * * 后续挑战 : * 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码? * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/is-subsequence * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author neptune * @create 2020 07 27 9:27 下午 */ class Solution { fun isSubsequence(s: String, t: String): Boolean { if (s.length == 0) return true; var indexS = 0 var indexT = 0 while (indexT < t.length) { if (t[indexT] == s[indexS]) { //指向s的指针只有在两个字符串相同时才会往右移 indexS++; if (indexS == s.length) return true; } //指向t的指针每次都会往右移一位 indexT++; } return false } }
[ { "class_path": "Laomedeia__Java8InAction__0dcd843/leetcode/a392_isSubSequence_HARD/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class leetcode.a392_isSubSequence_HARD.Solution {\n public leetcode.a392_isSubSequence_HARD.Solution();\n Code:\n 0: aload_0\n 1: invokes...
scp504677840__JavaKotlin__36f9b85/Collection/List/part06.kt
package part06 import java.util.TreeSet fun main(args: Array<String>) { /*val treeSet = TreeSet<String>() treeSet.add("adbbcc") treeSet.add("abbabc") treeSet.add("acbcc") treeSet.add("abbc") treeSet.add("abcc") val iterator = treeSet.iterator() while (iterator.hasNext()) { println(iterator.next()) }*/ /* //元素自身具备比较性,实现Comparable接口即可。 val treeSet = TreeSet<Student>() treeSet.add(Student("aa", 11)) treeSet.add(Student("bb", 22)) treeSet.add(Student("cc", 8)) treeSet.add(Student("dd", 6)) treeSet.add(Student("ee", 6)) val iterator = treeSet.iterator() while (iterator.hasNext()) { val student = iterator.next() println("student:${student.name}--${student.age}") }*/ //当元素不具备比较性,我们可以传入自定义比较器 val treeSet = TreeSet<Student>(MyCompare()) treeSet.add(Student("aa", 11)) treeSet.add(Student("bb", 22)) treeSet.add(Student("cc", 8)) treeSet.add(Student("dd", 6)) treeSet.add(Student("ee", 6)) val iterator = treeSet.iterator() while (iterator.hasNext()) { val student = iterator.next() println("student:${student.name}--${student.age}") } } /** * 实现Comparable接口,实现比较方法 */ private data class Student constructor(var name: String, var age: Int) : Comparable<Student> { override fun compareTo(other: Student): Int { if (age > other.age) return 1 //注意:比较了主要条件以后,需要比较次要条件。 if (age == other.age) { return name.compareTo(other.name) } return -1 } } /** * 自定义比较器(推荐这种比较形式) */ private class MyCompare : Comparator<Student> { override fun compare(o1: Student, o2: Student): Int { val compareTo = o1.age.compareTo(o2.age) if (compareTo == 0) { return o1.name.compareTo(o2.name) } return compareTo } }
[ { "class_path": "scp504677840__JavaKotlin__36f9b85/part06/Part06Kt.class", "javap": "Compiled from \"part06.kt\"\npublic final class part06.Part06Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: in...
jaypandya__dsa__5f94df9/src/main/java/org/example/BiPartiteGraph.kt
package org.example class Solution { enum class Color { Red, Blue, None; } fun isBipartite(graph: Array<IntArray>): Boolean { val queue = ArrayDeque<Int>() val colorArray = Array(graph.size) { Color.None } for (index in colorArray.indices) { if (colorArray[index] != Color.None) continue colorArray[index] = Color.Red queue.addLast(index) while (queue.isNotEmpty()) { val node = queue.removeFirst() val nodeColor = colorArray[node] val neighborColor = if (nodeColor == Color.Red) Color.Blue else Color.Red val neighbors = graph[node] for (neighbor in neighbors) { if (colorArray[neighbor] == Color.None) { colorArray[neighbor] = neighborColor queue.addLast(neighbor) } else if (colorArray[neighbor] == nodeColor) { return false } } } } return true } } fun parseGraph(s: String): Array<IntArray> { var bracketCount = 0 val array = mutableListOf<IntArray>() var innerList: MutableList<Int> = mutableListOf() for (char in s.toCharArray()) { if (char == '[') { bracketCount++ if (bracketCount == 2) { innerList = mutableListOf() } } else if (char == ']') { bracketCount-- if (bracketCount == 1) { array.add(innerList.toIntArray()) } } else if (char == ',') { continue } else { if (bracketCount == 2) { innerList.add(char.digitToInt()) } } } return array.toTypedArray() } fun main() { val graph1 = arrayOf( intArrayOf(1, 2, 3), intArrayOf(0, 2), intArrayOf(0, 1, 3), intArrayOf(0, 2) ) val graph2 = arrayOf( intArrayOf(1, 3), intArrayOf(0, 2), intArrayOf(1, 3), intArrayOf(0, 2) ) val graph74 = parseGraph("[[],[3],[],[1],[]]") val graph76 = parseGraph("[[],[2,4,6],[1,4,8,9],[7,8],[1,2,8,9],[6,9],[1,5,7,8,9],[3,6,9],[2,3,4,6,9],[2,4,5,6,7,8]]") // [[1],[0,3],[3],[1,2]] val graph78 = arrayOf( intArrayOf(1), intArrayOf(0, 3), intArrayOf(3), intArrayOf(1, 2) ) val solution = Solution() assert(!solution.isBipartite(graph1)) assert(solution.isBipartite(graph2)) assert(solution.isBipartite(graph74)) assert(!solution.isBipartite(graph76)) assert(solution.isBipartite(graph78)) }
[ { "class_path": "jaypandya__dsa__5f94df9/org/example/BiPartiteGraphKt.class", "javap": "Compiled from \"BiPartiteGraph.kt\"\npublic final class org.example.BiPartiteGraphKt {\n public static final int[][] parseGraph(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #9 ...
regen-network__regen-kotlin-sdk__ea05372/ceres-base/src/main/kotlin/ceres/geo/Selection.kt
package ceres.geo import kotlin.math.* // Floyd-Rivest selection algorithm from https://github.com/mourner/quickselect fun quickselect( arr: Array<Double>, k: Int, left: Int = 0, right: Int = arr.size - 1, compare: Comparator<Double> = defaultCompare ) { quickselectStep(arr, k, left, right, compare) } fun quickselectStep( arr: Array<Double>, k: Int, l: Int, r: Int, compare: Comparator<Double> ){ var left = l var right = r while(right > left) { if (right - left > 600) { val n = right - left + 1 val m = k - left val z = ln(n.toFloat()) val s = 0.5 * exp(2 * z / 3) val sd = 0.5 * sqrt(z * s * (n - s) / n) * (if (m - n / 2 < 0) -1 else 1) val newLeft = max(left, floor(k - m * s / n + sd).toInt()) val newRight = min(right, floor(k + (n - m) * s / n + sd).toInt()) quickselectStep(arr, k, newLeft, newRight, compare) } val t = arr[k] var i = left var j = right swap(arr, left, k) if (compare.compare(arr[right], t) > 0) swap(arr, left, right) while (i < j) { swap(arr, i, j) i++ j++ while (compare.compare(arr[i], t) < 0) i++ while (compare.compare(arr[j], t) > 0) i++ } if (compare.compare(arr[left], t) == 0) swap(arr, left, j) else { j++ swap(arr, j, right) } if (j <= k) left = j + 1 if (k <= j) right = j - 1 } } fun swap(arr: Array<Double>, i: Int, j: Int) { val tmp = arr[i] arr[i] = arr[j] arr[j] = tmp } val defaultCompare: Comparator<Double> = object : Comparator<Double> { override fun compare(a: Double, b: Double): Int = a.compareTo(b) }
[ { "class_path": "regen-network__regen-kotlin-sdk__ea05372/ceres/geo/SelectionKt$defaultCompare$1.class", "javap": "Compiled from \"Selection.kt\"\npublic final class ceres.geo.SelectionKt$defaultCompare$1 implements java.util.Comparator<java.lang.Double> {\n ceres.geo.SelectionKt$defaultCompare$1();\n C...
iluu__algs-progfun__a89b0d3/src/main/kotlin/com/hackerrank/FormingAMagicSquare.kt
package com.hackerrank import java.util.* val magicSquares = arrayOf( intArrayOf(8, 1, 6, 3, 5, 7, 4, 9, 2), intArrayOf(4, 3, 8, 9, 5, 1, 2, 7, 6), intArrayOf(2, 9, 4, 7, 5, 3, 6, 1, 8), intArrayOf(6, 7, 2, 1, 5, 9, 8, 3, 4), intArrayOf(6, 1, 8, 7, 5, 3, 2, 9, 4), intArrayOf(8, 3, 4, 1, 5, 9, 6, 7, 2), intArrayOf(4, 9, 2, 3, 5, 7, 8, 1, 6), intArrayOf(2, 7, 6, 9, 5, 1, 4, 3, 8)) fun main(args: Array<String>) { val scan = Scanner(System.`in`) val arr = IntArray(9) for (i in 0..2) { for (j in 0..2) { arr[i * 3 + j] = scan.nextInt() } } println(minimalCost(arr)) } fun minimalCost(arr: IntArray): Int { return magicSquares.map { arr.zip(it) .filter { (first, second) -> first != second } .sumBy { (first, second) -> Math.abs(first - second) } }.min()!! }
[ { "class_path": "iluu__algs-progfun__a89b0d3/com/hackerrank/FormingAMagicSquareKt.class", "javap": "Compiled from \"FormingAMagicSquare.kt\"\npublic final class com.hackerrank.FormingAMagicSquareKt {\n private static final int[][] magicSquares;\n\n public static final int[][] getMagicSquares();\n Code:...
iluu__algs-progfun__a89b0d3/src/main/kotlin/com/hackerrank/ConnectedCellsInAGrid.kt
package com.hackerrank import java.util.* fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextInt() val m = scan.nextInt() val arr = Array(n, { Array(m, { scan.nextInt() }) }) println(sizeOfMaxRegion(Board(arr, n, m))) } fun sizeOfMaxRegion(board: Board): Int { var maxSize = 0 for (i in 0..board.n - 1) { for (j in 0..board.m - 1) { val node = Pair(i, j) if (!board.wasVisited(node)) { val size = regionSize(node, board) if (size > maxSize) { maxSize = size } } } } return maxSize } fun regionSize(node: Pair<Int, Int>, board: Board): Int { var region = if (board.isNode(node)) 1 else 0 board.markVisited(node) board.neighbours(node) .map { regionSize(it, board) } .forEach { region += it } return region } class Board(val arr: Array<Array<Int>>, val n: Int, val m: Int) { private var visited = mutableSetOf<Pair<Int, Int>>() fun markVisited(node: Pair<Int, Int>) { visited.add(node) } fun neighbours(node: Pair<Int, Int>): List<Pair<Int, Int>> { val neighbours = setOf( Pair(node.first - 1, node.second - 1), Pair(node.first - 1, node.second), Pair(node.first - 1, node.second + 1), Pair(node.first, node.second - 1), Pair(node.first, node.second + 1), Pair(node.first + 1, node.second - 1), Pair(node.first + 1, node.second), Pair(node.first + 1, node.second + 1)) return neighbours.filter { (first, second) -> valid(first, second) } } fun isNode(pair: Pair<Int, Int>): Boolean { return arr[pair.first][pair.second] == 1 && !wasVisited(pair) } fun wasVisited(pair: Pair<Int, Int>): Boolean { return visited.contains(pair) } private fun valid(row: Int, col: Int): Boolean { return row in 0..n - 1 && col in 0..m - 1 && arr[row][col] == 1 && !wasVisited(Pair(row, col)) } }
[ { "class_path": "iluu__algs-progfun__a89b0d3/com/hackerrank/ConnectedCellsInAGridKt.class", "javap": "Compiled from \"ConnectedCellsInAGrid.kt\"\npublic final class com.hackerrank.ConnectedCellsInAGridKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc ...
booknara__playground__04dcf50/src/main/java/com/booknara/problem/graph/EvaluateDivisionKt.kt
package com.booknara.problem.graph /** * 399. Evaluate Division (Medium) * https://leetcode.com/problems/evaluate-division/ */ class EvaluateDivisionKt { // T:O(v+e), S:O(v+e) fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray { // build a graph for the equations val res = DoubleArray(queries.size) val graph = HashMap<String, ArrayList<Pair<String, Double>>>() for (i in equations.indices) { val first = equations[i][0] val second = equations[i][1] val value = values[i] graph.putIfAbsent(first, ArrayList()) graph.putIfAbsent(second, ArrayList()) graph[first]?.add(Pair(second, value)) graph[second]?.add(Pair(first, 1.0 / value)) } for (i in 0..queries.size - 1) { val start = queries[i][0] val end = queries[i][1] res[i] = dfs(start, end, graph, HashSet()) } return res } fun dfs(start: String, end: String, graph: HashMap<String, ArrayList<Pair<String, Double>>>, visited: HashSet<String>): Double { if (!graph.containsKey(start) && !graph.containsKey(end)) { return -1.0 } if (start == end) { return 1.0 } visited.add(start) if (graph.containsKey(start)) { val list = graph.getValue(start) for (i in 0..list.size - 1) { val pair = list.get(i) if (!visited.contains(pair.first)) { val res = dfs(pair.first, end, graph, visited) if (res != -1.0) { return res * pair.second; } } } } return -1.0 } } fun main(args: Array<String>) { val equations = listOf(listOf("a", "b"), listOf("b", "c")) val values = doubleArrayOf(2.0,3.0) val queries = listOf(listOf("a", "c"), listOf("b", "a"), listOf("a", "e"), listOf("a", "a"), listOf("x", "x")) val result = EvaluateDivisionKt().calcEquation(equations, values, queries) for (r in result) { println(r) } }
[ { "class_path": "booknara__playground__04dcf50/com/booknara/problem/graph/EvaluateDivisionKtKt.class", "javap": "Compiled from \"EvaluateDivisionKt.kt\"\npublic final class com.booknara.problem.graph.EvaluateDivisionKtKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n...
booknara__playground__04dcf50/src/main/java/com/booknara/problem/math/ValidSquare.kt
package com.booknara.problem.math /** * 593. Valid Square (Medium) * https://leetcode.com/problems/valid-square/ */ class ValidSquare { // T:O(1), S:O(1) fun validSquare(p1: IntArray, p2: IntArray, p3: IntArray, p4: IntArray): Boolean { // input check, there are four points val points = arrayOf(p1, p2, p3, p4) points.sortWith(compareBy<IntArray> { it[0] }.thenBy { it[1] }) return (getDistance(points[0], points[1]) != 0) and (getDistance(points[0], points[1]) == getDistance(points[1], points[3])) and (getDistance(points[1], points[3]) == getDistance(points[3], points[2])) and (getDistance(points[3], points[2]) == getDistance(points[2], points[0])) and (getDistance(points[0], points[3]) == getDistance(points[1], points[2])) } private fun getDistance(p1: IntArray, p2: IntArray) = (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]) } fun main() { val valid = ValidSquare().validSquare( intArrayOf(0, 0), intArrayOf(5, 0), intArrayOf(5, 4), intArrayOf(0, 4) ) println(valid) } /* (0,4) (5,4) (0,0) (5,0) [1134,-2539] [492,-1255] [-792,-1897] [-150,-3181] */
[ { "class_path": "booknara__playground__04dcf50/com/booknara/problem/math/ValidSquareKt.class", "javap": "Compiled from \"ValidSquare.kt\"\npublic final class com.booknara.problem.math.ValidSquareKt {\n public static final void main();\n Code:\n 0: new #8 // class com/boo...
booknara__playground__04dcf50/src/main/java/com/booknara/practice/kotlin/higherorderfunction/Groceries.kt
package com.booknara.practice.kotlin.higherorderfunction data class Grocery( val name: String, val category: String, val unit: String, val unitPrice: Double, val quantity: Int) fun main(args: Array<String>) { val groceries = listOf<Grocery>( Grocery("Tomatoes", "Vegetable", "lb", 3.0, 3), Grocery("Mushroom", "Vegetable", "lb", 4.0, 1), Grocery("Bagels", "Bakery", "Pack", 1.5, 2), Grocery("Olive oil", "Pantry", "Bottle", 6.0, 1), Grocery("Ice cream", "Frozen", "Pack", 3.0, 2) ) val highestUnitPrice = groceries.maxBy { it.unitPrice * 5 } println("highestUnitPrice: $highestUnitPrice") val lowestQuantity = groceries.minBy { it.quantity } println("lowestQuantity: $lowestQuantity") val sumQuantity = groceries.sumBy { it.quantity } println("sumQuantity: $sumQuantity") val totalPrice = groceries.sumByDouble { it.unitPrice * it.quantity } println("totalPrice: $totalPrice") val vegetables = groceries.filter { it.category == "Vegetable" } val unitPriceOver3 = groceries.filter { it.unitPrice > 3.0 } val nonFrozen = groceries.filterNot { it.category != "Frozen" } val groceryNames = groceries.map { it.name } val halfUnitPrice = groceries.map { it.unitPrice * 0.5 } val newPrices = groceries.filter { it.unitPrice > 3.0 } .map { it.unitPrice * 2 } for (item in groceries) { println(item.name) } groceries.forEach { println(it.name) } for (item in groceries) { if (item.unitPrice > 3.0) println(item.name) } groceries.filter { it.unitPrice > 3.0 } .forEach { println(it.name) } var itemNames = "" for (item in groceries) { itemNames += "${item.name} " } println("itemNames: $itemNames ") itemNames = "" groceries.forEach { itemNames += "${it.name} " } println("itemNames: $itemNames ") val groupBycategory = groceries.groupBy { it.category } // println(groupBycategory) groceries.groupBy { it.category }.forEach { println(it.key) it.value.forEach { println(" ${it.name}") } } val ints = listOf<Int>(1, 2, 3) val sumOfInts = ints.fold(0) { runningSum, item -> runningSum + item } println("sumOfInts: $sumOfInts") println(sumOfInts.javaClass.kotlin.simpleName) val productOfInts = ints.fold(1) { runningSum, item -> runningSum * item } println("productOfInts: $productOfInts") val names = groceries.fold("") { string, item -> string + " ${item.name}" } println("names: $names") val changeFrom50 = groceries.fold(50.0) { change, item -> change - item.unitPrice * item.quantity } println("changeFrom50: $changeFrom50") }
[ { "class_path": "booknara__playground__04dcf50/com/booknara/practice/kotlin/higherorderfunction/GroceriesKt.class", "javap": "Compiled from \"Groceries.kt\"\npublic final class com.booknara.practice.kotlin.higherorderfunction.GroceriesKt {\n public static final void main(java.lang.String[]);\n Code:\n ...
h-j-k__advent16__5ffa381/src/main/kotlin/com/advent/of/code/hjk/Day22.kt
package com.advent.of.code.hjk import kotlin.math.abs object Day22 { private fun parse(line: String): Node? = "/dev/grid/node-x(?<x>\\d+)-y(?<y>\\d+)\\s+(?<size>\\d+)T\\s+(?<used>\\d+)T.+".toRegex() .matchEntire(line)?.destructured ?.let { (x, y, size, used) -> Node(x.toInt(), y.toInt(), size.toInt(), used.toInt()) } fun part1(input: List<String>): Int { val nodes = input.drop(2).mapNotNull { parse(it) } return nodes.flatMap { node -> nodes.mapNotNull { other -> setOf(node, other).takeIf { node != other && node.used > 0 && node.used <= other.avail } } }.toSet().size } fun part2(input: List<String>): Int { val nodes = input.drop(2).mapNotNull { parse(it) }.sortedByDescending { it.avail } val maxX = nodes.maxOf { it.x } val wall = nodes.filter { it.size > 250 }.minByOrNull { it.x }!! val emptyNode = nodes.first { it.used == 0 } var result = abs(emptyNode.x - wall.x) + 1 result += emptyNode.y result += maxX - wall.x return result + (5 * (maxX - 1)) + 1 } internal data class Node(val x: Int, val y: Int, val size: Int, val used: Int) { val avail = size - used } }
[ { "class_path": "h-j-k__advent16__5ffa381/com/advent/of/code/hjk/Day22$Node.class", "javap": "Compiled from \"Day22.kt\"\npublic final class com.advent.of.code.hjk.Day22$Node {\n private final int x;\n\n private final int y;\n\n private final int size;\n\n private final int used;\n\n private final int ...
h-j-k__advent16__5ffa381/src/main/kotlin/com/advent/of/code/hjk/Day24.kt
package com.advent.of.code.hjk import java.util.ArrayDeque object Day24 { private fun parse(input: List<String>): List<List<Position>> = input.indices.map { y -> input[0].indices.map { x -> Position(x = x, y = y, value = input[y][x].toString()) } } private fun Position.from(other: Position, board: List<List<Position>>): Int { val seen = mutableMapOf(this to 0) val queue = ArrayDeque<Position>().also { it.add(this) } while (queue.isNotEmpty()) { val current = queue.pop() val distance = seen.getValue(current) if (current == other) return distance listOf( board[current.y][current.x - 1], board[current.y][current.x + 1], board[current.y - 1][current.x], board[current.y + 1][current.x] ).filter { it.isValid && !it.isWall && it !in seen }.let { neighbors -> seen.putAll(neighbors.map { it to distance + 1 }) queue.addAll(neighbors) } } return 0 } private fun mapDistances(map: List<List<Position>>): Map<Pair<Int, Int>, Int> { val targets = map.flatMap { r -> r.mapNotNull { p -> p.n?.let { it to p } } }.toMap() return targets.flatMap { (target, position) -> targets.filter { it.key > target }.flatMap { (otherTarget, otherPosition) -> val distance = position.from(otherPosition, map) listOf(target to otherTarget, otherTarget to target).map { it to distance } } }.toMap() } private fun shortestPath(map: List<List<Position>>, isReturning: Boolean): Int { val (targets, distances) = mapDistances(map).let { it.keys.flatMap { (a, b) -> listOf(a, b) }.toSet() to it } fun move(leftover: Set<Int>, current: Int, steps: Int): Int = if (leftover.isEmpty()) steps + (distances.getValue(current to 0).takeIf { isReturning } ?: 0) else targets.filter { it in leftover } .minOf { move(leftover - it, it, steps + distances.getValue(current to it)) } return move(targets - 0, 0, 0) } fun part1(input: List<String>): Int = shortestPath(parse(input), false) fun part2(input: List<String>): Int = shortestPath(parse(input), true) private data class Position(val x: Int, val y: Int, val value: String) { val isValid = x >= 0 && y >= 0 val isWall = value == "#" val n = try { value.toInt() } catch (e: NumberFormatException) { null } } }
[ { "class_path": "h-j-k__advent16__5ffa381/com/advent/of/code/hjk/Day24$Position.class", "javap": "Compiled from \"Day24.kt\"\nfinal class com.advent.of.code.hjk.Day24$Position {\n private final int x;\n\n private final int y;\n\n private final java.lang.String value;\n\n private final boolean isValid;\n...
h-j-k__advent16__5ffa381/src/main/kotlin/com/advent/of/code/hjk/Day23.kt
package com.advent.of.code.hjk object Day23 { private fun process(input: List<String>, initial: Map<String, Int>): Int { val copy = input.toMutableList() val registers = initial.toMutableMap() var i = 0 while (i < copy.size) { val values = copy[i].split(" ") i++ when (values[0]) { "cpy" -> values[2].takeIf { it in "abcd" }?.let { registers[it] = parseOrGet(values[1], registers) } "inc" -> registers.compute(values[1]) { _, v -> v!! + 1 } "dec" -> registers.compute(values[1]) { _, v -> v!! - 1 } "jnz" -> { var value = parseOrGet(values[1], registers) val offset = parseOrGet(values[2], registers) if (value > 0) { val current = i - 1 i = current + offset if (values[1] in "abcd") { val loopOffset = copy.subList(i, current).indexOfFirst { it.matches("(inc|dec) ${values[1]}".toRegex()) } if (loopOffset < 0) continue val multiplier: Int val loopIndex: Int if (offset == -2) { multiplier = 1 loopIndex = if (loopOffset == 0) i + 1 else i } else { val inner = copy.subList(i, i + loopOffset) val innerLoopOffset = inner.indexOfFirst { it.matches("jnz.*-2".toRegex()) } val key = copy[i + innerLoopOffset].split(" ")[1] val from = inner.singleOrNull { it.matches("cpy . $key".toRegex()) } ?: continue multiplier = value value = registers.getValue(from.split(" ")[1]) val temp = copy.subList(i, i + innerLoopOffset) .indexOfFirst { it.matches("(inc|dec) $key".toRegex()) } loopIndex = if (temp + 1 == innerLoopOffset) i + temp - 1 else i + temp } val (loopInstruction, loopVariable) = copy[loopIndex].split(" ") if (loopInstruction == "inc") { registers.compute(loopVariable) { _, v -> v!! + value * multiplier } registers[values[1]] = 0 } else { registers.compute(loopVariable) { _, v -> v!! - value * multiplier } registers[values[1]] = 0 } i = current + 1 } } } "tgl" -> { val target = i - 1 + parseOrGet(values[1], registers) if (target < copy.size && target >= 0) { val newInstruction = when (copy[target].count { it == ' ' }) { 1 -> if (copy[target].startsWith("inc")) "dec" else "inc" 2 -> if (copy[target].startsWith("jnz")) "cpy" else "jnz" else -> values[0] } copy[target] = copy[target].replaceRange(0, 3, newInstruction) } } } } return registers.getValue("a") } private fun parseOrGet(value: String, registers: Map<String, Int>) = try { value.toInt() } catch (e: NumberFormatException) { registers.getValue(value) } fun part1(input: List<String>) = process(input, mapOf("a" to 7, "b" to 0, "c" to 0, "d" to 0)) fun part2(input: List<String>) = process(input, mapOf("a" to 12, "b" to 0, "c" to 0, "d" to 0)) }
[ { "class_path": "h-j-k__advent16__5ffa381/com/advent/of/code/hjk/Day23.class", "javap": "Compiled from \"Day23.kt\"\npublic final class com.advent.of.code.hjk.Day23 {\n public static final com.advent.of.code.hjk.Day23 INSTANCE;\n\n private com.advent.of.code.hjk.Day23();\n Code:\n 0: aload_0\n ...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day16.kt
package cz.wrent.advent import java.lang.Integer.max import java.util.Deque import java.util.LinkedList fun main() { // println(partOne(test)) // val result = partOne(input) // println("16a: $result") println(partTwo(test)) println("16b: ${partTwo(input)}") } private fun partOne(input: String): Int { val valves = input.toValves() calculateDistances(valves) return recursiveSolution(valves) } private fun recursiveSolution(valves: Map<String, Valve>): Int { val meaningful = valves.values.filter { it.flowRate > 0 }.sortedByDescending { it.flowRate }.map { it.label } return meaningful.map { process("AA", it, 30, 0, emptyList(), meaningful, valves) }.maxOf { it } } private fun process( current: String, next: String, minutes: Int, released: Int, opened: List<String>, meaningful: List<String>, valves: Map<String, Valve> ): Int { val distance = valves[current]!!.distances[next]!! val time = minutes - distance - 1 if (time < 1) { return released } val nextReleased = released + time * valves[next]!!.flowRate val nextOpened = opened + next if (meaningful.size == nextOpened.size) { return nextReleased } else { return meaningful.filterNot { nextOpened.contains(it) } .map { process(next, it, time, nextReleased, nextOpened, meaningful, valves) }.maxOf { it } } } fun <T> List<T>.permutations(): List<List<T>> = if (isEmpty()) listOf(emptyList()) else mutableListOf<List<T>>().also { result -> for (i in this.indices) { (this - this[i]).permutations().forEach { result.add(it + this[i]) } } } private fun calculateDistances(valves: Map<String, Valve>) { valves.values.filter { it.label == "AA" || it.flowRate > 0 }.forEach { curr -> curr.distances = calculateDistances(curr, valves) } } private fun calculateDistances(from: Valve, valves: Map<String, Valve>): Map<String, Int> { val nextValves: Deque<Pair<String, Int>> = LinkedList(listOf(from.label to 0)) val map = mutableMapOf<String, Int>() while (nextValves.isNotEmpty()) { val next = nextValves.pop() map[next.first] = next.second val nextValve = valves[next.first]!! val nextDistance = next.second + 1 nextValve.leadsTo.forEach { if (map[it] == null || map[it]!! > nextDistance) nextValves.push(it to next.second + 1) } } return map } private fun partTwo(input: String): Int { val valves = input.toValves() calculateDistances(valves) return recursiveSolutionWithElephant(valves) } private fun recursiveSolutionWithElephant(valves: Map<String, Valve>): Int { val meaningful = valves.values.filter { it.flowRate > 0 }.sortedByDescending { it.flowRate }.map { it.label } return meaningful.map { i -> meaningful.map { j -> if (i == j) -1 else processWithElephant("AA", "AA", i, j, 26, 26, 0, emptyList(), meaningful, valves) }.maxOf { it } }.maxOf { it } } private fun processWithElephant( current: String, currentElephant: String, next: String, nextElephant: String, minutes: Int, elephantMinutes: Int, released: Int, opened: List<String>, meaningful: List<String>, valves: Map<String, Valve> ): Int { val distance = valves[current]!!.distances[next]!! val time = minutes - distance - 1 val elephantDistance = valves[currentElephant]!!.distances[nextElephant]!! val elephantTime = elephantMinutes - elephantDistance - 1 if (time < 1 && elephantTime < 1) { return released } var nextReleased = released var nextOpened = opened if (time > 0) { nextReleased += time * valves[next]!!.flowRate nextOpened = nextOpened + next } if (elephantTime > 0) { nextReleased += elephantTime * valves[nextElephant]!!.flowRate nextOpened = nextOpened + nextElephant } if (meaningful.size == nextOpened.size) { if (nextReleased > best) { best = nextReleased println(best) } return nextReleased } else { val filtered = meaningful.filterNot { nextOpened.contains(it) } if (!canBeBetterThanBest(nextReleased, max(time, elephantTime), filtered, valves)) { return -1 } return filtered.map { i -> filtered.map { j -> if (i == j) -1 else processWithElephant( next, nextElephant, i, j, time, elephantTime, nextReleased, nextOpened, meaningful, valves ) }.maxOf { it } }.maxOf { it } } } private fun canBeBetterThanBest( nextReleased: Int, max: Int, filtered: List<String>, valves: Map<String, Valve> ): Boolean { val b = nextReleased + filtered.mapIndexed { i, label -> valves[label]!!.flowRate * (max - (2 * i)) }.sumOf { it } // println("$best : $b") return b > best } var best = 1488 private data class Next( val label: String, val time: Int, val released: Int, val alreadyReleased: MutableSet<String> = mutableSetOf() ) private fun String.toValves(): Map<String, Valve> { val regex = Regex("Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.*)") return this.split("\n") .map { regex.matchEntire(it)!!.groupValues } .map { Valve(it.get(1), it.get(2).toInt(), it.get(3).split(", ")) } .map { it.label to it } .toMap() } private data class Valve( val label: String, val flowRate: Int, val leadsTo: List<String>, var opened: Boolean = false, var distances: Map<String, Int> = emptyMap() ) private const val test = """Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II""" private const val input = """Valve QZ has flow rate=0; tunnels lead to valves IR, FA Valve FV has flow rate=0; tunnels lead to valves AA, GZ Valve GZ has flow rate=0; tunnels lead to valves FV, PO Valve QL has flow rate=0; tunnels lead to valves MR, AA Valve AA has flow rate=0; tunnels lead to valves QL, GQ, EV, FV Valve SQ has flow rate=23; tunnel leads to valve ZG Valve PK has flow rate=8; tunnels lead to valves MN, GN, WF, TY, CX Valve GQ has flow rate=0; tunnels lead to valves AA, MT Valve TI has flow rate=22; tunnels lead to valves GM, CS Valve JU has flow rate=17; tunnels lead to valves TT, RR, UJ, JY Valve YD has flow rate=7; tunnels lead to valves AT, ZS, BS Valve YB has flow rate=0; tunnels lead to valves EA, MW Valve FA has flow rate=0; tunnels lead to valves QZ, JT Valve TN has flow rate=0; tunnels lead to valves ZS, PO Valve MW has flow rate=0; tunnels lead to valves YB, YL Valve XN has flow rate=0; tunnels lead to valves VL, VM Valve MN has flow rate=0; tunnels lead to valves PK, TT Valve IP has flow rate=9; tunnels lead to valves YC, SA, CH, PI Valve PD has flow rate=0; tunnels lead to valves YZ, VM Valve ZS has flow rate=0; tunnels lead to valves TN, YD Valve PC has flow rate=0; tunnels lead to valves MR, XT Valve VM has flow rate=13; tunnels lead to valves CX, XN, PD Valve PO has flow rate=4; tunnels lead to valves GZ, TN, SA, XT, BM Valve GN has flow rate=0; tunnels lead to valves PK, YL Valve YL has flow rate=5; tunnels lead to valves MT, YZ, GN, SU, MW Valve IR has flow rate=6; tunnels lead to valves LK, PI, BM, QZ, EV Valve GM has flow rate=0; tunnels lead to valves TI, RH Valve CS has flow rate=0; tunnels lead to valves UJ, TI Valve EA has flow rate=18; tunnels lead to valves VL, YB, WF, JY Valve LK has flow rate=0; tunnels lead to valves IR, MR Valve BM has flow rate=0; tunnels lead to valves IR, PO Valve JZ has flow rate=0; tunnels lead to valves RH, RR Valve SA has flow rate=0; tunnels lead to valves IP, PO Valve XT has flow rate=0; tunnels lead to valves PO, PC Valve YC has flow rate=0; tunnels lead to valves IP, IL Valve RH has flow rate=15; tunnels lead to valves WJ, JZ, GM Valve CH has flow rate=0; tunnels lead to valves IP, BS Valve JY has flow rate=0; tunnels lead to valves EA, JU Valve TY has flow rate=0; tunnels lead to valves WJ, PK Valve WJ has flow rate=0; tunnels lead to valves TY, RH Valve IL has flow rate=0; tunnels lead to valves YC, MR Valve BS has flow rate=0; tunnels lead to valves YD, CH Valve AT has flow rate=0; tunnels lead to valves YD, UX Valve UJ has flow rate=0; tunnels lead to valves CS, JU Valve VL has flow rate=0; tunnels lead to valves EA, XN Valve JT has flow rate=21; tunnels lead to valves ZG, FA Valve UX has flow rate=10; tunnel leads to valve AT Valve RR has flow rate=0; tunnels lead to valves JZ, JU Valve TT has flow rate=0; tunnels lead to valves JU, MN Valve MT has flow rate=0; tunnels lead to valves GQ, YL Valve EV has flow rate=0; tunnels lead to valves AA, IR Valve ZG has flow rate=0; tunnels lead to valves JT, SQ Valve WF has flow rate=0; tunnels lead to valves EA, PK Valve YZ has flow rate=0; tunnels lead to valves PD, YL Valve MR has flow rate=3; tunnels lead to valves LK, IL, QL, SU, PC Valve PI has flow rate=0; tunnels lead to valves IR, IP Valve CX has flow rate=0; tunnels lead to valves VM, PK Valve SU has flow rate=0; tunnels lead to valves YL, MR"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day16Kt$recursiveSolutionWithElephant$$inlined$sortedByDescending$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class cz.wrent.advent.Day16Kt$recursiveSolutionWithElephant$$inlined$sortedByDescending$1<T> implements ja...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day9.kt
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("9a: $result") println(partTwo(test)) println(partTwo(test2)) val resultTwo = partTwo(input) println("9b: $resultTwo") } private fun partOne(input: String): Long { val commands = input.split("\n") .map { it.split(" ") } .map { it.get(0) to it.get(1).toInt() } val visited = mutableSetOf(0 to 0) var head = 0 to 0 var tail = 0 to 0 commands.forEach { command -> repeat(command.second) { head = head.moveHead(command.first) tail = tail.moveTail(head) visited.add(tail) } } return visited.size.toLong() } private fun partTwo(input: String): Long { val commands = input.split("\n") .map { it.split(" ") } .map { it.get(0) to it.get(1).toInt() } val visited = mutableSetOf(0 to 0) val knots = mutableListOf<Pair<Int, Int>>() repeat(10) { knots.add(0 to 0) } commands.forEach { command -> repeat(command.second) { knots[0] = knots.first().moveHead(command.first) for (i in 1..9) { knots[i] = knots[i].moveTail(knots[i - 1]) } visited.add(knots[9]) } } return visited.size.toLong()} private fun Pair<Int, Int>.moveHead(direction: String): Pair<Int, Int> { return when (direction) { "U" -> this.first to this.second + 1 "D" -> this.first to this.second - 1 "R" -> this.first + 1 to this.second "L" -> this.first - 1 to this.second else -> error("") } } private fun Pair<Int, Int>.toNeighboursAll(): Set<Pair<Int, Int>> { val set = mutableSetOf<Pair<Int, Int>>() for (i in this.first - 1..this.first + 1) { for (j in this.second - 1 .. this.second + 1) { set.add(i to j) } } return set } private fun Pair<Int, Int>.moveTail(head: Pair<Int, Int>): Pair<Int, Int> { if (head.toNeighboursAll().contains(this)) { return this } else if (this.first == head.first) { return this.first to if (this.second > head.second) this.second - 1 else this.second + 1 } else if (this.second == head.second) { return (if (this.first > head.first) this.first - 1 else this.first + 1) to this.second } else { return (if (this.first > head.first) this.first - 1 else this.first + 1) to if (this.second > head.second) this.second - 1 else this.second + 1 } } private const val test = """R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2""" private const val test2 = """R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20""" private const val input = """R 2 L 2 D 2 U 2 R 2 D 2 L 2 D 2 U 2 L 2 D 1 R 1 D 2 R 2 U 1 R 1 U 2 R 1 L 2 D 2 L 1 U 1 L 1 D 1 R 1 L 2 U 2 R 2 U 1 R 2 L 2 D 1 U 1 D 2 L 1 U 1 L 1 D 1 U 1 D 1 L 2 D 2 U 2 L 2 U 1 R 2 D 2 L 1 R 1 U 1 R 1 L 1 U 2 D 1 U 2 R 1 U 1 R 2 D 2 R 2 U 2 D 2 U 2 L 1 D 2 R 1 L 2 D 2 R 2 L 2 U 2 L 2 R 1 D 1 R 1 L 2 D 1 L 2 R 1 U 1 R 1 U 1 L 2 U 1 D 2 R 1 L 1 D 1 R 1 L 2 R 2 L 2 R 1 L 1 D 1 L 1 R 1 D 2 U 1 D 2 R 1 D 1 U 1 L 1 R 1 D 2 R 2 L 2 R 1 L 1 R 1 U 3 L 2 R 3 L 1 R 1 L 2 D 1 U 3 L 1 R 3 U 1 L 2 U 2 D 2 R 2 D 1 L 2 U 1 R 1 L 3 R 2 L 3 R 2 L 2 D 2 U 3 R 2 L 1 R 2 U 1 D 2 U 3 D 1 U 3 L 1 R 3 D 2 R 1 L 2 D 1 L 1 D 3 U 2 L 3 R 1 U 3 L 1 R 2 U 3 D 2 U 3 L 3 R 1 L 2 R 2 D 3 L 1 D 3 R 3 L 1 U 1 D 1 L 3 D 1 U 2 D 3 U 3 L 1 U 2 D 1 R 3 D 1 R 1 L 2 U 1 R 1 L 1 U 3 D 3 U 3 R 1 D 3 U 1 L 2 R 2 U 2 R 1 D 3 L 1 D 2 U 2 R 2 D 2 R 3 L 2 R 1 L 3 D 3 R 1 L 1 U 3 R 1 D 3 R 3 D 2 U 2 R 2 D 2 U 3 D 2 R 1 U 2 L 3 D 1 L 2 U 1 D 1 U 4 R 4 U 4 D 4 U 3 D 1 R 4 L 1 D 2 R 3 U 1 R 2 D 2 U 4 R 3 D 2 L 1 U 4 D 3 U 1 D 4 L 2 U 3 D 4 R 3 L 2 D 4 L 2 R 3 U 2 R 2 U 1 L 3 R 3 L 3 U 4 R 4 U 2 R 3 U 1 L 3 D 4 L 4 R 4 D 3 L 4 R 1 U 4 D 3 R 3 U 1 L 4 U 2 L 2 D 4 U 3 R 1 U 2 D 4 U 4 D 4 U 1 L 4 R 3 U 2 R 1 L 4 D 4 U 3 R 2 L 2 U 3 L 1 R 1 L 1 U 4 L 1 R 3 U 1 R 1 D 2 R 2 L 4 D 1 L 2 R 1 D 1 L 3 D 3 U 4 R 2 L 4 U 2 L 1 R 3 U 3 L 2 R 2 D 2 R 3 U 4 L 1 U 3 L 3 U 1 R 1 L 2 D 3 L 5 D 2 U 2 D 4 R 2 L 3 U 3 R 1 U 4 D 1 R 2 U 1 L 5 R 4 D 5 R 5 D 2 U 2 L 5 D 2 U 3 R 2 L 4 D 5 L 4 R 4 U 5 R 2 U 5 L 1 D 2 L 3 U 4 D 2 U 2 L 3 R 4 U 4 R 5 L 1 D 2 U 4 D 5 L 5 R 4 U 3 R 2 U 5 L 3 U 5 R 3 U 2 R 2 D 3 R 2 L 2 D 4 R 4 U 3 R 3 D 5 R 2 U 3 L 5 R 1 U 5 D 4 R 3 D 5 U 1 R 4 L 5 D 1 U 3 L 4 U 3 R 3 D 5 U 5 D 5 L 5 U 4 D 5 L 3 R 3 D 4 U 2 L 5 R 1 U 5 L 4 U 4 D 5 R 4 L 1 U 2 D 2 L 1 R 2 D 4 R 5 L 3 R 4 D 4 L 4 R 2 L 1 D 3 L 3 R 2 D 3 R 5 D 2 U 4 D 5 L 1 U 3 D 3 U 6 L 1 R 1 L 4 R 6 L 1 R 1 D 2 U 6 R 1 U 3 R 6 U 1 R 1 L 3 D 5 R 6 L 6 R 1 U 2 R 1 L 5 R 5 D 6 R 4 D 4 R 1 U 6 R 4 U 1 R 5 U 3 L 5 U 1 R 5 L 5 D 5 R 3 L 5 D 3 L 2 U 3 R 1 U 1 D 4 R 4 L 2 U 3 L 1 U 5 L 5 D 4 R 6 U 6 L 5 U 3 R 3 D 1 U 6 R 2 L 4 R 2 L 5 U 3 D 1 U 3 R 1 D 1 L 3 U 6 L 5 U 2 L 3 D 1 L 3 U 6 L 4 D 3 R 4 D 1 L 4 U 1 R 6 D 6 R 5 D 4 R 4 D 4 U 6 D 4 L 3 R 4 L 5 R 1 D 6 U 6 D 2 R 1 L 6 U 6 L 5 D 6 U 4 R 4 D 3 U 5 D 6 U 7 L 5 U 7 R 6 U 1 L 6 U 1 R 2 D 7 R 4 U 1 R 6 L 6 D 4 L 4 U 4 R 1 D 7 L 7 D 7 L 5 D 1 L 1 U 2 R 5 D 5 L 3 U 5 D 6 L 4 R 1 U 6 L 3 D 6 L 7 D 6 R 3 U 7 R 1 D 6 R 3 U 7 D 5 U 1 L 4 U 3 D 3 U 3 R 1 L 2 R 2 L 1 U 3 D 5 U 7 D 1 U 7 L 4 D 3 U 4 R 6 D 2 L 5 R 7 L 5 R 1 U 6 R 7 U 4 D 3 U 1 L 1 D 1 U 6 L 1 U 1 R 7 L 4 D 1 U 2 R 7 L 7 R 5 U 4 R 2 L 7 U 6 R 5 L 1 R 3 U 7 D 7 L 4 R 1 U 4 R 1 L 7 D 4 L 5 D 7 U 4 L 5 R 6 U 1 L 4 R 6 D 2 L 1 D 2 U 4 L 5 U 5 D 4 U 7 L 2 D 3 U 5 R 7 D 1 R 7 D 6 U 4 R 3 D 5 U 5 D 8 R 7 L 7 R 1 D 5 L 3 R 1 U 3 R 6 D 5 R 6 L 5 D 7 L 5 R 2 D 1 R 7 L 1 D 3 R 8 L 5 U 8 R 6 U 4 D 2 U 4 D 5 U 7 D 5 U 2 D 3 U 1 R 4 L 2 R 4 U 7 R 8 D 2 U 3 R 7 D 2 U 1 D 6 R 4 L 4 R 3 D 8 R 8 U 7 L 3 U 7 D 1 U 6 R 8 L 1 R 1 D 8 U 7 L 3 D 4 L 4 R 2 L 6 D 6 L 4 R 7 D 8 L 8 U 8 R 2 L 6 U 5 D 2 L 5 U 1 L 6 D 6 U 7 L 2 U 5 R 6 D 5 L 8 U 8 R 1 U 2 L 3 D 1 L 3 U 4 D 3 L 6 R 9 L 9 U 9 R 1 D 4 U 1 L 3 R 7 U 7 R 1 U 1 R 2 D 4 U 8 L 7 R 3 U 8 L 1 R 1 D 7 U 3 L 3 U 8 D 3 L 1 D 6 L 3 U 4 D 3 U 3 L 3 D 5 L 6 U 9 L 1 U 2 L 3 R 1 L 9 D 2 U 1 L 3 R 9 L 8 R 2 L 7 D 4 L 4 R 2 L 4 R 8 D 4 L 2 D 5 R 8 U 6 L 9 D 1 L 6 R 9 D 4 L 5 U 5 D 1 U 3 L 4 U 2 L 2 R 2 L 1 R 7 L 4 D 4 U 4 L 1 R 2 D 6 L 1 U 8 D 7 R 5 D 7 R 7 L 8 U 8 L 5 D 7 U 2 D 2 R 1 U 2 L 1 R 1 L 2 D 1 U 9 L 9 U 9 R 1 U 3 R 7 U 8 R 1 L 7 D 1 U 7 R 9 D 8 R 2 D 5 L 5 D 2 L 6 U 6 R 1 L 1 D 2 R 4 L 3 U 2 R 5 L 3 R 6 U 8 R 1 U 1 R 7 D 10 R 2 D 4 R 3 L 5 D 1 U 8 R 1 U 4 D 6 L 5 U 8 D 6 L 6 R 4 L 9 R 5 U 6 L 8 U 6 L 10 D 4 U 6 L 8 U 3 R 3 L 6 U 1 R 9 D 8 U 9 R 5 U 10 R 8 U 9 L 7 R 4 D 7 U 3 L 5 R 3 D 9 L 9 U 6 R 10 L 2 D 7 U 8 D 4 L 3 U 4 R 2 L 10 D 4 U 10 R 7 D 5 R 7 U 3 L 10 R 8 L 7 D 3 L 6 R 1 L 2 U 1 R 1 U 8 R 5 L 9 R 9 L 1 D 4 R 6 U 7 L 7 R 3 U 4 D 2 U 8 L 5 D 3 L 6 D 7 L 2 U 1 R 6 L 8 D 9 R 3 U 4 D 8 L 5 R 9 L 1 U 7 L 5 D 4 U 5 L 4 R 4 L 3 U 11 D 1 L 10 U 6 L 5 D 3 U 8 D 11 L 8 R 2 U 5 L 9 D 3 L 11 R 2 U 5 L 7 D 11 R 8 U 1 L 10 R 10 L 9 R 9 L 8 R 7 D 3 U 6 R 11 U 8 D 4 L 9 U 3 D 5 L 4 R 5 D 7 L 5 U 10 D 8 L 3 D 2 U 9 D 6 L 3 U 3 D 8 U 4 R 1 L 9 U 4 L 5 D 10 L 11 U 6 D 8 L 5 R 9 L 2 U 2 L 10 R 5 U 6 L 7 R 7 U 9 D 6 R 7 D 8 U 7 R 6 L 2 D 6 R 8 L 5 R 1 L 10 R 8 U 11 R 10 L 10 R 10 L 4 U 4 D 9 U 8 R 5 D 7 U 7 L 6 D 4 L 9 R 2 U 8 D 2 L 2 D 2 U 6 L 2 R 9 U 10 D 11 U 3 R 9 U 1 L 11 R 7 L 4 R 5 U 10 L 3 R 10 L 10 D 2 L 9 D 9 L 6 D 11 R 10 L 2 R 4 D 2 R 4 D 8 L 3 U 10 R 4 L 2 U 1 L 3 R 1 L 2 R 3 D 2 L 2 D 3 R 5 U 10 L 12 R 5 D 5 U 9 L 9 D 2 L 8 U 2 L 11 U 5 L 8 U 7 R 4 U 10 D 4 L 5 R 3 D 8 R 12 L 5 U 9 L 10 R 5 U 10 R 1 L 5 U 6 D 7 L 12 D 2 R 12 L 1 U 11 D 8 R 12 L 8 U 3 R 9 L 8 D 2 L 10 D 10 R 4 D 2 R 11 U 4 R 10 U 7 L 7 D 5 U 5 R 9 D 10 L 10 U 1 D 11 U 4 D 5 U 5 D 8 U 2 D 4 R 4 L 5 U 10 D 12 R 9 L 11 R 9 L 1 D 9 L 11 D 12 U 4 R 7 D 1 U 3 L 4 U 9 R 12 D 1 L 7 U 7 D 6 U 1 R 3 L 7 U 5 L 2 D 10 R 12 L 3 U 7 D 10 L 5 R 1 U 9 L 1 D 11 R 5 L 2 D 1 U 3 R 2 L 3 U 5 L 3 D 5 R 10 L 7 R 12 U 4 D 3 R 3 L 2 R 7 U 4 D 9 U 7 D 1 R 9 L 2 U 6 R 5 D 3 U 7 R 12 L 10 D 11 L 8 U 12 D 13 U 9 D 5 U 4 R 2 L 3 U 13 R 4 L 9 U 4 L 3 U 9 R 1 D 6 U 4 D 3 U 5 R 5 L 11 R 8 D 1 U 4 D 10 R 5 D 10 U 3 D 4 R 1 U 3 R 13 L 6 D 8 R 12 L 4 U 2 L 13 D 11 L 4 U 8 L 10 R 2 D 8 R 11 L 2 D 8 R 8 L 10 U 10 L 4 D 9 L 7 D 11 L 10 U 13 L 6 U 7 D 8 L 3 R 10 L 14 U 13 L 11 D 5 R 8 U 2 D 9 L 14 U 7 R 4 U 1 D 8 U 8 D 9 L 2 D 7 R 1 D 9 R 2 U 4 D 8 L 9 R 6 L 2 R 11 D 6 L 5 U 8 L 4 R 3 D 5 L 3 U 9 R 3 U 1 D 7 R 1 L 10 U 1 L 8 U 11 D 8 U 12 R 9 L 5 D 10 L 2 R 8 D 10 R 6 D 1 L 11 D 8 R 7 L 14 D 12 L 11 R 11 U 9 R 12 D 10 L 12 R 4 L 8 D 2 R 3 L 14 R 7 U 10 R 1 L 6 R 4 D 11 L 13 R 12 U 4 L 12 U 10 D 8 R 10 D 9 R 13 L 2 U 2 D 7 U 7 R 3 D 3 R 13 U 8 R 10 U 13 D 14 R 11 D 7 R 2 U 5 D 2 L 6 U 14 L 10 R 9 U 11 R 12 D 5 L 11 R 12 U 11 R 8 L 2 D 14 U 3 D 9 U 5 L 4 U 5 L 6 D 3 L 1 R 10 L 4 D 12 U 15 L 5 D 11 L 15 D 10 L 14 U 1 L 14 D 6 R 6 U 9 R 1 L 7 D 11 U 12 D 2 R 7 L 2 D 13 U 13 R 6 L 3 D 3 R 11 U 3 D 3 U 11 L 10 U 7 R 7 D 9 U 10 R 11 U 12 D 11 R 11 U 2 R 2 D 9 R 12 D 1 L 11 R 1 U 2 R 14 L 4 R 1 D 12 R 7 U 12 L 2 U 5 D 7 R 15 D 5 L 9 D 7 R 10 U 12 D 10 R 11 D 5 U 10 R 2 U 11 R 3 U 6 D 14 U 11 D 5 L 8 D 6 L 2 U 2 L 14 R 8 U 15 L 10 D 1 R 4 L 8 D 7 L 15 U 10 D 14 U 9 L 7 R 13 U 11 R 15 L 11 R 2 L 11 R 14 L 1 D 10 L 2 U 7 L 9 D 12 R 2 L 4 U 4 R 9 L 6 R 13 D 1 U 13 R 7 D 3 R 14 L 12 D 15 R 16 L 7 R 2 U 3 R 9 U 10 D 6 U 7 L 11 D 12 L 16 R 12 D 10 U 16 D 9 U 14 L 14 U 11 D 14 L 14 D 10 L 3 D 10 U 6 D 11 L 8 U 4 D 1 U 5 D 5 L 4 U 8 R 3 D 12 U 4 R 8 D 6 U 8 D 2 U 12 L 6 D 12 R 7 D 6 U 7 D 12 L 3 R 2 L 12 R 13 U 16 L 6 D 8 U 13 R 14 D 4 U 7 D 1 R 4 D 13 R 10 D 7 R 11 L 6 U 6 R 7 L 8 D 2 L 11 U 3 L 12 U 4 D 11 U 8 D 10 U 1 R 12 U 1 L 15 R 15 D 2 L 8 D 13 L 3 R 8 U 14 R 5 U 3 D 15 U 7 D 1 L 6 D 8 U 13 R 6 L 6 D 3 L 9 D 17 U 8 R 16 L 6 D 9 U 3 L 10 R 13 L 14 U 8 R 7 U 12 D 14 R 1 D 3 L 11 R 8 D 9 R 17 D 5 R 17 U 8 L 10 D 7 U 4 D 16 L 9 D 1 L 16 R 7 L 1 R 11 U 10 R 2 U 10 L 15 U 10 R 2 D 11 U 12 L 15 U 4 D 2 R 4 U 2 L 11 R 16 U 10 R 4 D 9 U 7 D 2 R 10 D 14 L 10 U 9 R 7 D 3 R 7 L 3 U 15 D 13 L 17 R 12 U 13 D 16 U 13 R 13 U 14 L 16 U 7 D 2 R 11 U 17 D 9 R 12 U 16 L 11 R 3 U 9 L 6 D 2 U 1 D 7 L 1 U 7 D 8 U 11 L 4 R 6 L 2 U 12 L 13 U 5 L 17 R 16 D 10 U 12 L 7 R 4 U 8 D 17 R 13 L 2 D 5 L 1 R 2 D 16 U 9 D 15 L 8 U 14 R 9 D 18 U 16 L 17 U 9 D 11 U 17 R 8 D 17 U 14 D 8 U 8 R 8 U 14 R 5 L 1 R 3 D 5 U 10 R 16 U 18 D 16 U 11 D 18 U 13 L 11 D 2 R 16 D 15 L 9 D 12 R 11 L 8 U 8 R 10 L 2 D 6 L 5 D 9 L 3 D 1 U 18 D 12 U 13 L 6 R 17 D 10 R 9 L 6 R 3 U 1 R 1 U 6 L 15 U 8 D 15 U 14 R 10 L 6 U 1 L 12 R 9 D 13 U 1 L 16 U 16 L 13 R 4 U 3 D 11 L 12 R 11 U 17 R 18 L 4 R 6 L 18 D 10 L 16 R 2 D 4 R 14 D 11 L 12 R 7 L 9 U 12 D 12 R 4 L 1 D 14 R 14 L 3 U 2 L 6 R 7 D 6 U 18 L 17 U 12 R 12 L 5 D 13 R 7 D 8 L 16 D 13 U 4 D 3 R 16 L 9 U 8 D 15 R 8 L 12 R 5 L 1 U 11 D 11 L 10 U 7 D 6 L 15 D 9 R 10 D 6 U 14 L 7 U 19 R 17 L 12 U 1 L 9 R 17 D 12 U 3 L 15 R 16 D 15 R 15 L 1 U 16 R 19 D 9 L 16 D 12 R 8 L 2 D 16 L 17 U 16 D 9 L 9 U 8 L 9 R 16 L 3 D 8 U 7 D 10 U 17 R 2 D 16 R 6 U 9 R 4 L 17 D 10 U 10 L 14 D 9 R 8 L 9 R 18 U 13 L 16 R 2 U 16 L 11 U 4 L 13 R 8 L 19 U 4 D 10 R 10 U 14 R 13 L 17 U 17 R 12 D 18 R 2 D 5 L 12 U 6 D 7 R 9 L 13 D 15 R 9 U 16 D 14 R 8 L 8 U 10 L 8 D 18 U 8 D 9 L 6 R 8 U 4 D 14 L 13 D 4 R 3 U 13 L 2"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day9Kt.class", "javap": "Compiled from \"Day9.kt\"\npublic final class cz.wrent.advent.Day9Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String test2;\n\n private static final java.lang.String inp...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day14.kt
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("14a: $result") println(partTwo(test)) println("14b: ${partTwo(input)}") } private fun partOne(input: String): Int { return simulate(input, withFloor = false) } private fun simulate(input: String, withFloor: Boolean): Int { val map = input.split("\n").map { it.toShape() }.flatten().map { it to Material.ROCK }.toMap().toMutableMap() val cave = if (withFloor) CaveWithFloor(map) else Cave(map) var i = 0 try { while (true) { cave.sandfall() i++ if (cave.map[500 to 0] == Material.SAND) { return i } } } catch (e: EndlessFallException) { println("Finished") } return i } private fun partTwo(input: String): Int { return simulate(input, withFloor = true) } private open class Cave(val map: MutableMap<Pair<Int, Int>, Material>) { fun add(coord: Pair<Int, Int>, material: Material) { map[coord] = material } fun sandfall() { val next = this.fall(500 to 0) add(next, Material.SAND) } fun fall(from: Pair<Int, Int>): Pair<Int, Int> { val bellow = findBellow(from) return if (get(bellow.first - 1 to bellow.second) == null) { this.fall(bellow.first - 1 to bellow.second) } else if (get(bellow.first + 1 to bellow.second) == null) { this.fall(bellow.first + 1 to bellow.second) } else { bellow.first to bellow.second - 1 } } open fun get(coord: Pair<Int, Int>): Material? { return map[coord] } open fun findBellow(from: Pair<Int, Int>): Pair<Int, Int> { return this.map.entries.filter { it.key.first == from.first }.filter { it.key.second > from.second } .minByOrNull { it.key.second }?.key ?: throw EndlessFallException() } } private class CaveWithFloor(map: MutableMap<Pair<Int, Int>, Material>) : Cave(map) { val floorY = map.keys.maxByOrNull { it.second }!!.second + 2 override fun get(coord: Pair<Int, Int>): Material? { return if (coord.second == floorY) return Material.ROCK else super.get(coord) } override fun findBellow(from: Pair<Int, Int>): Pair<Int, Int> { return try { super.findBellow(from) } catch (e: EndlessFallException) { from.first to floorY } } } private class EndlessFallException() : Exception() private enum class Material { ROCK, SAND, } private fun String.toShape(): Set<Pair<Int, Int>> { val set = mutableSetOf<Pair<Int, Int>>() val points = this.split(" -> ").map { it.split(",") }.map { it.first().toInt() to it.get(1).toInt() } points.windowed(2).forEach { (first, second) -> var current = first if (first.first == second.first) { while (current != second) { set.add(current) val diff = if (current.second < second.second) 1 else (-1) current = current.first to current.second + diff } } else { while (current != second) { set.add(current) val diff = if (current.first < second.first) 1 else (-1) current = current.first + diff to current.second } } set.add(second) } return set } private const val test = """498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9""" private const val input = """503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 545,125 -> 549,125 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 558,119 -> 563,119 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,131 -> 543,131 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 526,82 -> 530,82 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 548,122 -> 553,122 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 523,84 -> 527,84 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 551,119 -> 556,119 529,84 -> 533,84 505,62 -> 509,62 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 526,86 -> 530,86 548,128 -> 552,128 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 523,88 -> 527,88 551,131 -> 555,131 541,122 -> 546,122 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 517,88 -> 521,88 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 562,122 -> 567,122 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 532,82 -> 536,82 505,58 -> 509,58 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 502,60 -> 506,60 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 535,88 -> 539,88 554,134 -> 558,134 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 508,56 -> 512,56 540,91 -> 540,92 -> 547,92 -> 547,91 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 540,91 -> 540,92 -> 547,92 -> 547,91 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 499,62 -> 503,62 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 548,134 -> 552,134 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 542,134 -> 546,134 518,76 -> 518,77 -> 530,77 -> 530,76 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 544,119 -> 549,119 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 493,15 -> 493,16 -> 504,16 -> 504,15 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 542,128 -> 546,128 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 540,91 -> 540,92 -> 547,92 -> 547,91 511,58 -> 515,58 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 538,86 -> 542,86 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 508,60 -> 512,60 517,62 -> 521,62 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 518,76 -> 518,77 -> 530,77 -> 530,76 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 493,15 -> 493,16 -> 504,16 -> 504,15 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 547,116 -> 552,116 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 518,76 -> 518,77 -> 530,77 -> 530,76 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 541,88 -> 545,88 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 555,122 -> 560,122 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 532,86 -> 536,86 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 550,113 -> 555,113 554,116 -> 559,116 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 514,60 -> 518,60 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 535,84 -> 539,84 521,65 -> 521,67 -> 513,67 -> 513,72 -> 526,72 -> 526,67 -> 523,67 -> 523,65 511,62 -> 515,62 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 529,80 -> 533,80 545,131 -> 549,131 503,53 -> 503,50 -> 503,53 -> 505,53 -> 505,51 -> 505,53 -> 507,53 -> 507,52 -> 507,53 -> 509,53 -> 509,50 -> 509,53 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 504,19 -> 504,23 -> 503,23 -> 503,31 -> 512,31 -> 512,23 -> 507,23 -> 507,19 539,150 -> 539,152 -> 534,152 -> 534,159 -> 544,159 -> 544,152 -> 543,152 -> 543,150 536,172 -> 536,168 -> 536,172 -> 538,172 -> 538,164 -> 538,172 -> 540,172 -> 540,168 -> 540,172 -> 542,172 -> 542,163 -> 542,172 -> 544,172 -> 544,164 -> 544,172 -> 546,172 -> 546,171 -> 546,172 -> 548,172 -> 548,165 -> 548,172 -> 550,172 -> 550,170 -> 550,172 -> 552,172 -> 552,170 -> 552,172 554,110 -> 563,110 539,105 -> 539,98 -> 539,105 -> 541,105 -> 541,100 -> 541,105 -> 543,105 -> 543,103 -> 543,105 -> 545,105 -> 545,101 -> 545,105 -> 547,105 -> 547,95 -> 547,105 -> 549,105 -> 549,104 -> 549,105 -> 551,105 -> 551,99 -> 551,105 -> 553,105 -> 553,97 -> 553,105 -> 555,105 -> 555,96 -> 555,105 493,15 -> 493,16 -> 504,16 -> 504,15 529,88 -> 533,88 527,147 -> 527,139 -> 527,147 -> 529,147 -> 529,142 -> 529,147 -> 531,147 -> 531,138 -> 531,147 -> 533,147 -> 533,137 -> 533,147 -> 535,147 -> 535,140 -> 535,147 -> 537,147 -> 537,146 -> 537,147 -> 539,147 -> 539,142 -> 539,147 -> 541,147 -> 541,140 -> 541,147 536,134 -> 540,134 500,34 -> 500,37 -> 496,37 -> 496,40 -> 506,40 -> 506,37 -> 504,37 -> 504,34 520,86 -> 524,86"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day14Kt.class", "javap": "Compiled from \"Day14.kt\"\npublic final class cz.wrent.advent.Day14Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n ...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day8.kt
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("8a: $result") println(partTwo(test)) val resultTwo = partTwo(input) println("8b: $resultTwo") } private fun partOne(input: String): Long { val map = input.parse() val visible = mutableSetOf<Pair<Int, Int>>() processDirectionFromZero(map, visible) processDirectionFromZero(map, visible, true) processDirectionToZero(map, visible) processDirectionToZero(map, visible, true) return visible.size.toLong() } private fun partTwo(input: String): Long { val map = input.parse() val scenicMap = map.map { it.key to getScenicScore(it.key, map) }.toMap() println(scenicMap) return scenicMap.values.maxByOrNull { it }!!.toLong() } private fun getScenicScore(coord: Pair<Int, Int>, map: Map<Pair<Int, Int>, Int>): Int { val current = map[coord]!! val a = map.getRightFrom(coord).getVisible(current) val b = map.getLeftFrom(coord).getVisible(current) val c = map.getUpFrom(coord).getVisible(current) val d = map.getDownFrom(coord).getVisible(current) return a * b * c * d } private fun List<Int>.getVisible(current: Int): Int { val res = this.takeWhile{ it < current }.size if (res == this.size) { return res } else { return res + 1 } } private fun Map<Pair<Int, Int>, Int>.getRightFrom(coord: Pair<Int, Int>): List<Int> { return this.filter { it.key.second == coord.second } .filter { it.key.first > coord.first }.entries.sortedBy { it.key.first }.map { it.value }.toList() } private fun Map<Pair<Int, Int>, Int>.getLeftFrom(coord: Pair<Int, Int>): List<Int> { return this.filter { it.key.second == coord.second } .filter { it.key.first < coord.first }.entries.sortedByDescending { it.key.first }.map { it.value }.toList() } private fun Map<Pair<Int, Int>, Int>.getUpFrom(coord: Pair<Int, Int>): List<Int> { return this.filter { it.key.first == coord.first } .filter { it.key.second < coord.second }.entries.sortedByDescending { it.key.second }.map { it.value }.toList() } private fun Map<Pair<Int, Int>, Int>.getDownFrom(coord: Pair<Int, Int>): List<Int> { return this.filter { it.key.first == coord.first } .filter { it.key.second > coord.second }.entries.sortedBy { it.key.second }.map { it.value }.toList() } private fun processDirectionFromZero( map: Map<Pair<Int, Int>, Int>, visible: MutableSet<Pair<Int, Int>>, switch: Boolean = false ) { val max = map.keys.maxByOrNull { it.first }!!.first var i = 0 var j = 0 var localMax = -1 while (j <= max) { while (i <= max) { val coord = if (switch) j to i else i to j val current = map[coord] ?: break if (current > localMax) { visible.add(coord) localMax = current } i++ } localMax = -1 i = 0 j++ } } private fun processDirectionToZero( map: Map<Pair<Int, Int>, Int>, visible: MutableSet<Pair<Int, Int>>, switch: Boolean = false ) { val max = map.keys.maxByOrNull { it.first }!!.first var i = max var j = max var localMax = -1 while (j >= 0) { while (i >= 0) { val coord = if (switch) j to i else i to j val current = map[coord] ?: break if (current > localMax) { visible.add(coord) localMax = current } i-- } localMax = -1 i = max j-- } } private fun String.parse(): Map<Pair<Int, Int>, Int> { val map = mutableMapOf<Pair<Int, Int>, Int>() this.split("\n") .mapIndexed { i, row -> row.split("").filter { it.isNotEmpty() }.forEachIndexed { j, value -> map.put(j to i, value.toInt()) } } return map } private const val test = """30373 25512 65332 33549 35390""" private const val input = """003112220410413101104044022234320204233341435252223642044225451531421012104343030211442433410302111 301233004003313130222434121135033231250505241131342032404032560542233000343455552123100410402211201 111301041221333142533352050250154136146324550411565615444115604102531135302000320033233340431313123 011312210420442043155233305201305643445224334303310253225205601265233454400214114322131420224022313 130102441231200141254202121022423405224443210463250415204410624313613034320040015223211432442333110 133121132322223054104323242043651144066341346000104210124535555236324451132555525220523220023202433 110011123024113203143145243605143331512223606564503661350336662505131254503242354031400131012444222 221400422202335053520044325014041432662161415523526711633662600635304000112322014001533351130303321 030222020044115331004065013253364503664435753416641653716424535324654054023321025154331103034342414 030331241153233040140314112524504535172167445223426653152774166352145410064425434012002122431142343 224111232453145423354550035141103644127571711431336236226321752314754510214316215104550522141301020 424321022432003551434012134531644165753146143232242275633762323631713541330463531053004424012234010 221233440041435131321565604060121637542135243721227576264551457171313165211546132314103242442012133 301320232222024200651041405631257577625236256225367443317773421262762172454463051224654015452230401 124314451244222611016300517414362722551374735555353871173242751564427674344212032442221554524035432 000210412345203005364660077252742673773341654558568632445755573574757433452636410261362004114032013 333130514223252440150314572132443233363783556666363566733363262631651361523573335361463232143300044 400403124212626240015541437753711632635435857234865883574647337436376563235264524230225211320425534 430312520241033613150127256341412352564548243842255622454762832274857163157242366022041262252034150 125211521340246341461723355443362487532437274863758283488567453538667642367654751321503343220351304 015045453331430626273664314125778234645658386774837783464366334264476243327176571544650404453253132 354034323663213666746174754737374552772744668787244468236435632534753452366177147233020313054042345 305241054630156250416544221136444247327848337737584777837244467756426322644474332262330430251551212 100144030632532041231474166555527386344645548655948476835366757558682728623657547471260405014131510 155501551351164622444476154658383338677369856795967346765977585753438378656352723127554031451225340 213252046404053134327512554784653544697439375473948735593644477348334755453317243676612665133404310 022440140420166534174335264388542568833984445757393864997986883894574577853347367415453352646352541 303425632364032563633467847288735478557676734393879573848466463466672455482853676764477400452414425 421140260266576264621526686828328833799894373434775335763857585383998562862724435337211515426106224 251234063153345361761483764445395779384568938899876568577359785776678952473247274437226445141011143 124165362100637756715727365876646574835535677777467785479666667584536895483528343623556220650044411 523533116461715454347526758528694839737349689796485884675949699354664766465728468324363766204426020 011655232111314171647378426863359767797699886798595874554677869353593448485338287251255363024600501 201454444103773472628888556987787587788889498545597569965587748496753787964648276727241677205552530 022050015673621733475438774338498584975649879876857968775687577968447843939528275674512475556245535 415145246426622536566872225778388854879897849855475687687595454675468637795674534385355242230005213 515410462156777244275234668693874665788796767699675757959578987749863457937753862877526274731341533 532441044352764132482273798897585496755464759898898996955476545867443535986538526852746625533463346 042116466642255478273735578633656564997786577695957789988869999965866866547392358543326526744105124 305463642721567264236826357995536786844968968785757997557699474697669835738584868845834527260231552 066231251534151145564875937345768799895756579656987695996797768779596848379994862646436522463360266 506513057363414584637639439854956668854878865987777598756576697549657897644947484484534264535522136 131666244551736787837659743739478747677995596779697659755568679946768553647438363837764527562663652 424404413335566473356634745356959967996577965786978695878778775749964899347635788855331715645156443 366410447316422733452686338845457787759555776998978979667795556665499755678449775626855353212651324 302136251253517685366593955978666557656668675898896669776695986549696689467499828826265743355612425 546506521534743584874443398869667685788797956777788696997955989646664668879679457843885333126334344 362262154313747445367249673496655464765879658679769897687679766789496785648597346877862642316202103 026226125354532563527338467655476495659657769687899897897899856576869585587683926347427571714351012 324246031677535478765836973778855888768885696676889798687785885666785975868394627754287365751563132 031351623136767474878299634934847976977866799698978866969865695657475657893553946224747277645245120 026056143144572747422538333594694756756655696798979976879958687957995676939686658475475623336500612 662533125413523284737634669357979456995895856799797767679899585888899799675553357648455413641663031 014206153225663545455694774965848955686699676678777689996997596965668976646983688667633463335404141 413012617325174456878669973969459678955956597997687976869576778966464554568469886777721516427616513 502662203642612255238447486939957458967857897679766997696655868558575999589335922456844736112131654 212661502516734223324889447354689969855787756889968698877896757975877697383989627364337421772343024 062105566125733258245733457473775547779958796868868895787767755559647545379345865238624356123242000 402335614754636628236824679555597465548989986755969565969678898559987586856955673832271674166105362 451334645753376162243335579543677879955598768556565759756869877876795947966569855573232735534601241 500262052615557247375888358635954578969966856685689678868986899965887995757987425824514566556143415 025221464647151347477323745438738647477798995699788989796688598687779795846437577837865212462025305 506261641542645445623578634938859695857548567987658895685668887664467397754563764284864222243613255 544001251632514343434242438697698767785468785559797877757559476976744589553445545348132556324315401 312662335054751647576346847944998349986995969646958568675577475645539379875732364426714676752004534 442336642122316123757636234859863735657746598877646757975758669549947438746824526434264347133600103 110222605363451462773826376864836593598856459788567868745977445869448964569655348846536363204056350 000101232124176476234372634789857987399659768658796566947966644948468844584756623732364133065443412 134465433226374477324823357757785535937975665949586889647565456766846389552458234767667646466124353 421406224300535763513347544755878674693949665984559799965894778876384773264625738631365460212615513 452351220036426717772576544574486575445936589965659469684553983864958887588836456352652752044465624 513131310021516677236857346343788436737376979889979498674877368855367664436225742117611411543534241 025341550553445563557374338552585545787433393754685485676457956894674542662544752536711135543323540 535152616216423251726174753447757785566344854848638858756838495369785886445488572266324260520452211 040010242452167571763413223445374499838658479769797468459895353937866635767567612446231533425561512 540233435611063354343623584674548775576735445736954663985773597646587532834332126771664204465150223 115125460640513624264577427672484376565394997956949478368583668555354324253116433334364541633501141 325235035031330065764773672233563447278366899833655673943396323666327273534372213517324021336301134 210455052102126060367721574443448283734742249765698995536842573866568587565571317173455040136014133 130303041444343616551636147765524538863657233824485633222587838375574238775244261440413305250410213 215411311040450233266672334763832288583822422248882386376826865647256855122326112462046245434214110 230231555011111141243461222762213386584878775753548542777758687642766773174237314624160241043301041 323544455001621231632772663352437368846236258422868628887825466644733647626344222306513541033345051 103143140115330535101443674523313247636278477357763543634765673375252223123145511514215131041302240 232425305344242122243634141575125456216884578682284677823883878251534364736772005201664151453532422 102015414143426060302001452111353522415644252842283555326642135161755673127454553246636405351210230 434225550123100466121402111553624464277266354226553673463535217337233242261322143516321221202244233 241043514014314144343662453056766274716234347315115145214653247673432611160552306341450310405413111 242112143335044304622645260260424573275613637141734623226773527441742321265241643455134145215344111 111301110035433343532532505066367716542154757534155161173124736561116131435620565213531350550432142 242323242143224035106205224411500635634124323342513747342475634262646442514656422055112331122023144 002021344233114150010341663531513334522142253265466242366366534525551142525131661102314124401314042 024004104024242151413420354625126365606642452553232242411563750634302214411623615524332515123123121 322320201030004104054100060453523451362415465573527326430616603635233444523531105134335533102202414 013231044323002420215041311645066036204353535300445225661352044506065120312154410321400034312200320 031030413344440552442114452066553136026033443442226333515665300213012326102141034413121232242040400 133131302014414220215344004521556454235620502443013233464014064103264525100404050140223431001414000 221120341111243124154321401255010441026151433422443520262166251632146441120442553301443334201231200 021222222103332103301112520131442023663055232552042262505152050120510455441325453404132240001402111"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day8Kt.class", "javap": "Compiled from \"Day8.kt\"\npublic final class cz.wrent.advent.Day8Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n Cod...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day15.kt
package cz.wrent.advent import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { println(partOne(test, 10)) val result = partOne(input, 2000000) println("15a: $result") println(partTwo(test, 20)) println("15b: ${partTwo(input, 4000000)}") } private fun partOne(input: String, row: Int): Int { val map = input.parse() val sensors = map.flatMap { r -> r.value.filter { it.value > 0 }.map { (it.key to r.key) to it.value } } val beacons = map.flatMap { r -> r.value.filter { it.value == BEACON }.map { it.key to r.key } }.toSet() val set = mutableSetOf<Pair<Int, Int>>() sensors.forEach { (coord, dist) -> set.addAll(getCleared(coord, dist, row)) } set.removeAll(beacons) return set.size } private fun partTwo(input: String, limit: Int): Long { val map = input.parse() val sensors = map.flatMap { r -> r.value.filter { it.value > 0 }.map { (it.key to r.key) to it.value } } for (i in 0..limit) { val notCleared = sensors.map { (coord, dist) -> getCleared(coord, dist, i, limit) }.getNotCleared() if (notCleared != null) { return notCleared.toLong() * 4000000 + i.toLong() } } return -1 } private fun getCleared(coord: Pair<Int, Int>, dist: Int, row: Int): Set<Pair<Int, Int>> { val distToRow = abs(coord.second - row) val remainingDist = dist - distToRow return (coord.first - remainingDist..coord.first + remainingDist).map { it to row }.toSet() } private fun getCleared(coord: Pair<Int, Int>, dist: Int, row: Int, limit: Int): IntRange { val distToRow = abs(coord.second - row) val remainingDist = dist - distToRow if (remainingDist < 0) { return IntRange.EMPTY } return (max(0, coord.first - remainingDist)..min(coord.first + remainingDist, limit)) } private fun List<IntRange>.getNotCleared(): Int? { val sorted = this.sortedBy { it.start } var current = sorted.first() sorted.drop(1).forEach { if (!current.contains(it.start)) { return it.start - 1 } if (it.endInclusive > current.endInclusive) { current = current.start .. it.endInclusive } } return null } //private fun getNotCleared(coord: Pair<Int, Int>, dist: Int, row: Int, max: Int): List<IntRange> { // val distToRow = abs(coord.second - row) // val remainingDist = dist - distToRow // return listOf(0 until coord.first - remainingDist, coord.first + remainingDist until max) // todo ta nula tam asi hapruje //} //private fun Map<Int, Map<Int, Int>>.fill(): Map<Int, Map<Int, Int>> { // val clear = mutableMapOf<Int, MutableMap<Int, Int>>() // this.forEach { (y, row) -> // row.forEach { (x, value) -> // if (value > 0) { // addAllClears(x to y, value, clear) // } // } // } // this.forEach { (y, row) -> // row.forEach { (x, value) -> // clear.computeIfAbsent(y) { mutableMapOf() }[x] = value // } // } // return clear //} // //private fun addAllClears(from: Pair<Int, Int>, value: Int, to: MutableMap<Int, MutableMap<Int, Int>>) { // val remaining: Deque<Pair<Pair<Int, Int>, Int>> = LinkedList(listOf(from to 0)) // while (remaining.isNotEmpty()) { // val curr = remaining.pop() // val coord = curr.first // val next = curr.second // if (next <= value) { // to.computeIfAbsent(coord.second) { mutableMapOf() }[coord.first] = CLEAR // curr.first.toNeighbours().map { it to next + 1 } // .forEach { // remaining.push(it) // } // } // } //} private fun String.parse(): Map<Int, Map<Int, Int>> { val map = mutableMapOf<Int, MutableMap<Int, Int>>() val regex = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") this.split("\n") .map { regex.matchEntire(it) } .filterNotNull() .map { it.groupValues } .forEach { val beacon = it.get(3).toInt() to it.get(4).toInt() val sensor = it.get(1).toInt() to it.get(2).toInt() map.computeIfAbsent(sensor.second) { mutableMapOf() }[sensor.first] = dist(sensor, beacon) map.computeIfAbsent(beacon.second) { mutableMapOf() }[beacon.first] = BEACON } return map } private fun dist(a: Pair<Int, Int>, b: Pair<Int, Int>): Int { return abs(a.first - b.first) + abs(a.second - b.second) } private const val BEACON = -1 private const val CLEAR = 0 private const val test = """Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3""" private const val input = """Sensor at x=3844106, y=3888618: closest beacon is at x=3225436, y=4052707 Sensor at x=1380352, y=1857923: closest beacon is at x=10411, y=2000000 Sensor at x=272, y=1998931: closest beacon is at x=10411, y=2000000 Sensor at x=2119959, y=184595: closest beacon is at x=2039500, y=-250317 Sensor at x=1675775, y=2817868: closest beacon is at x=2307516, y=3313037 Sensor at x=2628344, y=2174105: closest beacon is at x=3166783, y=2549046 Sensor at x=2919046, y=3736158: closest beacon is at x=3145593, y=4120490 Sensor at x=16, y=2009884: closest beacon is at x=10411, y=2000000 Sensor at x=2504789, y=3988246: closest beacon is at x=3145593, y=4120490 Sensor at x=2861842, y=2428768: closest beacon is at x=3166783, y=2549046 Sensor at x=3361207, y=130612: closest beacon is at x=2039500, y=-250317 Sensor at x=831856, y=591484: closest beacon is at x=-175938, y=1260620 Sensor at x=3125600, y=1745424: closest beacon is at x=3166783, y=2549046 Sensor at x=21581, y=3243480: closest beacon is at x=10411, y=2000000 Sensor at x=2757890, y=3187285: closest beacon is at x=2307516, y=3313037 Sensor at x=3849488, y=2414083: closest beacon is at x=3166783, y=2549046 Sensor at x=3862221, y=757146: closest beacon is at x=4552923, y=1057347 Sensor at x=3558604, y=2961030: closest beacon is at x=3166783, y=2549046 Sensor at x=3995832, y=1706663: closest beacon is at x=4552923, y=1057347 Sensor at x=1082213, y=3708082: closest beacon is at x=2307516, y=3313037 Sensor at x=135817, y=1427041: closest beacon is at x=-175938, y=1260620 Sensor at x=2467372, y=697908: closest beacon is at x=2039500, y=-250317 Sensor at x=3448383, y=3674287: closest beacon is at x=3225436, y=4052707"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day15Kt.class", "javap": "Compiled from \"Day15.kt\"\npublic final class cz.wrent.advent.Day15Kt {\n private static final int BEACON;\n\n private static final int CLEAR;\n\n private static final java.lang.String test;\n\n private stati...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day7.kt
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("7a: $result") println(partTwo(test)) val resultTwo = partTwo(input) println("7b: $resultTwo") } private fun partOne(input: String): Long { val nodes = input.parseTree() return nodes.values.filterIsInstance<Dir>().filter { it.getSize() <= 100000 }.sumOf { it.getSize() } } private fun partTwo(input: String): Long { val nodes = input.parseTree() val root = nodes["/"]!! val freeSpace = 70000000 - root.getSize() val requiredSpace = 30000000 - freeSpace return nodes.values.filterIsInstance<Dir>().filter { it.getSize() >= requiredSpace }.minByOrNull { it.getSize() }!! .getSize() } private interface Node { fun getChildren(): List<Node> fun getSize(): Long fun getFullName(): String fun getParent(): Dir } private data class File( private val parent: Dir, private val name: String, private val size: Long, ) : Node { override fun getChildren(): List<Node> { return emptyList() } override fun getSize(): Long { return size } override fun getFullName(): String { return this.parent.getFullName() + "/" + this.name } override fun getParent(): Dir { return this.parent } } private data class Dir( private val parent: Dir?, private val name: String, private val children: MutableList<Node>, ) : Node { override fun getChildren(): List<Node> { return children } override fun getSize(): Long { return children.sumOf { it.getSize() } } override fun getFullName(): String { return (this.parent?.getFullName() ?: "") + "/" + this.name } override fun getParent(): Dir { return this.parent ?: this } fun addChild(node: Node) { this.children.add(node) } } private fun String.parseTree(): Map<String, Node> { val split = this.split("$ ").drop(1) val iterator = split.iterator() val root = Dir(null, "", mutableListOf()) val nodes = mutableMapOf<String, Node>(root.getFullName() to root) var current = root while (iterator.hasNext()) { val next = iterator.next() if (next.startsWith("cd")) { val path = next.split(" ").get(1).trim() val dir = Dir(current, path, mutableListOf()) if (path == "/") { current = root } else if (path == "..") { current = current.getParent() } else if (!nodes.containsKey(dir.getFullName())) { current = dir nodes[dir.getFullName()] = dir } else { current = nodes[dir.getFullName()] as Dir } } else if (next.startsWith("ls")) { val files = next.split("\n").drop(1).filter { it.isNotEmpty() } files.forEach { fileString -> val (size, name) = fileString.split(" ") val node = if (size == "dir") { Dir(current, name, mutableListOf()) } else { File(current, name, size.toLong()) } current.addChild(node) nodes[node.getFullName()] = node } } else { error("Unknown command $next") } } return nodes } private const val test = """${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k""" private const val input = """${'$'} cd / ${'$'} ls dir bntdgzs 179593 cjw.jgc 110209 grbwdwsm.znn dir hsswswtq dir jdfwmhg dir jlcbpsr 70323 qdtbvqjj 48606 qdtbvqjj.zdg dir tvcr dir vhjbjr dir vvsg 270523 wpsjfqtn.ljt ${'$'} cd bntdgzs ${'$'} ls 297955 gcwcp ${'$'} cd .. ${'$'} cd hsswswtq ${'$'} ls dir bsjbvff dir dpgvp 267138 grbwdwsm.znn dir hldgfpvh dir jdfwmhg dir jtgdv 93274 ptsd.nzh 268335 qdtbvqjj.dlh 185530 qdtbvqjj.jrw dir vcbqdj dir wtrsg ${'$'} cd bsjbvff ${'$'} ls dir dmnt 148799 grbwdwsm.znn 324931 hzmqrfc.lsd 211089 qdtbvqjj ${'$'} cd dmnt ${'$'} ls 221038 zht ${'$'} cd .. ${'$'} cd .. ${'$'} cd dpgvp ${'$'} ls dir fzttpjtd dir jdrbwrc dir rwz dir tssm ${'$'} cd fzttpjtd ${'$'} ls 149872 jdfwmhg ${'$'} cd .. ${'$'} cd jdrbwrc ${'$'} ls 149973 hpgg.srm dir ptsd ${'$'} cd ptsd ${'$'} ls 2594 twzf.pqq ${'$'} cd .. ${'$'} cd .. ${'$'} cd rwz ${'$'} ls dir jdfwmhg 302808 zzlh ${'$'} cd jdfwmhg ${'$'} ls 229683 cdcrgcmh 218733 nhzt ${'$'} cd .. ${'$'} cd .. ${'$'} cd tssm ${'$'} ls dir ptsd 37272 qfnnrqsh.qvg 215066 wnvjc.jqf ${'$'} cd ptsd ${'$'} ls 24102 bwtbht.dwq 224035 qdtbvqjj.dmp ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd hldgfpvh ${'$'} ls 316712 grbwdwsm.znn 328950 tqvgqjrr ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls 130652 gcwcp dir jdfwmhg 215427 lfw.zml dir qdtbvqjj 4181 rgsvgssj.qsr ${'$'} cd jdfwmhg ${'$'} ls dir bvm dir hsswswtq 122279 qznt.jhl dir sjw dir zpfdtl ${'$'} cd bvm ${'$'} ls 22841 fbcgh.mrp dir hsswswtq dir hstg 41317 ndrt dir nvmvghb 239316 ptsd dir qtwvdtsp 98555 vzh ${'$'} cd hsswswtq ${'$'} ls dir ddcjvjgf 127104 plwvb.pbj dir ptsd dir qhp dir rjtrhgwh ${'$'} cd ddcjvjgf ${'$'} ls 135870 bwtbht.dwq 81968 gcwcp 182253 mrbh.wmc 275931 nsrqrts 322128 pfpcp ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 214981 jsrlsc dir wpbdrcw ${'$'} cd wpbdrcw ${'$'} ls 197849 mljfb.ggb 173586 ptsd ${'$'} cd .. ${'$'} cd .. ${'$'} cd qhp ${'$'} ls 293198 bnrgl ${'$'} cd .. ${'$'} cd rjtrhgwh ${'$'} ls 224393 clrp.nst ${'$'} cd .. ${'$'} cd .. ${'$'} cd hstg ${'$'} ls 51671 gdsfpc 209216 hsswswtq 97203 jlnr dir thdhg 57399 tssm ${'$'} cd thdhg ${'$'} ls 201896 jjp.wvw ${'$'} cd .. ${'$'} cd .. ${'$'} cd nvmvghb ${'$'} ls 210047 gfcrzgj dir rqjbplv dir rvwd 292931 sgwvcqfr.bpq dir vtjd ${'$'} cd rqjbplv ${'$'} ls 105204 gcwcp ${'$'} cd .. ${'$'} cd rvwd ${'$'} ls 66170 jdfwmhg ${'$'} cd .. ${'$'} cd vtjd ${'$'} ls dir ptsd ${'$'} cd ptsd ${'$'} ls 300524 bwtbht.dwq ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd qtwvdtsp ${'$'} ls 289574 wctgtq ${'$'} cd .. ${'$'} cd .. ${'$'} cd hsswswtq ${'$'} ls 24935 gcwcp dir jzpbdcmc 26834 mljfb.ggb 182501 phnmlsjp.pjc dir pttnl dir qdtbvqjj dir vst ${'$'} cd jzpbdcmc ${'$'} ls 297521 grbwdwsm.znn dir qwc dir zzswd ${'$'} cd qwc ${'$'} ls 81143 hsswswtq.rjw 54843 mjvvfsz.rgz 273051 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd zzswd ${'$'} ls 216062 vlbwz.zmh ${'$'} cd .. ${'$'} cd .. ${'$'} cd pttnl ${'$'} ls 257733 mljfb.ggb 250887 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd qdtbvqjj ${'$'} ls 34667 gcwcp ${'$'} cd .. ${'$'} cd vst ${'$'} ls 70250 pfwgtmtt.ccs dir zpcqhml ${'$'} cd zpcqhml ${'$'} ls 219936 jdfwmhg.zbm ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd sjw ${'$'} ls 152311 nqjtvzff 157117 pfwgtmtt.ccs 118226 ptsd.vsm ${'$'} cd .. ${'$'} cd zpfdtl ${'$'} ls 189042 gcwcp ${'$'} cd .. ${'$'} cd .. ${'$'} cd qdtbvqjj ${'$'} ls dir ftz dir hvlffb dir lzbb 53335 ptsd dir qdtbvqjj ${'$'} cd ftz ${'$'} ls dir fft 256058 gcwcp 497 hsswswtq.vqs 103941 hvtcz.fsg 171587 ljlnz.ffg 115101 mljfb.ggb dir qdtbvqjj ${'$'} cd fft ${'$'} ls 58845 bwtbht.dwq 136040 gcwcp 256973 mljfb.ggb ${'$'} cd .. ${'$'} cd qdtbvqjj ${'$'} ls dir fgqhdh 304573 ntm.wmc ${'$'} cd fgqhdh ${'$'} ls 317143 gcwcp 26010 lsfpfdqz ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd hvlffb ${'$'} ls 6682 vjt.mcf ${'$'} cd .. ${'$'} cd lzbb ${'$'} ls dir bbvml 324162 bwtbht.dwq dir fjs dir pffntc dir pnltt dir ptsd ${'$'} cd bbvml ${'$'} ls dir qdtbvqjj dir qssdcrp dir tssm ${'$'} cd qdtbvqjj ${'$'} ls 246275 qdtbvqjj.cgn ${'$'} cd .. ${'$'} cd qssdcrp ${'$'} ls 274399 hsswswtq ${'$'} cd .. ${'$'} cd tssm ${'$'} ls dir ssqc ${'$'} cd ssqc ${'$'} ls 178904 njrssmlm.gcm ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd fjs ${'$'} ls dir dmvnp 121967 fqlzlvwt 204348 grbwdwsm.znn 102733 jdfwmhg.qsl 240279 ptsd.jwm 228793 ptsd.nsh dir ssm ${'$'} cd dmvnp ${'$'} ls dir psj dir zjw ${'$'} cd psj ${'$'} ls 170665 gcwcp 56058 lsfzc.dcp 40658 tfsllqqw.fgv ${'$'} cd .. ${'$'} cd zjw ${'$'} ls 79989 fggsl.dmz ${'$'} cd .. ${'$'} cd .. ${'$'} cd ssm ${'$'} ls 106263 bwtbht.dwq 106259 jdfwmhg.qtb 6246 rwbnr.tqv ${'$'} cd .. ${'$'} cd .. ${'$'} cd pffntc ${'$'} ls 111475 qbmrdms.ldm ${'$'} cd .. ${'$'} cd pnltt ${'$'} ls dir nptfhlf dir zngmf ${'$'} cd nptfhlf ${'$'} ls 223065 qrb.drh 205674 rdgfz ${'$'} cd .. ${'$'} cd zngmf ${'$'} ls 61655 bwtbht.dwq ${'$'} cd .. ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls dir hrvrt dir thwtl ${'$'} cd hrvrt ${'$'} ls 152296 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd thwtl ${'$'} ls 156783 pfwgtmtt.ccs 323304 sltc ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd qdtbvqjj ${'$'} ls 320175 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd jtgdv ${'$'} ls 81164 ptsd.tpj ${'$'} cd .. ${'$'} cd vcbqdj ${'$'} ls dir crng 330203 gvlrg 152022 qdtbvqjj.slq 294095 rthwj.zrf dir vjsbf ${'$'} cd crng ${'$'} ls dir gznrh ${'$'} cd gznrh ${'$'} ls 259458 ptsd ${'$'} cd .. ${'$'} cd .. ${'$'} cd vjsbf ${'$'} ls 47331 hlld.fzf 147103 jdfwmhg ${'$'} cd .. ${'$'} cd .. ${'$'} cd wtrsg ${'$'} ls 144344 dtcc ${'$'} cd .. ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls 323973 qdtbvqjj ${'$'} cd .. ${'$'} cd jlcbpsr ${'$'} ls dir htrdwm dir jdfwmhg dir pwmvbhsl dir vwfdfmcp ${'$'} cd htrdwm ${'$'} ls dir btn 105731 dlncqrbm.dgl 158267 gqqghldt 242513 hsswswtq.drj dir jdfwmhg 212816 swsgtv.wbb 228996 tgll.rcs ${'$'} cd btn ${'$'} ls 50419 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls dir bwc ${'$'} cd bwc ${'$'} ls 184634 cfwg ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls 319749 hsswswtq dir jdfwmhg 271619 jdfwmhg.znz dir jhmmt 181217 mljfb.ggb 11297 rcpl.tgf 83423 zwscbcvm.ths ${'$'} cd jdfwmhg ${'$'} ls 267171 cts.hlf ${'$'} cd .. ${'$'} cd jhmmt ${'$'} ls 84473 jdfwmhg ${'$'} cd .. ${'$'} cd .. ${'$'} cd pwmvbhsl ${'$'} ls dir jsg 171725 mljfb.ggb 152612 qjr dir vfsqw ${'$'} cd jsg ${'$'} ls 176951 jdfwmhg.fhn 284927 ljvvtw.wcq 153109 vnvtt ${'$'} cd .. ${'$'} cd vfsqw ${'$'} ls 104559 htsrns.gws ${'$'} cd .. ${'$'} cd .. ${'$'} cd vwfdfmcp ${'$'} ls 291404 csmvbjlt.tdf ${'$'} cd .. ${'$'} cd .. ${'$'} cd tvcr ${'$'} ls dir djtwv dir hsswswtq 272845 mdds dir ndshbjzn 65929 scpltww.twm dir tssm 30516 zdpscm dir zqdrdzv ${'$'} cd djtwv ${'$'} ls 271696 cwjj.hjp ${'$'} cd .. ${'$'} cd hsswswtq ${'$'} ls dir djngm dir hcz dir ptsd ${'$'} cd djngm ${'$'} ls 317775 ltwjzpjb.rcj 37776 qdtbvqjj.lzf ${'$'} cd .. ${'$'} cd hcz ${'$'} ls 217741 pgdmr 128868 qdtbvqjj 306138 zbmrplsn ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 304048 ftm 120236 mdcwvvng ${'$'} cd .. ${'$'} cd .. ${'$'} cd ndshbjzn ${'$'} ls 206408 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd tssm ${'$'} ls dir mlcnsf dir nbgjm 204079 pdljvb 185465 rqgdmbjf.rhr dir sfnlb ${'$'} cd mlcnsf ${'$'} ls 249868 fqrncwd 29146 zdz.jth ${'$'} cd .. ${'$'} cd nbgjm ${'$'} ls 113314 mljfb.ggb ${'$'} cd .. ${'$'} cd sfnlb ${'$'} ls 234917 tjp ${'$'} cd .. ${'$'} cd .. ${'$'} cd zqdrdzv ${'$'} ls 40790 vtdnhzm ${'$'} cd .. ${'$'} cd .. ${'$'} cd vhjbjr ${'$'} ls dir glv dir mvns dir qbrnh ${'$'} cd glv ${'$'} ls 288849 bgvqll.sfj 259105 jdfwmhg dir qcjlshcv ${'$'} cd qcjlshcv ${'$'} ls dir nwqqjcmh ${'$'} cd nwqqjcmh ${'$'} ls 137244 grbwdwsm.znn 312904 mzh dir qdtbvqjj ${'$'} cd qdtbvqjj ${'$'} ls dir nlqbq ${'$'} cd nlqbq ${'$'} ls 307636 ptsd.vtr ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd mvns ${'$'} ls dir gzqlmrdh dir qjhtlh dir tssm dir vthg ${'$'} cd gzqlmrdh ${'$'} ls 274950 mlzdqwm ${'$'} cd .. ${'$'} cd qjhtlh ${'$'} ls 157835 ptsd.lqm 300380 wst.trp ${'$'} cd .. ${'$'} cd tssm ${'$'} ls 15772 gcwcp ${'$'} cd .. ${'$'} cd vthg ${'$'} ls dir gdndtlnc ${'$'} cd gdndtlnc ${'$'} ls 3175 hsswswtq.bds 320462 mljfb.ggb 305508 mzvtzvqc dir qdtbvqjj 154575 tssm.vgb ${'$'} cd qdtbvqjj ${'$'} ls 236889 drnnvh ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd qbrnh ${'$'} ls dir hsswswtq 4623 hsswswtq.rnf 266326 jrmq.ztg 295980 tssm.vzb dir wnbfzd dir zjzhncs dir zttlggt ${'$'} cd hsswswtq ${'$'} ls 48277 gsqjdbhv ${'$'} cd .. ${'$'} cd wnbfzd ${'$'} ls 97133 mljfb.ggb ${'$'} cd .. ${'$'} cd zjzhncs ${'$'} ls 298303 gcwcp dir ggr 113206 grbwdwsm.znn ${'$'} cd ggr ${'$'} ls 244876 ptsd.zvb ${'$'} cd .. ${'$'} cd .. ${'$'} cd zttlggt ${'$'} ls dir hdbwrcm dir mbvpd dir mtd dir ptsd dir tcwqp ${'$'} cd hdbwrcm ${'$'} ls 267323 bwtbht.dwq ${'$'} cd .. ${'$'} cd mbvpd ${'$'} ls 84087 frf.smv ${'$'} cd .. ${'$'} cd mtd ${'$'} ls 158543 mljfb.ggb ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 112797 vtschwnb.fnp ${'$'} cd .. ${'$'} cd tcwqp ${'$'} ls 90637 lbsqcj.sfn 179097 tssm.dbl ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd vvsg ${'$'} ls 168715 bwtbht.dwq dir bwv dir hsswswtq dir lqmnjrlb dir mmrfrj 175244 vct.tsc dir zwvlhs ${'$'} cd bwv ${'$'} ls 201509 gcwcp 62815 grbwdwsm.znn dir gwdh dir mfdvcn 166355 pfwgtmtt.ccs dir ptsd 169681 qdtbvqjj.fgh 250573 wvndzgv ${'$'} cd gwdh ${'$'} ls 306377 sphrj.pjh ${'$'} cd .. ${'$'} cd mfdvcn ${'$'} ls 27796 bvclvtrm.jlf 65045 cghr.vzg dir hsswswtq 197145 jdqztgh.pvd ${'$'} cd hsswswtq ${'$'} ls 298155 bwtbht.dwq ${'$'} cd .. ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 27501 grbwdwsm.znn 231999 jdnsv 113528 rmfmb.zzw dir tssm dir vgjfsh ${'$'} cd tssm ${'$'} ls dir dndv 226375 grbwdwsm.znn ${'$'} cd dndv ${'$'} ls 152739 sdjrzcv.tvs ${'$'} cd .. ${'$'} cd .. ${'$'} cd vgjfsh ${'$'} ls 211409 swtbttb.vrp 170879 vvfnf.hrp ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd hsswswtq ${'$'} ls dir qdtbvqjj dir tssm 86418 vhsgq ${'$'} cd qdtbvqjj ${'$'} ls 118588 bwtbht.dwq ${'$'} cd .. ${'$'} cd tssm ${'$'} ls 113460 gml.wdg ${'$'} cd .. ${'$'} cd .. ${'$'} cd lqmnjrlb ${'$'} ls dir tssm ${'$'} cd tssm ${'$'} ls dir jdfwmhg ${'$'} cd jdfwmhg ${'$'} ls 64663 nswd.rwc ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd mmrfrj ${'$'} ls 319070 gltlwnlt.jzw 232039 hspr 104688 hsswswtq.jsr dir jdfwmhg 88712 jdfwmhg.zcw dir pfr dir prnnpwcd 45488 qdtbvqjj dir tssm dir wcmwrtjn ${'$'} cd jdfwmhg ${'$'} ls 140910 bjjhtzct.stm ${'$'} cd .. ${'$'} cd pfr ${'$'} ls 289538 qdtbvqjj 217502 vvpwf ${'$'} cd .. ${'$'} cd prnnpwcd ${'$'} ls dir qdtbvqjj ${'$'} cd qdtbvqjj ${'$'} ls dir pqg dir tssm ${'$'} cd pqg ${'$'} ls 222392 ptsd.ggr ${'$'} cd .. ${'$'} cd tssm ${'$'} ls 158252 dcnvjj.zfd 10486 jdfwmhg.qmb 4374 qdtbvqjj.vqm 254229 vgqfw ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd tssm ${'$'} ls dir ptsd ${'$'} cd ptsd ${'$'} ls 173766 fvlsgqb 35658 wtc.vvd ${'$'} cd .. ${'$'} cd .. ${'$'} cd wcmwrtjn ${'$'} ls 160089 chfhpc 76202 frgpdnd.ngw 138996 jsfsfpqg.nhf dir mlm dir nbdbzsn dir ptsd 278574 vrnb ${'$'} cd mlm ${'$'} ls dir gqwhhmvd dir nrzvzgrt dir nzplht dir zzp ${'$'} cd gqwhhmvd ${'$'} ls dir ddmvjpj dir jdfwmhg ${'$'} cd ddmvjpj ${'$'} ls 273423 jdfwmhg 43605 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls 239406 qctw.vzb ${'$'} cd .. ${'$'} cd .. ${'$'} cd nrzvzgrt ${'$'} ls 20712 gcwcp 239372 gjgdvbwb.gcz dir hdzhl 124814 jdfwmhg dir jfzr 295071 qwjgwqp 221611 shrzpsj.dwh dir tssm dir wdlsvzvl ${'$'} cd hdzhl ${'$'} ls dir gfwbd 184323 hsswswtq.mln 177147 nqgqz.tnf 4680 pfwgtmtt.ccs ${'$'} cd gfwbd ${'$'} ls 254870 cldm.fft 301411 tssm.cvn ${'$'} cd .. ${'$'} cd .. ${'$'} cd jfzr ${'$'} ls dir dvvflnnw dir jdfwmhg 216389 lwtwn.ttt 201727 pfwgtmtt.ccs 107829 prphc.ncb 5816 sdvq.jvn ${'$'} cd dvvflnnw ${'$'} ls 24741 brtrbwh.wwd 27700 mljfb.ggb ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls 325218 bwtbht.dwq 63718 mvl.ngz 162645 vtd.vgp ${'$'} cd .. ${'$'} cd .. ${'$'} cd tssm ${'$'} ls 60903 pfwgtmtt.ccs 332768 qdtbvqjj.jwb ${'$'} cd .. ${'$'} cd wdlsvzvl ${'$'} ls 142213 vgvd ${'$'} cd .. ${'$'} cd .. ${'$'} cd nzplht ${'$'} ls 275904 hsswswtq 157369 jdfwmhg 84363 jvcvmbm.fht dir qbjqgg ${'$'} cd qbjqgg ${'$'} ls 331934 gcwcp ${'$'} cd .. ${'$'} cd .. ${'$'} cd zzp ${'$'} ls 151335 flsd.zmj dir gwlhqlp 99086 jdfwmhg.hft ${'$'} cd gwlhqlp ${'$'} ls 201894 glcnpqzp.jvc ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd nbdbzsn ${'$'} ls 169929 bwtbht.dwq ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 128999 bwtbht.dwq dir jtlrn dir pszlt dir ptjnh dir ptsd 2981 qdtbvqjj.qcn dir rpb dir tcjgpqj dir tmddnh dir tssm ${'$'} cd jtlrn ${'$'} ls 124888 grbwdwsm.znn 30046 jznz.dwf ${'$'} cd .. ${'$'} cd pszlt ${'$'} ls 154368 dbblsg.mzr ${'$'} cd .. ${'$'} cd ptjnh ${'$'} ls 306974 grbwdwsm.znn 82840 ptsd ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls dir ftjhsb dir jdfwmhg 304012 lqgtvmrl.qbj 96971 mljfb.ggb ${'$'} cd ftjhsb ${'$'} ls 56965 dhgds ${'$'} cd .. ${'$'} cd jdfwmhg ${'$'} ls dir lssbmtms dir vmwshd ${'$'} cd lssbmtms ${'$'} ls 95453 gcwcp 198402 mljfb.ggb 1507 mzlmp 40526 twlqhml ${'$'} cd .. ${'$'} cd vmwshd ${'$'} ls 267087 pfwgtmtt.ccs ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd rpb ${'$'} ls dir lqbchlbp dir ptsd ${'$'} cd lqbchlbp ${'$'} ls 151429 ptsd.tjz ${'$'} cd .. ${'$'} cd ptsd ${'$'} ls 28900 gcwcp 55920 llt ${'$'} cd .. ${'$'} cd .. ${'$'} cd tcjgpqj ${'$'} ls dir cvdlcvq 329232 hcmj.nvp 232764 nvtmgc.qgs 108056 ptsd.gcn 39056 qdtbvqjj 91792 tssm.wqz ${'$'} cd cvdlcvq ${'$'} ls 46978 grbwdwsm.znn 17760 qrdbsdpj.dhm ${'$'} cd .. ${'$'} cd .. ${'$'} cd tmddnh ${'$'} ls 238434 gggvq.tfc ${'$'} cd .. ${'$'} cd tssm ${'$'} ls dir tlllv ${'$'} cd tlllv ${'$'} ls 198184 trmf.qqw ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd .. ${'$'} cd zwvlhs ${'$'} ls 19923 gcwcp 129179 grbwdwsm.znn 214660 pghcvh 101270 ptsd.gzl dir srjlz ${'$'} cd srjlz ${'$'} ls 221301 nrcg.pqw"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day7Kt.class", "javap": "Compiled from \"Day7.kt\"\npublic final class cz.wrent.advent.Day7Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n Cod...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day13.kt
package cz.wrent.advent import java.util.Deque import java.util.LinkedList fun main() { println(partOne(test)) val result = partOne(input) println("13a: $result") println(partTwo(test)) println("13b: ${partTwo(input)}") } private fun partOne(input: String): Int { val pairs = input.split("\n\n") val packetPairs = pairs.map { it.split("\n").filter { it.isNotEmpty() }.map { it.parsePacketData() } } .map { it.first() to it.get(1) } return packetPairs.mapIndexed { index, pair -> index to pair.first.compareTo(pair.second) }.filter { it.second < 0 } .sumOf { it.first + 1 } } private fun partTwo(input: String): Int { val parsed = input.split("\n").map { it.trim() }.filter { it.isNotEmpty() }.map { it.parsePacketData() } + "[[2]]".parsePacketData() + "[[6]]".parsePacketData() val sorted = parsed.sorted() val a = sorted.indexOfFirst { it == PacketList(listOf(PacketList(listOf(PacketInt(2))))) } val b = sorted.indexOfFirst { it == PacketList(listOf(PacketList(listOf(PacketInt(6))))) } return (a + 1) * (b + 1) } private fun String.parsePacketData(): PacketList { val root = mutableListOf<PacketData>() val input = this.substring(1, this.length - 1) val stack: Deque<MutableList<PacketData>> = LinkedList<MutableList<PacketData>?>().apply { add(root) } as Deque<MutableList<PacketData>> val sb = StringBuilder() for (char in input) { when (char) { '[' -> stack.push(mutableListOf()) ']' -> { if (sb.isNotEmpty()) { stack.peek().add(PacketInt(sb.toString().toInt())) sb.clear() } val closed = stack.pop() stack.peek().add(PacketList(closed)) } ',' -> { if (sb.isNotEmpty()) { stack.peek().add(PacketInt(sb.toString().toInt())) sb.clear() } } else -> sb.append(char) } } if (sb.isNotEmpty()) { stack.peek().add(PacketInt(sb.toString().toInt())) sb.clear() } return PacketList(root) } private interface PacketData : Comparable<PacketData> private data class PacketInt(val value: Int) : PacketData { override fun compareTo(other: PacketData): Int { return if (other is PacketInt) { this.value.compareTo(other.value) } else { PacketList(listOf(this)).compareTo(other) } } } private data class PacketList(val value: List<PacketData>) : PacketData { override fun compareTo(other: PacketData): Int { return if (other is PacketList) { val zipped = value.zip(other.value) var result = 0 for (pair in zipped) { val compare = pair.first.compareTo(pair.second) if (compare != 0) { result = compare break } } if (result != 0) { result } else { this.value.size.compareTo(other.value.size) } } else { this.compareTo(PacketList(listOf(other))) } } } private const val test = """[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9] """ private const val input = """[] [[6,[4,[4,10,7]],[[0,8,6],2],[[],8,[7,10,6,4,2],[10,10],6],4]] [[[9,6,2,5,[4,6,6,8,2]],1,4,10],[[[2,10,9,8],6,1,[0]],[[],[8]]],[[9,[0,7,8],6],[[],9,[5,5],[3]]],[6,3,[7,[1],[0,10,10,2,1],[7]],6,[4,2,3,[]]],[[0,4,[5,4,2,9,5],[2,10],4],5,6,[5,8,4],[[4],5]]] [[4,0,7,[1,[2,7,2],5,[6]],5],[3,[1,10,[10,4,5,9],8]],[7],[[0],[],6,8],[[[1,2],10,3,8,[]],0,7]] [[[4,6,9,3,1],4,[3],[2,4,[6,10]],6],[]] [[4,8],[[],6],[3,4]] [[10,[[8],7,[4,10,3],1,7]],[[[],2,[6]],10,[[10,0,6,1],1,0],8],[]] [[2,[3]],[[[],0,[2,6]]]] [[3,[[8,1,10,7],[10,8,1,5],5,[8]],10]] [[[4],5,[[],[],10]],[[[],[],[10],[3,7,1],[5,5,6]]],[[4,3],7],[[[5,9,8,9]]]] [[5,[1],9,[[7,10,5],8,[8,7,2],[6,1]]]] [[[[1,6],6,7],[],1,[],[[8,4,4,0,4],9]]] [[[2,7,[10,6,0],[10]],[[1,6,9],9],[[2],[],1,[8]]],[[]]] [[],[5,9,3,[9,[10,8,10,1],6],[3]],[[10,3,[6,5,1,5]]],[5,[]]] [[4],[[0,[1],1,4],[3,0,8,[10,3,7,8]],3],[4,9],[[8],[[9,1,4,6],[0,3,7,9,3],[2,9,9,9,0],[]],10,8]] [[],[3,[0,[4,7],2],10,3,[2,3]]] [[[[2,2],2,[9],[1,6,7,6,2]],[],6]] [[3,3,10],[[3,[10,2,6,8,9],[10,10,4,6,1],[7,1,0]],1,[[1,1,9],[10,4,7,4]]],[[],[8,5],[1,[4,4,4,8],[6,7,4],[1,4]],5,8],[4]] [[9,8,8],[],[],[7,[0,1,1],8]] [[9,[[2,5]],[10,[1,5,10,5]],4,5],[0]] [[],[],[4,[9],[[3,7]],4],[5,10,[4],[[9,4,7],[2,0,6,8,5],3,5,7],10],[]] [[4,[2,10,[],[9,5,9]],[[2,8,8],[4,6,10],1,[9],[1,9]],[8,[5,3,10,10],[7,0],0],[]],[],[],[[10,[1,8,3,3],7,7,[4]],4],[[],1,3]] [[9,[[1,2,6],1,6,2],5,[4,[0,5,9],[2],3]]] [[[],[1,8,[3,7,0],7],1,[5,4],[[10,0,0],6,0,[1,2,6],[0,4]]],[1,1,0,[[3],[6,8,6],[10,7,8],[2,10,8,7],6],[]],[[],[[9,5,1,1,8],8,[5]],[[6,10,2,10,2],7,0,8,[10]]],[[[1,4,1,10],[],7],[[6],9,8,[4,1,9,3,3],[2,10,0]],2,[9,8]],[[],4,[]]] [[5],[9,[[10,3],[0,5,10,6],9,8,5],10,[6,3,6,6]],[4,8],[1,[[2],7,5]]] [[[4],[[3,0,7],[],7]],[[[],10,[],[10,3,6,1],8],8,0,[[9,8,3],5,[],1],2],[[],[[6,9,10,8,8]],0],[7,[8,0,8,5,[8,3,5]],[8,[6,3,1]],3],[[],[2]]] [[5,[10],5,10],[],[],[7,3],[4,4]] [[6,[[10,3,2,7,2],[7,3]]]] [[],[[10],9,5,9,1],[7,4,[]],[6,[10,6,[2],[5,10,4,9]]]] [[0,5,9],[[[3],[7,7,4,2],[],1,[]],3,[5,[3,1,9],0,[9,8],4],[6,5],10],[[8,3,[5,9,7,5,7],4],10,[[5,5,4],[2,1,4],1,[7,5,9]]]] [[[[0],[5]],7,[5,5,2,2]],[10,[[10,1,7,6,6],[5,1,10,3,7],[9,5,7]]]] [[],[1,[[0,7,0,5,10],10,[4]]],[2,[3,[3,9,1]],[[10,9,0,4],8]],[2],[6,10,2,[[2,1,4]],6]] [[6,[[3,8],5,0,7],[5,3,4]],[[10,5,[],[10,8,6,3,9]],2,[2,2],1],[1,[2,[8,4],2,7,[]]],[[[1],[3]],[[2],[10,10,5,6],9],[[5,6,7],[0,9],1,2],2]] [[[8,4],[9,[],8,8,10],3,4,2],[[5,[4,8,5],[2,0,1,4]],[0,[5,5,6]]],[5,[]],[]] [[[[],[0,7,5],5],9,[3,7,[]],[]],[[[4],7,10,[4,6,10,10,8]],[0,[9,8,4,0],10,3,9],10,[[1,9],10,[3,5,6,2]],0],[6],[[[0]],2,1]] [[6],[1,[[5],[1,8,0,8,3],5,6,7],[6],[[3,0,1,6,2],[9,7,8],10,[0,1,5,0,0],[4,10]]],[[9,8],9,[[8],0,[8,10,4,0],[]]]] [[[],[0,[10,7,2],[9,3,4,9],[10,0,10]],[],[[2,6,3,0],9],6]] [[5,[7,1,6,[9,1,5]]],[[7,[10,4,1,7],8,[2,10,0]],10,2,10,[[10,8,2,7,0],[3,6,0,8,4],7]],[[0,10,[9,4,10],3,[0,1,7,10,9]],1,1],[7,8,[6,[9],[3,5,0,3,5],[4,10,7,0,7],[4]],3,7],[3,[1],0,[[6,7,9],[7,9,0],[9,7,9,7,7]],[[5,10]]]] [[5,9,0],[[7,[]],[9,6,[6,8],2],1,[]],[],[[[6,4,3,2],[6,3,5],[6,9,0,9,2],0,1],[1,[2,4,7,1],0]]] [[3,[],[7,[3,5,9,10],[2,4]],0,1],[7]] [[[[5,4],10],10,[[1,4,1,10]]],[2,[]],[4,[1]],[[1],6,[[4,0,9,10,2],5],8]] [[],[[],3],[1],[[9],[[],[0],3,5]],[2]] [[10,6,5,10,[]],[[10,9,4,6],7,10]] [[1,10,[[9,10,0,6,5],4],10,10],[[[3,2,10,3],7,[],[3,9,2,5]],2,4]] [[],[[],6,[[9,8,6,7,9],[9,3],1,8,[6,1,7]],2],[[0],[1,4,10,[],10]],[7,1,1,6],[]] [[8,6,[1,9,9]],[0,[5,7]]] [[],[],[[5,[2,2,8,5,7],3,9,[4,6,0,2,0]],1,7,0],[],[[[7,6,5],9,[2,2,10,5,6]],4,[0,[],[9,4,1,8]],8,7]] [[7,0,0]] [[[[4,9,6,5,4],[0]],[]],[[[7],3,[10,7,4,8,4],[8,9],4],[5,4,[1]]]] [[[[4,9,0,2],[2,5,6],[3,10,4]],0,8,1,1],[[10,[2],1,[9,0,0,1,9],[8,9,6]],[[9,6,6],4,[5,7],8,[5,9,8,7,10]],10,2],[],[[],[2,0,9,10],1],[4,[[6],[]],5,[7,8,[9,9,3],0],1]] [[2,10,[[],0,9,8,7],6,0],[7,5,2,[],7],[3]] [[],[8,[1],5]] [[[[10,2,4],3,[],0],1,[[5,3,9,0],1],[7,[0,1],[1],9,5],[[1,10],[4,1,9,5,9]]],[8],[1,[9],5,[4,4,6],[8]]] [[1,10,[[2,3,4,8],8,8],2],[[[],[8,2],9,[0,5,7,0,5],4],4,[[],9,[]],[9,[2,9]],[[],[5],6,7,[]]]] [[9],[[[4,9],2,[6],[1],[]],[],[]],[[1]],[],[[],[0,[7,4,1],10],[[1]],[[1],[],[6,2,2,1,4],0,[5,4,2,2,5]],[]]] [[[4,2,1,3],[[9,2,3,3,4],10,8,8,10]],[7,[2,[3,3,6,3],0,[10,2,3,3]]],[[[],6,[5,6],3,[5,6,5,6,9]]]] [[[5,7,[9,7,10],[]],[[3,10,9,5],5],[],[[],8],[[1,10],10,9]],[[],[1,[4,8,5],[],[2,7,6,7,5]],1],[],[9,4]] [[],[6,7,3,3],[[3,[]],[]]] [[[[3,4],8,0,5],4,[[2,10]],7],[[[8,3,4],10,[6,9,8],[2,6,7,7,4]],10,5,[[1],[0,9],[1,1,3,5]]],[]] [[[[8,4],[0,6,5],0,[0,6]],[2],[[5]]]] [[8],[[2,7,2,[0,3,8]],[[6,3,8],3,[0],[3,6,1,4,3],6],10,6,[0]],[7],[[],[[],2,[0]]],[4,9,[[6,7,6]],7]] [[[[8]]],[[2,[3,4,0,1,6],10,[8],[]],[[7,9],4,10],[[6,8],[],6,[],[5,7,6]],[[6,7,10,5,2]],3],[2,3,2,[[10]]],[8,2,[9,8,[1,0,2]]]] [[7,[[0,5,6,0],[4,1,7,0],8,[1,3,7]],3,[]],[[10,8,[4,3],6,10],7],[],[[],6],[[1,2,4],[[1,3],[9,10],2,[10,6,5,6,0]],[[0],[],3,1],3,[[8],0,9]]] [[3,8,[5,9,5],4],[3],[],[[],[10,7,[7,0,7],7]],[7]] [[7,[[],8,[1],[9,1,6,7]],[[],0,[5,2,7,9]]],[[[10],8,[7,1],9],10],[[]]] [[[6,6,[0,0]],6,5,4,4]] [[[0,[2,10,1],[4,8,7,4],2,[9]],[5],8],[],[[2,7,[7,10],8,2],8,9,[1,4]],[[[1,4,2],3,[3],[4,1,9]],8,[],[9,[]],[]]] [[],[[0,1],3,[[4,2,7],10,6,[6,8,6],[3,8,3,5,8]],8,6],[1,1],[9,[[]],7],[[[6],[7,9],[0,6],[4,5,9,4]],[5,9,[10,5,7],[]],[3,[],1,10],5]] [[[[]],[],0,[[],[2,0,9],[3,3,1],7,[]],8],[[[2],[5,10],5,[10,0,5]],[[6],[0,0,4,6],[0,10]],5,[[]],6],[[2,[4,8,4,3,8],9],2,5,[[],2]],[[[5]]]] [[],[7,8,[[9,6],[7]]],[[[],1],1],[[[8,5,8,5],[]],[],9,1],[5,[[],10,[10,1,4,6,8],[10,9,9],[2,10,5]],0,[4,[4,2,0,1],2],5]] [[6,10,3]] [[],[[],3,[1],6],[],[[3],8,[1,1,[0,5,6,6,5],[]]]] [[9,8,9,5,[[3,9,6]]]] [[],[9,[[1,3],1,[8,6,4],[7,0,5,3,10],6],[[5],[1,5,3,8,4],10],[7,[0,0],[7,2,3,9],[6,5],[]]],[4,[],6,[[7,2]]],[8,8,3]] [[[[],7]],[5,[5,0,[6]]],[5,[0]],[9,2,[[]],[10,[4,9,9,5,10],6,7],10],[]] [[[[7,2],[1,2],10,[],[2,8]]]] [[0,[0,5,[4],4,4]]] [[[[10,0,2,2],1,[]],[10,[3]]],[6,10,[],6]] [[[],9,5],[[],8,[3]],[[],[[8],[6,8,5,4],[],[0,5,4,4,10]],8,[[],[10,0,1],[2,1,8,0]]],[[0],3,[4,0,[8],[4]],[]],[[[2,10,10,7,10],8,3,0,[7,0,3,1]],[[],[4,9,10,10],[5,8,6,9]],[2,[8,7,10],[7,9],[],[10]]]] [[6,9],[[8,9],1],[6,[0,[9,2,5,10],5],[9,[10,2,2],8,[9,3],[7,5,2,8]],8]] [[[3,1,[3,9]],1,[[]],6],[],[6,[[4,10,10,2,4],[],[6,7],0,6],[[7],[],[10,9],[5]]],[[5,[0,10,5],[6,9,4],4,9],5,8,[6,7]]] [[0]] [[[],1,[[8,6,8],[5,9],10],[[10,9,1,10,10],9,[8,3,3,0,5],[2,6,1,3,5],[0,7,8,7]],[[8,6,9,1],4]],[10,[1]],[],[4,[[5,4,0],[1],5]]] [[[]],[10,5,4]] [[10,10],[7]] [[],[[],10,6,8]] [[7,8],[1,[]],[]] [[2,2,3,8,7],[],[4,7,[0,4,4,[]],4],[[[3,0,9,10],[],[2,0]],[[1,10,3,5,9],3,[],[]]]] [[[[8],7,[2,7,5,9],[7,5,9,9]],[[],[7],7],6,0],[[[9,6],[1,3,9,4,4]],[[4,4],10],5,9],[1,4,7,7,3],[]] [[],[]] [[2,[1],[],[[8,10,4,0]]],[[],[1,[5,6,5,9],6]],[]] [[[4,6,1,5],[],2,[6,[]]],[[[7,7,2,3]]]] [[1,[[],9],1,[9,3,[1,9,4,5],10],4],[3,[[],[5,0,1,9,0]]],[[1,[2],1]]] [[],[[5,6,10,6],[[3,7,0,0,8],2,0,[9]],[5,10,6,7,4],1,[[6,9],6,[7,6],1]],[],[[2,8,[5,7],4],9,0]] [[[5,[6,5]],[1,2,4,[6,9,2],2],3,[[],[10,7,0,9],[10]]],[3,[[9,3,3],1,[4],[0,3,5],10],[[8,5,5],[],[10,3,10,1]],2],[[[10,9,2,0,9],0,[8,7,7,7]]]] [[],[[]],[[[5,10],[0,7,4,0],[3,3,10,8,0],[8,5,3,4,7],[3,6]],3,4],[1]] [[6,2],[],[9],[]] [[],[[[],6,2,[6,5,0,4],[1,7,6,1,5]],[[],6,[6,7,8,4,6],[4,10,5,10]],[],6],[0,[],[5]],[6]] [[10],[[[2,10],0],[1,[2,8,8],[]],[[8,1,0]],2,7],[0]] [[7,[8,[]]]] [[1,6,9,10,4]] [[[]],[[10,[0,1,1,9,8],[2,3,4,0]],[[5,2],[5,5,3,5],4,5]]] [[6,10,[10,4,3,10,[9,9,8,0]]],[[[8,6,5]],8,7,6,[]],[[[1,1,5,10,9],10],[[4,6,8,10,1],10,[0,0,5]],[[9,7]]]] [[],[[7,[8],7]],[],[1],[]] [[1,[[1,2,6,9,9],[],[],9],5],[8],[[7],[0,[7,3,9],[4,3,8,7],2,[]],10,[[],10,0,7],[2]],[4,[[],[9],[],8,7],[[9,6,2],2,[8],[4,1,0]],[],8],[]] [[],[[[7,8,10,3,1],0,4,[3,6,8,8,4]],6,9,[10,8,5,10]],[[[3,10,3],6],[2,[3,10,4,2,8],[7,3,3]]],[]] [[5,10,[],[10,[1,1,6,3],[8,5,5,1],10]],[2]] [[[],[],[[2,1,2,3,8],[9,4],[10,9,7,6],0],10,[[5,4,6],2,[4,8],3]]] [[[[6,0]],[[],6,0],3,[],7]] [[[[10,5],[]],[],7,5,6],[[[5],[9,8,5,10,4],[10,9,2,3,10],[2,6,2,0]]],[[1,2,10,[6,4,8,5,5],1],1,10,[[5],[4,0,10,5,6],[3,2,5,7],5,1],7]] [[],[[[5],[9,5,1,7,1],[2,2,10,5]],[5,3,[8,1],[]],[6,3,[2,8,2,6,1]],[[7,0,0,7],[]]],[9,[],[10]],[[5,10],[[6,1,2,7],[0,8,0,4]],[],1,2]] [[1,8,[],1,[]],[5],[3,6]] [[7,6],[6,[6,[]],[],10,10],[[1,[4],[1],[10,10,9,0]],[7,2,[],7,[8,5,6]]],[],[[],5,2,[]]] [[[[4,9],[4],2,[8,0,8,2]],[4,[7,0],[3,1,7,0],[0,1,3],[0,7,1,10]],2,[]]] [[[[6],[6],[0,6,9,9,0]]],[6,[[],[9,9,5,1],[0,1,6]],[[6,6,5],[5,2],[8,1,3],[4,2,5,2],7]]] [[[[9,1],[9,3,3,6,8],[],[7,5],3],4,[6,5,9],[[2,1,4,9,8],0,[5,10,1,7,6],[9,7,7]],[[5,5],2]]] [[[[7,5,3,3,4],[4,6,1,5]],10,[8,1],3],[5,[9,[10,8],[10,5,4,8]],[5,2,0,[0,0,6]],[[2,10,6],[10,2,6],0,1],3]] [[10,[6],[9,[1,1,0,5],6,10,4],8,0],[[]]] [[[[4,6],[6,7,5,7,9],1,5],5,7,8,[[8,5,1,9,2],3,[],[1,2,8],[5,3,6]]],[9],[8]] [[[[6,10,7,1,5],[3,1,4,9,0]]],[[[9,7],1,2],4,[[2,4],10,10,5]],[5,[1,0,6,[10,6]]]] [[[[8,5],8,1],1,1],[[5,[5,10,8],1,6,1],5,3],[0,3,6,[]],[7,3,4],[[[2,2],8,2],[[4,1,10,8],[2],3],4,8]] [[[9,1]]] [[[8,3,[0,10,4,10]],2]] [[3]] [[[[],[3,6],[5,7,1,9],[9,5,6,2,7]],8,0,7,2],[],[5,0,[4,[7,8,4],[7,1,2],[4,7,1]],[]],[4,9,[[5,6,9,6]],1]] [[[2],4,5,[[10,2,7,9,10],5]],[8,[5,5,[9,5,4,8,9],7,[3,10,0,1,7]],[6],[],[1]],[8,[[2,1,10],[]],[[8,3,7,8,4]],[[10,1,8],[10,0,10],3,7,5],[[0,5,1]]],[8],[[10,[],[6],[],6],3,[3,[],2,2,[3,1,10]],2]] [[],[[3,0,[]],[1,[10,2,3,5,5],[0,8,3,7,2],[5,0]],[2],[[0,4,2,3,7],[8,6,7,5],1]],[[0,[6]],[[4],2,[6,6,3],[8,3,4,2]],[5,1,[4,2,9]]]] [[[7,[],[10,8,4,3,8],[1,0]],2,8],[3,1,2],[[3,6,[7,6,0,9,7]],8],[8,6,[[4,10,1,1]],[[1,1,1],10],[6]],[[]]] [[[],[[5],4],[],9,3],[[7,[2,0,5,9,8],6,6,0]],[[5,4,[],[9]],7],[4,[[1,1],3,4,2],[[6,5,7],6,[2,0,5,3]]],[]] [[2],[[[10]],2,3],[[[1,6,2,9],10,[3,6,7,2,10],4,[6,3,10,6,7]],[[9,2]]]] [[[[]],[2],[1,2,[0],0],10,[[],3,9,[]]],[3,1]] [[[],7]] [[],[[[2,9,9],[]],8,[],[],[[6,1]]],[[10,0,[9,4,6,6],7,[]],9,[8,5,9]]] [[7,[]],[10,[8],[[9,8,7,6,8],[],10,2,2]],[[],3,[8,10],8,[2,6,[4,8,3]]],[[1,[5,1],4,0],[2,0],9,[]]] [[],[9,[[7,10,8],2,4],2],[3,5,3,10]] [[],[1,6],[1,8]] [[1,[[5,10,6,10,4],[10,8,9],[9,2,2,10,3],8],[1,5,1],[[8]]]] [[[6,10,6,[5,0,4]],9,8,5,[[4,9],10,[1,4],[]]],[8,[[1,7,8]],[10],[],1],[5,8,[[1,2,9],[3,1,6,4,2],10],3]] [[[10],[[10,4,7,4]],[[1],7,3,[5]]]] [[[],[]],[9,4,[],[],5],[[[8,3],[10],[],[2,8]],4,[[1,6,3],[6,8,0]],0],[[[2]],[3,4,[0,3,0],[2]]]] [[1],[1],[]] [[],[[5,[]],2],[[[4,7]]],[8,5,[[8]],3]] [[[3,2,[10]],5,[[9,8,2,10],4,[0,5,4],1],0,[]],[9,[[9],[7,3,6,9],7,[6],4],1],[9,[[4,3,4,10]],[[6,9,6,4,6]],[[0,5,2,5,0],[4,8,3,4],[2,0,9],[],[3,9]]],[[[1,0,7,2,8],[8],6,9]]] [[[[],1,[7,6,9,8],[2,1,1],8],1,0],[[9,[],[10,0,4,0,5],[]],[[5,1],[2,1,6],0,0,[2,8,0]],1,8]] [[[[9,10],[10,3,10,8],[],[],[7,5]],[[0,9,4,10,0]],[8,1,4,4,[2]],[7,[10,1,0],[],10],[]],[[0,8,3,6,9],9,[[],[6,2,3,3],[6,4,7],[2]],6],[],[]] [[[],6,2,9,5],[],[5,7]] [[6,4,[[7]]]] [[0],[3,6,7],[[7,[8,8,10]]]] [[7,[[],5],7,[[2,10],4,[4,0,3]],[]],[7,[2,[9,1],[0],5,7],0,5,[8,[7,8],0]],[[[2],[8]],[]],[6,[9,10,0,4],5,[[3,3,3,3,7],[3],[7,3],0]],[]] [[[[4],3,5,6],[],[3,7,[2,0,4,9,8]]]] [[2,[[1,1,8]]]] [[[1,10,3,5,2],[5],9],[[9,[10],[10,3,0,9]]],[[[4,2,8,10]],[8,[3,0,10],[8,7],2,[9,7,7]],[]]] [4,5,9,7] [4,5,9,7,3] [[[4,0,5,[3,6,9],[7,1]],[9,6],1,5]] [[3,[1,[5,8,10,3,5],[8,7,8],[8,2]],4,[[7,4,7],[6],[3,2],4]],[],[0,0,3,[[4,2]]],[8,[[1,1,2,8,7],1,[5,4,0,10,6]],[0,0,9],9,[2,[0,9,8,3],10,5]],[7,[3,[4],[1,2]],[[9,4,0,5],5,[1,3,9,5],[6,2,10,6,1],[1,5,1,2,1]]]] [[5,[4,[5,0,2],[6],[7]]],[8,9],[6,[8,1,7,[6]]]] [[[6,[4,3,5,10,2],3,[2,7,6],9],7,[1,[5,6,1,4,10],3,[],5]],[[7,[8,4,8],[5,3],[0,4,8],[4,9,1,3]],0,[],6],[[7,[4,9,3,4,7]],[2,3,0,[],6],[[4,5,3],[8,3,10,3,5],[3,8],3,9]],[[9,1,0,1],[3,[8,10],7]]] [[7,[[9,4,0,1,9],[7],[9,3],[2,9,3],[2,9,3,10]],[[8,1],[4],9],[8],[]],[[1,9,[]],0,6]] [[[[]],5]] [[9]] [[3,[[9]]],[[[1]],4,5],[0,3],[3,0,[4,0,6],[[3,6],[9,7,3],5,3,8]],[2,[0,2,[10]],3,7,[]]] [[],[[6,[7,2,7,9,6],[9,4,5],3,[]]],[5,4,9,0]] [[2,3,[],5,8],[[3,5,[9,3]]]] [[5,[],[]]] [[],[[]],[[[6],2,2,8],[[]]],[[],[[8],0],2,[[1]],[5,8]]] [[[2],[[3,0,0,3,2],[1,1],[2,7,2,10],[3]],2],[5,[7,9,6,[7,2,4,8,2]],[10]]] [[10,8,3],[9],[],[6,[],[[2,6],[8],8],[1,[1,3],4]]] [[9],[5,[[2,2,1,9,4],[2,2,0,3],3,1],[2,8,3,5]],[],[10],[]] [[[5]],[9],[9,[[8],[1,6]],7]] [[0],[],[1,[[],[8]],8,[[7,6,6,2,0],[7,6,3],[7,5,9],9]]] [[[9,1,4,[8,6]],2,8]] [[[[7,10,3],6,4],[[5,8,7,4,7],[2,4,3,7]],[4,7,[4,7,1,8],[]],2]] [[[[4,9]],[7,[2]],[],[[1,9,7],4,4,6,7]],[]] [[[2,0],[0,10,[1]],9,[[5],[1,9],4,[3,0,3,7,3],8]],[2],[],[[[1,1],[8,8,6]],[4,[7,9,9],[10,10,6,6,5]],[[10,3,9],[10,5,5,9],1,3,9],4],[4,3]] [[[[],[8,8,7,2]],[[5,3],[2,3],8,[7,8,9,4,4]]],[[5,0,6,8,[1,1,4,3,1]],[[9,5,4,5],2],[],[8,7,[9,2,0,6],[]]],[4,[[],[1],6]]] [[4,[2,8,[3,7,4,6,5],[9]]],[[[],7],2,3,[3],[]],[]] [[6,2,0],[],[[[],6]]] [[[4,6],7],[[4,[6,5],9],7,0],[6,2,5],[8,[[10,2],0,6,[],[0,4]],[[8],10,7,[0,6]],[[7,1,9,3]]],[[[],10,1,[7,6,0]],8,8]] [[2,[7],5],[],[0,[[0,5],0,[2,5,3,5,7],[10,3,3]],3,[],[10,10,[]]],[[[8,0,8,7],10,6,[9,4,6,1]],9],[[]]] [[[]],[[8],[7,5,10],0],[1,[[3,10,2],[9,4,3,6],0,[3,0,7,7,2],[7,3,4,2,10]],[7,[3,1,8,9,4],0,7,2],[6,6,[10,7,2,7,9]],7],[[4,1,[10],[8,2,9,6,1]],0,[[8],[0,6,5,3,10],[1,8,0,0],5,7],8],[8]] [[[[3,1,2,10,0],7],[[9,9,5,10],[4,2,3],8],6,[]],[10],[[[10]]],[[[9,5,0],[7]],10,[]],[[[8,9],1,1]]] [[10,1,[0]]] [[3,4,4],[5,[6]],[[1]],[3,[[9,1]],[[]]],[7,1]] [[],[8,5,[[2,8,7],[3]],9,[1,[4,7,2,6,0],0]],[6],[[10,0,8,1]],[3,9,[7,[]],[[9,3],[0,0,8,7,1],10]]] [[0],[5,10,10,[4,9,9,2,[4,7]]]] [[9,3]] [[[5,10,[5,1,10,6,5],10]],[],[[9,7,[2,5,7,9,5],[8,4,3,4,5],[3]],8,[[0,5],4,[9,6]],[]]] [[[[5,6],[6,2],0]],[4,[[3,3,0],[]]],[[[]],9,2,6,4],[[[9],3,8,1],6,[6,3,10,6]],[[10,[1]],[9,9],2,4,[[3,3],6,[],[5,9,2,0,9]]]] [[[[4,9],3,[9,4,10,7]],[[9,6,7],6,[2,4,3],5],6,1,[]],[3,8],[1]] [9,3,1,1,2] [9,3,1,1] [[[],4,[4],[[9,2,4,1],[0],[4,7],[1,5,10]]],[8,[[2,3,4,4,1]],[]]] [[8],[],[],[2,2,3,9],[9,3,[]]] [[2],[10,8],[[[7,3,3,5,7],[]],10,1,[[0,3,0],[],[2,2],2,[3,7,1]],8],[]] [[[10],[1,1,3,[9]],[1,4],[[],9],[8,3,[3]]],[[[9,4,8,7],9,4,[7,6,6,6]],7,4,[8,[1],4,4,8],2],[[[3,10,10],8,[5,9],[2,1,0,7,4]],[1,5,6,[10,7,10,7]],[],3,[[7],[6,7,5,2],0]]] [[],[[6,8,4,8,[4,7,4,2]],8,[[3,5,2],[]],[0,9,[0,6,2,6,6]],8]] [[8],[7,8,4],[5,2,[[5,2],0,[5,9]],[[10,2,4,7,4],7,0,[10,6],[3,6]],[5,4,8,8]]] [[10,[[6]],[2],5,3]] [[3,6,[0,7,[]]],[9,[]],[0,[[7,8,8,10,5],9,[]],[[7,7,10],3],[[5,4,4,0],8,1]],[[],[4]]] [[],[[[]],[6,[],10],[],2,[[1],[10,10],[7,10]]]] [[9,4,[[4,0,0,8,8],[6,10,3,10,0],8]]] [[2,[3,[8,9,5]],[[],9,[]],9],[8,[],[[],8,3]],[[3,[8,2,4]],[[8,5,5,8,7],9,4],[[5,2,0],7,[],[7,5],3],10]] [[[],[3,7],[[9,5,1],[3,9,3],5],[5],[3,9,[],[4,3,2],[8,8,8,8,7]]],[[],[6,4,[0,3,1]],[3,[1,4,4,5]]],[[9,[5,9,1,3,0],6,[]],9,1,[[5,2,7,3,9],4,4,7,[10,2,5,6]],8],[7,[],[[0,6],[8,6,8],5]]] [[6,2,[[],0,[1]]],[[[2],[6,2,8,5,0],[6,6,5,3],[8,10,8,5,1],[]],[[],[10,2,7],[7,3,4],3],[[3],1],8],[8,[7],[],7],[[[0,4,5,3,0],[0,10]],7]] [[[[6,9]],0,[1,[6,6,4,6,5],8],[2,6,0,[3]],[]],[[2,1],[8,2,8,3,6],5,10],[1,8],[1,8,1],[[10,[5,5,4,8,2],1,[]]]] [[3,4],[[],4,[6,[9,10,10,9,0],[0,10,0],[2,2]],[9,[8,4,2,3,4],6,[9,10,1,2],[3,2,2,3,4]]],[[8]]] [[9,[[]]],[],[2,[[0,4,8,7,7],[0,5]]],[]] [[7,5,4],[[[],1,[]]],[7],[4],[[],2,[[],[9,1,2],10,[6,5,1],[8,9,8]]]] [[[1,[10,2,3,0,3],9,0,5],4,[5,0,1,3,[5,2,1,9,10]],8],[[10],[[3,9,9,3,3]],9,10],[],[8,[],6,[8,9,10,8],[[4]]],[2,[9],2,[[10,5,8,2,9],[4,1,1,10],[3,3],[2,1,3],[6]]]] [[5,[]],[],[[0,4,1],4,[],[]],[[[1,7,3]],4,3],[8,[[9],[0,4,4,2],[10,6,4],[3],4],[4,[],[]]]] [[5,4,1,[10,2]]] [[4,[]],[6,[[1,2,3,10,9],[5,0,2,2,2],1,5,[8,8,8,9,3]]],[[[4,1,0,5],3,[2,10,8,5],[1],[4,9,6,5]],7,8,[2,4],6],[6],[]] [[[[1,9],[],[3,4,0]],[[6,1,6],0,4,8,5],6],[2,8],[[8,[7,10,5,0],9,[2,0,9,7,3]]]] [[0,[5,[],0,[],4]],[[3,5,[0],[10,10,2,5]],[[1,5],[6],4,0]]] [[[[3],[4,9,8,4,8],[]],6,[[3,5,6,9],5]],[[10,[3,7],[],[1,7,7,4,4],[3,9,4,1]],[0,1,5],4,7,[0,3]],[],[[],[[3,1,8,7]],[[9,9,10],[9,8,7,10],[9,2,0,5]]],[0,[[1,1,6],9,9,4]]] [[[0,10],[],[],2,[]],[[],5,[10],10],[5],[4,[[2,2,0,3],[0,10,9,4,9],[8],[7,8,9,6,3]],[[0,4],[3],[0,8,10,3,8]]]] [[1,[7],[6],7],[[],[1,[10],[3,1]],8],[[[9,1,8],2],0,10,3,3],[4,[[10,7,9],4],[6,10,10,2,9],4,[5]]] [[5,[],[[8,7,6,4],3,[5,2]],7,[[7,3,1,5],[7,8,2,1]]],[4,1,8],[[10,5],10,[5],3],[[3,[1,9,10,9,0],9,[5],7],10,10,[[7,10,0,10]],[8,[3,9],5,[],10]],[[7,[9,6,6,9],7,7,[3,1,1]],10,4,[[]],6]] [[7,[[6,4,5],10],6,[3,6,[8],[6,4,5],0],[[9,0,7,8,10],10,[4]]],[8,1,8,7],[[[],[0,1,0,2],0,[10,6,1,9],4],[[10,2,5,6,8]]],[]] [[]] [[[6,5,10,1,2],[6],3,5,1],[],[[9],7,[[],[5,3,8,3,6],0],5]] [[[[1],[3],[7,3,2,9]],[[5,1,0,7],[],1],[]]] [[],[[1],7,[8,[3,0],[0]],[1,[10,3,9],[],0]],[[]],[5,10],[[8,[5,10]],4,8]] [[[2,3,[6],5],[[6,9],[9,2,2],[9,3,2,0],[6,5,9,3],[5]],0,[[8,8,7,5],[9],9],[]],[[9,8,10],[4],4,9,[8,[],10,2,5]],[5,[],0,2],[[]]] [[8,[1],[6],0,10],[[8,[3],3],7,[[8,1],7,[10,2,0,1],[10,2],2]],[4]] [[8,10,9],[[],4,[10,[7,7,7],[],6],[]],[4,8,5,7]] [[[[9,1,1,8],5]],[[1,6,4,0,5],8],[],[[],5,[9,[]]]] [[[3,3,6,0],2,9,[[3,6,10],[],7,[3],[8,1]]],[[[0,1,10,2,0],3,4,8],[],[[4],[10,10],[9],9],[0],5],[[],[0,1,1,[5,2,1]]],[1]] [[[5,[2]],[1],3,3,6],[[[3,9],[8,10,4,3,4],10,[10]],6,[[6,9,2]],6,8],[[[],4,5,[10,6,0,2],[8,0,7,6,9]],[[6,8],8,5,6,[]]],[[[9],2],[9,[],[0,0,7,3,3],6],6,6,3]] [[[1],10],[[],7],[[[]],7,[[1,3],[4,2,9,10,5]],[[4,1],1]],[[[10,3,5,6,4],10,3,[6,4],0],[2],8,[0,[8],6,[],[6,4,9]]]] [[[3,2,9],[[3,0],10]],[[6,3],[[6,9,0],[6,9,10,6],[3,9],[7,4,8,5,9],[4,1,4,3,1]],[8],[6,8,[10],8]]] [[7],[[],[],6],[[[7,8,5,6,5],8,[2,8],9,[4]],0]] [[[],3,[[3,1],[1,5,4],[8,6,8,5],[5,7,4],[]],3,9],[6,1,[],[]],[[],5],[1,[5,6,[9],[0,2,6,3,7],[7,5,1,1]],[3,4],[[7,3],5,2]]] [[10,[]]] [[[[]],[4,[],[1,0,2,2]],[6,[],5,[1],[6,2,7]],[4,9]],[[4,[2,6,2,5,3],[1,8,10],10,[]],1,10,5],[[1,3,7],0]] [[],[],[5,4,0,10,7],[2,[[],2,0,[7,4,7,7,10],[]],[]]] [[[0,1],[],6,[10,4,[1,10,5],[8,5,7],7]],[2],[]] [[],[8,[[],8,[3]],7,3],[1,0],[[],3,2,[]],[]] [[[2,[8,9,10],[],[4,5,10,0,3]],6,[[]],8],[[10,[5,10,10],[0,3,2,0],8],[7,[8,9]],3,7,[[4,3,6,4,0],2,6]],[3,[5]]] [[[[0,1,3,3],7,[9,9,1,5,0],2,9],[5,[5,9,1,2,3],1],6,[[10,0],[8,10,8,4],3],1]] [[[0,7,[8,5,5,6,0],[],8],[]],[0,2,0,[9,1,[6,10,1,9,2],[0,7,10,1,7],9],10]] [[[8],[[3,0,9],[10,0],1],[[6,3,7,5],[]]]] [[[],1,[[8,2],[4],9],3,1],[]] [[],[],[[2],[3],[[10],10,0,[4,1,7,2,10],9],2,[4,9,[4,6,6,1,2],9]]] [[10]] [[],[10,[5],[],[6,[2,4,4,8,9],[0,0,8,9],[8],4]],[5,[],7,3,[[5],[8,9,1],7,[9]]],[6,5]] [[[3,[],[],[3],[6,1,4,4]],5,[],6],[[[6,6,2]],5,[5,5],7],[[[9,8,1,10,0],1,[2,10,0,9,6]],1,4,9]] [[0],[[7]]] [[[[0,4],[0]],[],[0,4,0,[5,4]],5],[[],[7,8,4,[7],[10,5]]],[1,1,[[],[],[3,0,1,3]],6],[[],[],7,7,8]] [[[[1,10,0,1],[7],[2,0,6,3],[],[4,8,5,8,6]],7,[6,9]]] [[2,0,[[8],1],6,[1,5]],[4],[],[1,9,9]] [[2,[10,[9,3,6,2],[7],4,5]],[[],9,10],[[],2,[4,[0],[7,5,3,2]],8,10],[9,[1,4,2],[[3,5,6,4,0]]]] [[3,[9],0,8],[[[7,3],[4,6,6],2,[],[2,5,10,3]]]] [[[[6,10],4],[3,[6,10,8],[2],[0,2],[8,5,9,6]],7,3],[[[8,3,5]],[2,[10,7,1,4],5]],[[[7,1,7,8]],[2,[1,6,7,7,3]],10],[[10,4,[6],[],7]]] [[1,[[10,5,2],[5]],0,[1,[7,1,4,9]],6],[],[[[4],[9,6,4]],[[5]]],[[[5,2],10,[10,5,10,9],[5,7]]]] [[1,[4],4,2]] [[],[8,[6],1,3],[[]],[[9,8],[[]]]] [[[7,[],6,9,2],[5,[9],1,8]],[6],[10,1,4]] [[[8],9,[6],[],0],[[0,4,[8,9],[],8],4,[7,3,[],[6]],[[]],[[],[1,2,7],[]]]] [[4]] [[1,[[6],7,5]],[7],[1,10,5],[7,8,[[3],[1,1,5,1],2],[],[7,2,[1,10,5,4],0]],[]] [[[[]]],[0],[3,[5],9,8,[6,[8,5,2,4,10],[3,4,0],[7,2,4,5,5],[4,8,7,1,4]]],[10,[],[5,[3,6,6,7,3],5,6],7,[10,7,[]]]] [[2,5,2,2,[[4,2,0,8],[8,7],[1],3]],[[],[[7,5,5,2],[10,2],5,0],[[],3,7,6,9]],[2,[7,[5,6],[5,0,1,8]],3],[[[0,1,4,8,1],[0,0,7,2,1],5,[7,8,0],[]]],[2]] [[],[1,7,[[0,6]],[[6],[],8]],[2,9,8,8,2],[[[5,1],[8,10,6,4,1]],[],5,5],[1,7,0]] [[],[8,[1,[2,4,4]]],[[[6,10,4,4,10],7,[3,10,8,3,2],6]],[[1,[10,7],6,1],10,[9,[2],[5,1,4]],[3]],[1,6,7,9,[[9,9,9,2],3]]] [[[[2,1],[5,9,2],[0,8,5,2],4,[7]]],[3,[1,2,[],6],[7],[[],10],0],[9,8,7,2,7],[[[6,1,8,9]],[[9,6],[0,8,3],4]]] [[0],[],[],[5,7]] [[5,8],[[6,7,[2,0,1,4],[3,0,8,5,8],[]],8]] [[5,8],[2,5,[],5,[[9,9,0],[8,0,3,5,5],[5],[4,9,0,0]]],[9,[],7,7,2],[5,[[],1,8,[10,6,0,10],5],[8,2],2],[6,4,[[9,5,2,0,9],10,7,[0,4,0,2,2],[4,5,0]],[1]]] [[9],[2],[7,8,[8],7,[]],[[6,8,[7,8,5,3],[9,1,5]],5,8,2],[9,5,[[9,9,2],2]]] [[],[[9,[6,6,6,0,5],8,5,10],7,[1,[],9,5],[[4,8]]],[[],3],[[[],1],8,[[3],[10,7,9],3,[],9],9,[6,[5,3,8,1,1],10,[]]],[3,5,4,[8,10,[0,4,5,1]]]] [[],[],[7,[0,[0,6,6,9,4],[],[8,3]],3,7,10]] [[[]],[10,3,10]] [[4,[5]],[6,1,[[3],[7],[9,1],[0,4,4,10]]],[[[9],[],[3]]],[[[9,8,0],0,[]],2,5,[6,5,[4,7,4,6,2]]]] [[1,9],[[[1,9,9,0,8],[8],[5,8,6]],5,4,[3,2,0],5],[2]] [[5,[10],3]] [[10,5,[3,6,4,5],7,0],[9,2,[7,[]],[7]],[4]] [[[],[],[[],4,[5,4,7,9,9],5,3]]] [[[[5],[],[5,9,6]],[[10,0],[3],2,6,1],6,[10,[5,8,5,3,1],6,[0],3]],[[9,2,9,3],[[7,7],9,[9,3,3,2,1]],[7,1,[2,6,2]],0,8]] [[10],[3,6],[],[1,8,3,6,1],[0,[[],10,3,[10,8]],4]] [[[[5,10,5,6],[4]],4,7,[[],[],5,4]],[[2,6,4,8],[]],[[[10,6],[4],[4,7,3]]]] [[[3,[7,6]],[[8,8,0]],1],[1],[[],5,4,4],[[2,[4,10,2],[3,3,8,7,9],[6,2,5,8],1],[[10,4,1,4],1,[5,5,2,1],[9,9,3]],[2,[7,8,4],[5,1,1,2],[],3]]] [[1,6,2,4],[1,[],8,[7,6,[5,4],10]],[0],[0,[8]],[[],4]] [[[1],[0,9,[10,2,2],[6,9,9]]],[[1,[3,3,5,8,10],[],1],[],4],[[[0,2],5,[1],[],7]],[3,7,[]]] [[8],[0,[7,6,2,[6,5,0]],[10,3,[],[1,6,4,4]],[6,[1,7,7],10,0],10],[9,[[5],[10,6,9,2],1,9],3],[[9,10,1,[10,9,3]],6,[0,[4,5,10],7],6]] [[4,[3,[9,8,10,2,6],[7,7,2,5,0],[6,9,8,6]]],[4,7,[]],[[4,0,[0,10],7],[4,[6,7,8,7],[7,0,1,0,9]],4],[9,[[6],5,6,4]]] [[9,7,[9]],[],[[[10,7,10],[1,9,5],[],[]],9],[[[3,9,2,1],8,[],[7,7,6,3],1],[[0,7],10,0],10,[10]],[[],[[8,4],0,[],[8,7,0]],[[9,3,6,0,4],9,[1,7,0,7,10],[]]]] [[[8],8,4,9]] [[],[9,8],[7,3,[],3]] [[[[5],1,4,3],5,[[0,9],4,[5,10,6,2,3],8],[6,3]],[9,2,1,[3,[1],[],4]],[5,[[0,7,9,5],[1,4,0,5],3],[1]],[6,7],[1,10]] [[[2],1,5,[9,[9,0,9],[],10]],[0,0],[0,[1,8]],[]] [[3,[]],[1,[4,6,10,6],[8,[3,1],8,6]],[10,3]] [[[2,4,8],7,[],[]],[4,[],2,[[3,5,4,7,9],[4,4,1]],[4,[0,9,6,5,8]]]] [[0,[7],[2,[5,7]],6,[3]],[0,[],[3]]] [[[8,[],[10,3,8],[3,1,2,10]],1,[9]],[[2,10,3,8,[3,1,5]]],[8]] [[5]] [[9,8,[[1,9,3,5],[9]],4,2],[7,5],[2,[1,[]]],[4,[[7,8],3,7,[3,2,6],[9,0,4]],9],[[[2,2,7],7],[[7],[2,2,9,10]]]] [[6],[10,[[2,7,3,8],[5],8,9],[0],10],[[[1,5],[1,4,0,2],[10,8,9]]],[2]] [[10,[],[5,[1,4,1],6],[[8,3,0,8],[2]]],[1,[[],[8],[]],10,9,10],[]]"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day13Kt.class", "javap": "Compiled from \"Day13.kt\"\npublic final class cz.wrent.advent.Day13Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n ...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day12.kt
package cz.wrent.advent fun main() { println(partOne(test)) val result = partOne(input) println("12a: $result") println(partTwo(test)) println("12b: ${partTwo(input)}") } private fun partOne(input: String): Int { val map = input.parse() val start = map.entries.find { it.value.specialArea == SpecialArea.START }!!.key map[start]!!.steps = 0 process(map, start) { (0..it + 1) } return map.entries.find { it.value.specialArea == SpecialArea.END }!!.value.steps } private fun partTwo(input: String): Int { val map = input.parse() val start = map.entries.find { it.value.specialArea == SpecialArea.END }!!.key map[start]!!.steps = 0 process(map, start) { it - 1..Int.MAX_VALUE } return map.entries.filter { it.value.height == 'a'.code }.minByOrNull { it.value.steps }!!.value.steps } private fun process(map: Map<Pair<Int, Int>, Area>, start: Pair<Int, Int>, moveRange: (Int) -> IntRange) { var next = listOf(start) while (next.isNotEmpty()) { val n = next.last() next = next.dropLast(1) val neighbours = n.toNeighbours() neighbours.forEach { neighbour -> if (map[neighbour] != null && map[neighbour]!!.height in moveRange(map[n]!!.height) && map [neighbour]!!.steps > map[n]!!.steps + 1) { map[neighbour]!!.steps = map[n]!!.steps + 1 next = next + neighbour } } } } fun Pair<Int, Int>.toNeighbours(): Set<Pair<Int, Int>> { return setOf( this.first to this.second + 1, this.first to this.second - 1, this.first + 1 to this.second, this.first - 1 to this.second ) } private fun String.parse(): Map<Pair<Int, Int>, Area> { val lines = this.split("\n") val map = mutableMapOf<Pair<Int, Int>, Area>() lines.forEachIndexed { j, line -> line.toCharArray().map { it.code } .forEachIndexed { i, height -> if (height == 'S'.code) { map[i to j] = Area('a'.code, specialArea = SpecialArea.START) } else if (height == 'E'.code) { map[i to j] = Area('z'.code, specialArea = SpecialArea.END) } else { map[i to j] = Area(height) } } } return map } private data class Area( val height: Int, var steps: Int = Int.MAX_VALUE, val specialArea: SpecialArea? = null ) private enum class SpecialArea { START, END } private const val test = """Sabqponm abcryxxl accszExk acctuvwj abdefghi """ private const val input = """abcccccccaaaaaaaaccccccccccaaaaaaccccccaccaaaaaaaccccccaacccccccccaaaaaaaaaaccccccccccccccccccccccccccccccccaaaaa abcccccccaaaaaaaaacccccccccaaaaaacccccaaacaaaaaaaaaaaccaacccccccccccaaaaaaccccccccccccccccccccccccccccccccccaaaaa abcccccccaaaaaaaaaaccccccccaaaaaacaaacaaaaaaaaaaaaaaaaaaccccccccccccaaaaaaccccccccccccccaaacccccccccccccccccaaaaa abaaacccccccaaaaaaacccccccccaaacccaaaaaaaaaaaaaaaaaaaaaaaaacccccccccaaaaaaccccccccccccccaaacccccccccccccccccaaaaa abaaaaccccccaaaccccccccccccccccccccaaaaaaaaacaaaacacaaaaaacccccccccaaaaaaaacccccccccccccaaaaccaaacccccccccccaccaa abaaaaccccccaaccccaaccccccccccccccccaaaaaaacaaaaccccaaaaaccccccccccccccccacccccccccccccccaaaaaaaaacccccccccccccca abaaaaccccccccccccaaaacccccccccaacaaaaaaaacccaaacccaaacaacccccccccccccccccccccccccccciiiiaaaaaaaacccccccccccccccc abaaacccccccccccaaaaaacccccccccaaaaaaaaaaacccaaacccccccaacccccccccccaacccccccccccccciiiiiiijaaaaccccccccaaccccccc abaaaccccccccccccaaaacccccccccaaaaaaaacaaacccaaaccccccccccccccccccccaaacaaacccccccciiiiiiiijjjacccccccccaaacccccc abcccccaacaacccccaaaaaccccccccaaaaaacccccacaacccccccccccccccccccccccaaaaaaaccccccciiiinnnoijjjjjjjjkkkaaaaaaacccc abcccccaaaaacccccaacaaccccccccccaaaacccaaaaaaccccccccccccccccccccccccaaaaaaccccccciiinnnnooojjjjjjjkkkkaaaaaacccc abccccaaaaacccccccccccccccccccccaccccccaaaaaaaccccccccccccccccccccaaaaaaaaccccccchhinnnnnoooojjooopkkkkkaaaaccccc abccccaaaaaaccccccccccccccccccccccccccccaaaaaaacccccccccccccccccccaaaaaaaaacccccchhhnnntttuooooooopppkkkaaaaccccc abccccccaaaaccccccccccacccccccccccccccccaaaaaaacccaaccccccccccccccaaaaaaaaaaccccchhhnnttttuuoooooppppkkkaaaaccccc abccccccaccccccccccccaaaacaaaccccccccccaaaaaacaaccaacccaaccccccccccccaaacaaacccchhhnnnttttuuuuuuuuupppkkccaaccccc abccccccccccccccaaccccaaaaaaaccccccccccaaaaaacaaaaaacccaaaaaaccccccccaaacccccccchhhnnntttxxxuuuuuuupppkkccccccccc abcccccccccccccaaaacccaaaaaaacccaccccccccccaaccaaaaaaacaaaaaaccccccccaacccaaccchhhhnnnttxxxxuuyyyuupppkkccccccccc abcccccccccccccaaaaccaaaaaaaaacaaacccccccccccccaaaaaaaaaaaaaccccccccccccccaaachhhhmnnnttxxxxxxyyyuvppkkkccccccccc abcccccccccccccaaaacaaaaaaaaaaaaaaccccccccccccaaaaaacaaaaaaaccccccccccccccaaaghhhmmmttttxxxxxyyyyvvpplllccccccccc abccacccccccccccccccaaaaaaaaaaaaaaccccccccccccaaaaaacccaaaaaacccaacaacccaaaaagggmmmttttxxxxxyyyyvvppplllccccccccc SbaaaccccccccccccccccccaaacaaaaaaaacccccccccccccccaacccaaccaacccaaaaacccaaaagggmmmsttxxxEzzzzyyvvvppplllccccccccc abaaaccccccccccccccccccaaaaaaaaaaaaacaaccccccccccccccccaaccccccccaaaaaccccaagggmmmsssxxxxxyyyyyyvvvqqqlllcccccccc abaaacccccccccccccccccccaaaaaaaaaaaaaaaaacccccccccccccccccccccccaaaaaaccccaagggmmmsssxxxwywyyyyyyvvvqqlllcccccccc abaaaaacccccccccccccccccccaacaaaccaaaaaaacccccccccccccccccccccccaaaaccccccaagggmmmssswwwwwyyyyyyyvvvqqqllcccccccc abaaaaaccccccccccccccccccccccaaaccccaaaacccccccccccccccccaaccaacccaaccccccccgggmmmmssssswwyywwvvvvvvqqqlllccccccc abaaaaacccccccccccccaccacccccaaaccccaaaacccccccccccccccccaaaaaacccccccccccaaggggmllllsssswwywwwvvvvqqqqlllccccccc abaaccccccccccccccccaaaaccccccccccccaccaccccccccccccccccccaaaaacccccccccccaaagggglllllssswwwwwrrqqqqqqmmllccccccc abaaccccccccccccccccaaaaaccccccaaccaaccccccccccccccccccccaaaaaaccaacccccccaaaaggfffllllsswwwwrrrrqqqqqmmmcccccccc abacaaaccccccccccccaaaaaaccccccaaaaaaccccccaacccccccccccaaaaaaaacaaacaaccccaaaaffffflllsrrwwwrrrmmmmmmmmmcccccccc abaaaaaccccccccccccaaaaaaccccccaaaaaccccccaaaaccccccccccaaaaaaaacaaaaaaccccaaaaccfffflllrrrrrrkkmmmmmmmccccaccccc abaaaacccccccccccccccaaccccccccaaaaaacccccaaaacccccccccccccaaccaaaaaaaccccccccccccffflllrrrrrkkkmmmmmccccccaccccc abaaacccccccccccccccccccccccccaaaaaaaaccccaaaacccccccccccccaaccaaaaaaacccccccccccccfffllkrrrkkkkmddddcccccaaacccc abaaacccccccccccccccccccccccccaaaaaaaacccccccccccccccccccccccccccaaaaaaccccccccccccfffllkkkkkkkdddddddcaaaaaacccc abaaaacccccccccccccccccccccccccccaaccccccccccccccccccccccccccccccaacaaacccccccccccccfeekkkkkkkddddddcccaaaccccccc abcaaacccccccccccaaaccccccccaacccaaccccaaaaaccccaaaccccccccccccccaaccccccccccccccccceeeeekkkkdddddccccccaaccccccc abccccccccccccccaaaaaaccccccaaacaaccacaaaaaaaccaaaaccccccccccaccaaccccccccccccccccccceeeeeeeedddacccccccccccccccc abccccccccccccccaaaaaacccccccaaaaacaaaaaccaaaaaaaacccccccccccaaaaacccccccccccccccccccceeeeeeedaaacccccccccccccaaa abccccccaaacccccaaaaacccccccaaaaaacaaaaaaaaaaaaaaaccccccccccccaaaaaccccccccccccccccccccceeeeecaaacccccccccccccaaa abccccccaaaccccccaaaaacccccaaaaaaaaccaaaaacaaaaaaccccccccccccaaaaaacccccccccccccccccccccaaaccccaccccccccccccccaaa abccccaacaaaaacccaaaaacccccaaaaaaaacaaaaaaaaaaaaaaaccccaaaaccaaaacccccccccccccccccccccccaccccccccccccccccccaaaaaa abccccaaaaaaaaccccccccccccccccaaccccaacaaaaaaaaaaaaaaccaaaaccccaaacccccccccccccccccccccccccccccccccccccccccaaaaaa"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day12Kt.class", "javap": "Compiled from \"Day12.kt\"\npublic final class cz.wrent.advent.Day12Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n ...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day11.kt
package cz.wrent.advent fun main() { val result = partOne(input, 20, 3) println("10a: $result") println(result == 51075L) println("10b: ${partOne(input, 10000, 1)}") } private fun partOne(input: String, rounds: Int, divisor: Long): Long { val monkeys = input.split("\n\n").map { it.parseMonkey() } val allMod = monkeys.map { it.testDivisor }.reduce { acc, l -> acc * l } for (i in 1..rounds) { monkeys.forEach { it.turn(monkeys, divisor, allMod) } } val sortedMonkeys = monkeys.sortedByDescending { it.inspections } return (sortedMonkeys.get(0).inspections * sortedMonkeys.get(1).inspections) } private class Monkey( val operation: (Long) -> Long, val testDivisor: Long, val trueMonkey: Int, val falseMonkey: Int, ) { val items = mutableListOf<Long>() var inspections = 0L fun add(item: Long) { items.add(item) } fun turn(monkeys: List<Monkey>, divisor: Long, allMod: Long?) { items.forEach { val worry = (operation(it) / divisor).let { w -> if (allMod != null) w % allMod else w } if (worry % testDivisor == 0L) { monkeys[trueMonkey].add(worry) } else { monkeys[falseMonkey].add(worry) } inspections++ } items.clear() } } private fun String.parseMonkey(): Monkey { val lines = this.split("\n") val startingItems = lines.get(1).replace(" Starting items: ", "").split(", ").map { it.toLong() } val operationData = lines.get(2).replace(" Operation: new = old ", "").split(" ") val operationNum = if (operationData.get(1) == "old") null else operationData.get(1).toLong() val operation: (Long) -> Long = if (operationData.first() == "*") { { it * (operationNum ?: it) } } else { { it + (operationNum ?: it) } } val testDivisor = lines.get(3).replace(" Test: divisible by ", "").toLong() val trueMonkey = lines.get(4).replace(" If true: throw to monkey ", "").toInt() val falseMonkey = lines.get(5).replace(" If false: throw to monkey ", "").toInt() val monkey = Monkey(operation, testDivisor, trueMonkey, falseMonkey) startingItems.forEach { monkey.add(it) } return monkey } private const val input = """Monkey 0: Starting items: 66, 79 Operation: new = old * 11 Test: divisible by 7 If true: throw to monkey 6 If false: throw to monkey 7 Monkey 1: Starting items: 84, 94, 94, 81, 98, 75 Operation: new = old * 17 Test: divisible by 13 If true: throw to monkey 5 If false: throw to monkey 2 Monkey 2: Starting items: 85, 79, 59, 64, 79, 95, 67 Operation: new = old + 8 Test: divisible by 5 If true: throw to monkey 4 If false: throw to monkey 5 Monkey 3: Starting items: 70 Operation: new = old + 3 Test: divisible by 19 If true: throw to monkey 6 If false: throw to monkey 0 Monkey 4: Starting items: 57, 69, 78, 78 Operation: new = old + 4 Test: divisible by 2 If true: throw to monkey 0 If false: throw to monkey 3 Monkey 5: Starting items: 65, 92, 60, 74, 72 Operation: new = old + 7 Test: divisible by 11 If true: throw to monkey 3 If false: throw to monkey 4 Monkey 6: Starting items: 77, 91, 91 Operation: new = old * old Test: divisible by 17 If true: throw to monkey 1 If false: throw to monkey 7 Monkey 7: Starting items: 76, 58, 57, 55, 67, 77, 54, 99 Operation: new = old + 6 Test: divisible by 3 If true: throw to monkey 2 If false: throw to monkey 1"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day11Kt$partOne$$inlined$sortedByDescending$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class cz.wrent.advent.Day11Kt$partOne$$inlined$sortedByDescending$1<T> implements java.util.Comparator {\n public cz.wrent.adve...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day18.kt
package cz.wrent.advent import java.util.* fun main() { println(partOne(test)) val result = partOne(input) println("18a: $result") println(partTwo(test)) val resultTwo = partTwo(input) println("18b: $resultTwo") } private fun partOne(input: String): Int { val cubes = input.split("\n") .map { it.parseCube() } .toSet() return cubes.sumOf { it.getArea(cubes) } } private fun partTwo(input: String): Int { val cubes = input.split("\n") .map { it.parseCube() } .toSet() val maxX = cubes.maxByOrNull { it.x }!!.x val maxY = cubes.maxByOrNull { it.y }!!.y val maxZ = cubes.maxByOrNull { it.z }!!.z val minX = cubes.minByOrNull { it.x }!!.x val minY = cubes.minByOrNull { it.y }!!.y val minZ = cubes.minByOrNull { it.z }!!.z val bigCube = mutableSetOf<Cube>() for (i in minX - 1 .. maxX + 1) { for (j in minY - 1 .. maxY + 1) { for (k in minZ - 1 .. maxZ + 1) { bigCube.add(Cube(i, j, k)) } } } val visited = blowAir(Cube(minX - 1, minY - 1, minZ - 1), bigCube, cubes) val inside = bigCube.minus(visited).minus(cubes) return cubes.sumOf { it.getArea(cubes) } - inside.sumOf { it.getArea(inside) } } private fun blowAir( cube: Cube, bigCube: Set<Cube>, cubes: Set<Cube>, ): Set<Cube> { val deque: Deque<Cube> = LinkedList(listOf(cube)) val visited = mutableSetOf<Cube>() while (deque.isNotEmpty()) { val next = deque.pop() visited.add(next) next.getNeighbours(bigCube).forEach { if (!(visited.contains(it) || cubes.contains(it))) { deque.push(it) } } } return visited } private fun String.parseCube(): Cube { return this.split(",") .map { it.toInt() } .let { Cube(it.get(0), it.get(1), it.get(2)) } } private data class Cube(val x: Int, val y: Int, val z: Int) { fun getArea(cubes: Set<Cube>): Int { return 6 - getNeighbours(cubes).size } fun getNeighbours(cubes: Set<Cube>): Set<Cube> { return setOf( Cube(x + 1, y, z), Cube(x - 1, y, z), Cube(x, y + 1, z), Cube(x, y - 1, z), Cube(x, y, z + 1), Cube(x, y, z - 1) ).intersect(cubes) } } private const val test = """2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5""" private const val input = """1,8,8 12,8,3 13,16,7 8,1,11 7,17,7 14,11,16 13,9,17 5,9,3 6,6,4 15,11,5 3,13,9 17,9,15 12,1,8 4,14,5 9,11,17 13,16,11 7,8,16 13,14,14 16,9,4 9,17,12 3,10,5 8,5,15 7,5,15 13,7,2 9,3,12 4,10,4 13,10,15 11,14,3 6,11,2 15,5,14 14,4,12 16,11,6 12,3,10 12,3,5 12,12,15 10,7,2 8,17,6 13,4,14 11,1,8 10,16,13 11,14,16 4,5,4 8,10,17 15,7,10 12,15,16 4,13,13 14,3,12 8,18,12 7,17,8 15,12,15 15,10,3 13,9,14 11,5,5 9,10,18 12,12,1 6,15,9 10,17,10 11,1,9 7,14,3 10,16,5 3,8,5 19,7,9 16,5,9 15,11,3 2,8,13 16,11,9 2,9,11 4,4,13 13,6,16 3,14,8 9,4,9 4,5,12 12,14,15 1,10,11 16,7,6 16,12,10 6,3,11 14,6,4 8,10,18 12,4,16 11,18,8 3,9,12 17,8,12 13,8,17 10,13,2 10,7,1 9,16,4 9,4,4 8,14,15 10,6,17 12,16,14 8,14,16 17,11,6 12,16,10 15,11,12 14,9,5 11,15,15 15,6,9 3,8,13 8,5,16 17,8,9 2,11,9 16,13,6 10,9,2 14,3,6 12,4,14 3,10,12 8,6,16 4,12,6 10,14,13 17,9,6 3,14,10 14,9,3 9,14,17 16,7,10 9,1,8 12,13,17 13,4,9 15,14,13 12,17,11 7,14,6 11,16,12 11,17,13 16,14,13 9,5,3 6,4,14 13,16,6 6,9,2 15,12,14 9,14,5 10,12,3 3,5,11 17,11,12 2,8,12 5,7,3 15,5,6 10,14,16 12,4,4 16,7,14 13,9,3 11,15,3 10,15,15 2,12,13 8,12,17 6,15,14 12,14,5 14,5,14 8,10,1 11,6,4 8,15,5 17,7,10 9,11,0 5,16,8 10,10,18 11,14,15 4,7,6 8,2,9 16,13,7 8,7,2 15,14,4 12,18,9 17,9,13 11,10,17 15,13,11 13,2,8 3,13,8 11,16,5 16,8,5 12,13,16 9,2,12 8,17,9 7,1,10 16,4,7 9,1,10 16,10,14 16,6,10 16,13,11 3,4,11 3,12,6 3,8,3 14,12,14 10,15,2 12,5,3 11,2,10 10,2,14 6,17,11 15,14,9 6,16,7 14,13,13 4,11,5 11,17,7 3,10,7 5,9,5 6,9,1 14,14,4 9,4,17 9,5,15 3,9,5 13,12,17 13,16,12 7,6,16 11,15,5 8,17,7 8,4,15 13,2,12 10,13,17 4,6,14 4,6,13 5,4,9 7,12,17 5,10,14 17,12,9 10,18,9 9,12,14 7,9,1 14,14,8 7,2,12 3,15,9 4,14,7 2,12,11 13,4,12 3,11,12 2,6,11 6,5,3 5,5,5 4,10,13 11,2,8 10,11,17 16,4,10 16,11,11 9,2,10 15,15,11 15,4,9 4,12,14 6,11,16 12,17,6 15,13,15 7,8,3 14,8,14 7,17,10 4,7,8 9,2,8 13,13,18 10,3,5 3,8,10 9,7,17 14,11,3 16,12,6 1,9,7 16,10,6 12,18,10 12,15,13 9,16,6 9,17,14 8,4,4 12,4,3 6,8,17 3,12,10 7,7,3 7,6,3 4,10,15 15,3,7 6,7,4 8,16,12 16,10,4 14,9,4 12,9,17 16,7,7 3,11,7 14,12,5 17,7,7 12,16,11 9,12,5 14,15,7 7,6,15 13,4,6 14,15,8 11,11,16 16,15,9 3,5,7 6,5,6 3,7,13 14,13,15 5,15,6 7,16,5 10,4,7 7,5,4 7,15,4 8,9,2 11,2,6 15,13,13 17,10,6 8,16,4 13,12,12 5,16,12 10,17,12 5,11,15 16,7,5 8,18,10 16,10,11 15,13,9 15,14,14 5,8,3 9,6,3 4,7,15 4,17,9 15,6,4 7,15,5 6,12,15 10,16,6 9,13,17 11,2,9 5,6,14 5,9,17 14,13,14 9,3,13 5,8,16 16,5,13 11,14,14 10,14,17 14,3,7 15,4,7 15,16,9 7,15,14 9,7,4 9,3,15 7,16,6 3,7,11 7,6,2 10,4,4 14,7,16 9,17,11 14,7,3 15,3,10 8,4,2 11,5,3 13,15,8 12,2,10 13,15,14 13,8,1 15,7,5 4,7,14 13,12,4 5,17,10 4,8,16 6,12,2 3,8,11 7,10,17 5,11,17 2,9,12 7,18,7 9,3,11 5,14,6 4,15,12 5,8,7 2,9,4 8,4,10 12,12,2 12,4,6 14,10,15 13,17,7 10,8,1 16,6,12 16,11,14 14,3,8 15,12,13 5,10,3 14,14,12 16,9,14 3,12,5 13,15,6 7,5,3 12,13,3 5,8,15 17,5,8 8,3,6 17,7,8 8,3,13 12,10,4 12,10,17 15,12,6 10,0,8 6,18,10 14,16,10 9,5,4 6,15,15 9,10,16 12,6,16 10,8,17 5,14,9 6,13,16 11,2,7 2,12,7 11,3,4 7,3,14 16,10,15 6,15,13 12,2,12 7,9,16 12,11,17 8,10,2 5,6,3 11,7,16 13,10,17 12,5,17 15,12,4 14,15,14 4,14,9 2,8,11 8,8,17 7,13,16 15,9,14 16,8,15 11,4,16 14,7,15 4,12,15 4,3,11 15,7,11 12,3,13 11,5,16 10,14,15 17,10,5 14,9,15 4,7,5 13,11,1 14,11,14 3,7,7 3,5,13 4,4,10 2,8,9 5,13,3 3,13,10 5,7,15 9,12,1 18,9,13 16,13,10 5,7,4 11,4,5 3,14,13 14,5,15 2,7,10 12,13,4 9,17,7 6,2,11 10,5,3 11,1,11 6,9,3 13,6,14 12,17,13 5,13,16 3,8,4 8,13,2 13,12,1 16,14,12 9,4,6 10,2,6 4,7,4 9,12,2 12,11,1 6,13,15 8,16,14 10,3,6 16,10,8 12,16,9 6,18,9 8,6,4 14,16,12 11,6,16 3,15,7 4,7,7 3,9,11 4,5,7 17,8,5 9,12,18 7,12,3 3,9,14 14,5,7 10,0,11 15,7,3 8,16,13 8,4,5 18,11,11 12,10,3 3,15,13 17,13,7 2,12,8 16,4,11 13,11,17 11,6,3 3,13,4 12,6,4 12,6,5 3,5,6 5,15,13 16,10,5 9,14,16 18,7,8 7,11,3 4,9,14 7,3,5 16,10,9 8,4,16 16,14,9 15,6,15 6,16,6 11,10,1 7,2,13 8,2,14 6,6,15 14,14,15 17,10,12 5,4,15 17,13,5 3,5,10 2,7,7 15,16,8 3,13,12 5,3,11 17,8,11 10,5,2 14,6,15 8,17,13 10,9,18 2,10,9 14,15,5 15,4,8 10,10,16 16,10,13 9,14,3 10,5,4 4,16,10 14,4,5 2,12,10 5,11,5 17,13,11 2,11,13 17,10,7 17,6,10 8,12,18 16,10,7 7,12,16 5,17,11 11,13,3 9,5,16 10,14,5 13,12,16 16,8,8 2,12,9 7,14,14 4,15,6 8,14,3 2,12,12 4,11,16 6,7,16 9,7,16 10,13,4 16,6,8 10,18,5 3,6,8 8,5,3 11,13,2 10,3,15 10,11,1 13,5,5 1,10,9 9,3,8 9,6,16 5,3,6 9,4,14 12,3,14 4,5,6 13,17,12 18,10,7 7,13,15 17,9,14 4,6,3 9,16,9 10,8,18 11,4,4 17,14,11 13,3,13 10,15,5 2,7,8 11,7,2 6,10,17 16,9,8 13,14,13 13,14,4 9,2,13 2,13,9 14,6,5 4,13,6 15,5,12 15,15,6 9,10,2 16,8,11 15,13,4 2,11,11 7,10,2 16,13,8 13,6,4 6,14,15 6,12,4 17,6,8 5,12,16 5,15,11 4,8,4 14,10,16 11,1,12 15,12,5 11,10,3 5,15,12 15,7,7 10,18,13 10,17,14 9,18,7 9,11,2 12,14,16 13,5,3 18,7,11 13,18,9 6,16,12 5,8,13 7,2,11 15,8,15 15,10,7 10,14,3 16,13,15 4,8,14 9,11,16 12,6,3 11,2,5 7,4,15 7,2,8 13,5,15 6,10,3 4,14,6 18,9,11 1,8,9 7,4,8 12,2,6 14,9,7 12,3,9 2,9,13 1,8,10 3,13,5 16,11,4 10,11,2 5,3,8 8,16,7 13,10,3 17,8,6 17,12,5 11,12,2 7,2,10 4,9,15 10,17,13 3,12,15 10,6,3 16,12,8 15,10,15 9,17,13 11,8,3 9,14,2 12,3,12 11,16,7 3,6,12 9,16,8 11,17,11 6,9,18 13,2,7 4,7,11 15,8,10 8,4,12 2,9,6 6,12,16 11,16,14 4,8,7 12,15,5 9,3,6 12,3,8 15,2,10 1,11,12 17,12,11 5,5,15 17,14,10 4,9,5 14,6,8 13,5,14 8,5,17 1,9,11 3,10,14 16,7,11 15,11,2 11,14,17 7,14,16 4,9,16 15,8,3 3,9,4 6,7,3 8,13,15 5,10,15 17,7,6 3,7,6 7,15,15 17,6,7 11,15,2 14,13,4 4,4,12 8,17,8 9,11,1 16,8,4 18,8,9 11,18,10 3,9,15 5,2,11 5,10,4 12,8,18 7,16,13 12,16,12 5,6,7 7,8,17 16,6,11 12,18,11 14,8,5 15,14,7 17,7,12 5,11,11 8,2,5 12,1,12 3,9,6 15,7,6 13,15,3 7,12,14 10,4,2 13,15,5 2,13,13 14,5,5 16,12,7 5,14,12 12,12,3 16,14,11 2,14,10 14,16,5 15,5,9 4,12,5 19,8,8 16,5,10 6,3,7 10,2,12 11,17,9 8,11,15 9,8,17 6,2,9 9,1,7 9,2,16 9,13,15 17,14,13 3,6,6 5,14,7 7,10,3 17,9,12 10,3,13 14,12,12 7,16,14 8,2,11 8,13,17 5,12,15 9,4,13 3,5,8 2,10,5 4,15,11 13,2,9 3,12,14 3,5,9 8,16,6 3,9,7 14,9,16 13,17,8 10,2,8 6,15,10 5,14,5 16,8,10 5,12,4 14,14,5 3,7,12 4,8,12 15,4,14 4,4,8 14,5,12 12,1,10 13,3,6 4,14,14 8,5,4 14,4,6 11,6,2 6,4,4 9,12,17 4,13,12 8,4,6 5,5,16 2,6,7 15,13,12 6,2,8 16,12,15 16,11,13 10,12,16 7,17,5 11,13,4 10,16,16 10,15,7 12,13,2 4,3,8 7,3,7 13,8,3 11,15,17 13,16,10 11,12,4 16,15,11 1,8,7 3,11,4 6,9,16 10,17,11 6,15,7 12,15,4 6,9,17 7,13,1 14,16,8 3,6,9 4,16,12 5,9,2 15,12,3 5,6,5 9,12,4 7,10,1 6,3,12 10,3,8 14,4,15 5,4,6 7,13,3 17,7,13 15,13,6 6,4,9 4,5,13 8,8,2 3,12,11 13,2,10 15,7,15 0,11,7 17,11,13 17,10,8 4,7,3 2,11,7 11,17,8 7,4,10 6,6,14 8,5,14 15,11,4 14,8,15 4,3,9 10,4,12 14,16,11 2,9,7 15,12,9 5,11,3 10,2,13 9,2,14 5,9,4 3,7,5 15,6,14 5,15,8 7,4,7 6,8,16 2,15,12 16,14,8 9,7,13 8,14,17 13,11,2 4,9,13 14,13,12 7,10,16 11,16,13 13,14,5 2,8,6 15,13,10 15,5,5 18,7,10 17,13,9 6,16,9 4,14,13 11,15,4 15,11,15 15,15,9 14,8,4 10,17,6 15,13,7 6,8,2 10,10,17 5,12,2 10,6,18 17,6,5 4,6,12 8,7,18 6,16,11 4,15,10 9,18,10 3,13,11 16,5,8 12,17,8 11,11,17 9,17,6 8,1,13 13,17,6 9,9,17 2,6,9 12,16,7 17,6,12 10,2,7 15,10,4 8,15,15 14,16,7 16,5,7 3,5,14 11,7,5 7,3,4 13,11,3 2,9,5 11,6,18 10,17,8 3,11,10 10,9,1 7,2,7 16,9,13 8,12,16 4,8,6 8,15,4 4,16,11 3,15,10 16,9,11 8,8,16 5,16,9 17,8,8 12,14,4 6,14,6 16,3,9 11,13,17 9,14,14 7,4,13 9,2,15 8,11,18 17,11,7 7,9,2 8,1,9 11,17,10 8,18,8 14,12,16 16,14,5 3,15,12 11,4,6 9,18,9 15,10,16 3,9,10 5,4,14 8,17,11 5,14,11 15,13,5 16,3,10 10,10,2 9,9,2 16,7,12 10,7,17 10,12,18 11,8,17 10,4,16 14,12,6 11,12,3 3,12,9 4,6,8 11,1,10 4,3,12 13,4,13 8,16,8 10,8,2 13,16,13 8,8,18 11,16,15 5,13,15 13,13,6 5,15,5 10,1,10 14,3,10 13,8,14 7,5,12 16,7,9 15,16,10 6,4,5 5,14,14 16,6,6 15,12,12 18,9,8 1,8,12 5,13,14 17,9,7 12,14,2 4,12,3 7,6,13 11,10,18 10,1,12 15,4,13 8,6,1 12,10,16 7,6,4 6,10,16 17,13,10 12,16,6 15,5,13 6,17,13 9,1,12 9,8,16 10,4,13 11,7,3 18,10,8 11,1,6 6,17,8 16,13,5 13,14,15 14,14,14 16,8,9 3,6,11 4,6,5 6,16,10 11,18,9 7,4,11 5,5,12 3,14,6 10,9,3 3,14,9 8,10,16 9,15,6 8,2,13 7,14,4 13,2,11 12,10,2 8,7,3 3,4,10 2,15,8 14,2,8 7,17,11 4,13,11 7,15,9 13,17,9 15,4,11 13,17,13 2,7,11 8,18,7 14,13,5 3,6,5 10,2,11 9,13,16 11,2,12 7,13,4 10,16,15 7,4,14 11,4,15 4,13,7 15,7,13 13,15,12 6,4,12 11,15,11 16,12,5 18,8,8 4,6,7 13,3,5 6,7,17 15,3,6 9,17,5 8,7,17 8,5,2 3,11,15 10,5,17 5,7,16 17,10,14 3,7,8 7,16,7 7,11,2 15,13,8 2,7,13 11,16,4 4,12,4 9,4,15 4,5,15 12,5,4 13,7,3 9,16,10 5,10,5 4,16,8 4,5,10 7,3,13 16,13,12 15,14,6 13,3,9 11,3,14 1,6,10 15,8,17 4,12,13 8,18,6 14,15,9 10,4,3 9,18,8 2,8,5 16,5,12 3,8,12 15,15,7 9,15,8 15,7,4 3,15,11 17,9,5 16,11,12 13,9,16 11,7,17 6,14,3 9,16,16 11,7,1 16,15,8 11,18,7 9,2,7 5,5,3 16,12,12 13,5,4 12,1,9 7,5,16 6,4,15 17,10,11 2,6,8 5,16,11 5,13,4 5,9,15 6,14,13 14,15,13 4,9,12 16,12,9 6,13,3 10,1,8 13,11,18 14,14,16 1,10,7 14,4,9 3,14,11 3,7,10 8,2,8 2,8,7 7,9,17 3,12,12 14,17,10 9,14,4 3,6,10 6,11,14 16,4,8 7,11,17 14,12,13 11,3,10 7,11,15 12,5,14 11,9,17 12,5,5 8,17,12 17,9,9 3,11,5 2,11,6 10,1,7 4,5,14 8,16,5 17,11,14 7,13,17 17,11,11 9,2,9 9,5,2 11,8,2 3,10,4 11,6,15 12,4,11 5,4,10 10,4,15 17,12,7 4,13,10 14,7,4 16,12,11 7,16,8 10,2,10 14,17,13 9,6,5 15,4,5 3,5,12 15,13,14 8,3,9 9,4,3 3,12,7 6,1,12 8,9,16 15,14,11 15,12,8 15,14,15 1,11,11 6,16,8 12,16,5 16,8,13 8,11,1 11,1,7 4,15,8 18,8,13 13,14,3 3,8,7 15,7,14 4,6,6 10,18,10 5,4,4 6,4,13 1,10,8 7,7,17 13,3,8 14,8,17 6,8,3 14,14,6 3,6,14 13,17,10 12,3,6 14,5,16 17,5,9 17,5,10 16,15,10 2,13,7 8,17,5 18,12,11 8,17,10 16,5,5 9,2,11 5,4,13 14,8,3 16,7,13 11,12,17 17,8,10 4,5,5 13,12,15 16,12,13 8,16,11 4,15,7 10,1,11 2,10,10 9,15,5 9,16,14 7,13,2 17,11,8 12,8,16 6,3,6 2,13,8 6,6,13 17,7,11 8,12,15 5,12,3 16,15,7 5,9,13 6,3,8 9,15,2 6,17,12 9,16,7 15,9,12 12,7,15 7,17,14 10,9,17 8,1,8 9,10,1 11,7,18 3,7,15 5,6,16 6,14,4 4,13,5 9,15,12 7,7,4 7,3,8 11,11,1 8,11,17 11,11,18 14,10,3 10,2,9 6,11,3 2,9,9 8,15,2 3,13,13 9,16,13 8,15,14 16,6,4 16,8,14 6,8,15 15,10,14 15,16,14 9,16,5 2,3,8 5,3,9 13,8,4 12,12,17 4,12,12 9,18,11 5,3,12 2,7,9 5,9,16 14,2,13 16,11,8 6,15,5 16,6,13 12,8,2 6,2,7 8,14,4 4,4,11 1,9,8 10,3,14 10,15,12 2,6,12 15,6,8 3,10,6 14,13,16 2,11,14 14,3,11 9,6,2 4,7,12 2,13,11 6,6,16 5,4,5 2,5,10 14,3,14 7,5,13 11,3,13 5,14,8 12,3,7 5,13,12 7,2,9 16,5,11 12,16,13 7,14,7 4,15,9 9,3,7 16,9,6 6,13,4 13,4,3 4,7,16 3,8,8 11,3,6 3,13,6 8,3,12 11,8,4 10,17,9 4,14,8 16,9,5 5,12,14 9,9,1 4,4,9 17,9,8 7,9,3 15,14,12 6,12,3 10,3,7 7,5,2 11,4,8 8,3,10 5,16,6 17,11,9 12,6,14 12,2,11 6,16,13 6,7,18 2,4,10 8,15,3 14,16,9 6,3,14 16,11,5 12,9,2 13,4,4 15,14,8 8,18,9 18,9,9 13,7,16 8,13,13 16,14,7 13,6,15 18,13,8 15,14,10 13,5,9 15,16,12 6,17,10 13,14,6 4,11,15 4,17,11 8,9,1 4,9,3 10,6,15 15,3,11 14,11,15 6,5,15 4,11,14 12,2,7 10,15,14 6,13,13 4,6,4 14,4,8 15,15,15 11,2,11 7,15,8 3,16,9 13,2,13 2,5,9 10,4,10 8,12,2 10,6,2 14,6,14 11,17,14 8,6,3 16,14,10 9,5,7 15,15,12 2,11,8 8,2,15 2,13,10 6,5,7 14,2,10 5,8,2 8,2,10 9,9,18 6,13,2 10,16,4 14,12,4 12,5,15 2,10,6 5,14,3 5,8,4 9,15,15 13,5,16 15,15,10 5,7,8 12,7,2 3,11,6 11,3,12 4,13,14 15,15,5 14,11,2 7,15,11 8,1,7 13,15,4 13,13,2 17,5,12 11,5,17 7,15,7 6,15,12 9,1,11 9,5,1 7,4,9 9,6,17 10,16,8 12,2,9 18,10,6 3,10,9 5,3,10 16,8,12 7,16,9 14,15,12 13,15,7 16,8,7 14,16,6 5,6,11 8,6,2 13,13,17 5,4,7 7,13,18 16,9,12 1,11,7 13,10,16 18,11,9 13,4,15 15,3,8 6,3,5 10,13,16 18,12,8 6,10,2 3,10,16 10,6,16 11,3,5 11,10,2 4,7,13 1,9,10 11,9,18 13,16,5 11,13,5 4,13,16 3,10,13 11,3,15 16,9,7 5,6,4 1,7,8 13,6,2 15,16,11 12,16,4 13,10,2 2,9,14 2,5,7 4,3,10 10,4,5 9,13,3 9,13,2 11,16,3 11,3,9 17,11,10 13,3,10 11,1,14 10,15,6 7,15,16 6,12,17 13,8,2 2,6,13 11,15,12 12,8,1 15,5,10 4,11,4 8,3,8 1,11,10 18,9,7 5,15,9 10,4,17 8,18,11 10,7,3 9,7,18 7,3,6 11,17,5 14,17,14 7,2,6 13,15,15 3,14,14 14,5,6 13,17,11 15,8,5 11,9,3 3,10,15 6,14,5 4,14,4 5,7,5 15,6,13 12,4,5 14,6,12 7,16,4 3,4,8 7,7,2 15,4,6 14,12,15 15,6,16 9,15,4 13,10,1 15,6,6 8,9,17 16,6,5 4,4,5 13,10,18 3,7,14 7,6,17 7,6,6 12,9,1 2,10,8 7,8,1 12,11,16 11,3,16 5,5,9 11,8,16 14,10,17 14,10,14 5,15,7 2,8,10 10,13,3 6,4,11 14,14,10 4,10,16 5,8,5 4,10,14 9,12,16 16,10,12 16,6,7 12,7,18 13,3,7 11,3,11 1,7,9 3,8,6 9,3,16 9,17,8 5,14,4 5,17,9 18,11,8 5,4,11 10,7,16 7,7,15 6,2,10 16,13,13 13,12,2 16,11,15 12,8,17 17,8,7 16,14,6 4,13,15 2,7,5 5,11,4 6,14,7 12,15,6 11,13,15 4,16,6 6,6,3 14,13,3 11,14,4 4,9,6 16,12,4 7,16,12 7,17,12 9,10,17 15,11,7 9,13,4 11,9,2 10,14,4 4,10,5 15,9,15 3,11,3 12,7,17 3,5,5 7,1,12 8,4,14 2,11,10 8,6,17 18,9,12 7,4,5 11,14,2 3,6,13 15,6,3 6,3,13 7,9,15 6,5,4 17,12,12 14,10,13 4,8,15 13,16,14 11,4,11 4,16,7 10,18,7 7,4,4 5,2,5 14,4,14 5,13,9 7,2,15 13,14,8 6,7,5 13,7,17 15,6,11 10,17,7 17,13,12 4,9,4 7,6,1 15,8,8 17,12,4 16,11,7 4,5,9 11,6,17 14,14,9 4,13,9 9,3,14 6,13,12 11,11,2 15,15,8 4,9,10 12,11,4 9,8,3 12,6,17 5,3,13 15,8,11 2,10,7 5,4,8 11,8,18 16,12,14 8,11,2 4,14,15 12,5,13 1,11,9 13,13,15 1,9,9 6,14,17 7,16,10 4,4,14 16,6,9 1,10,10 4,9,11 16,15,12 16,14,14 9,15,14 9,4,5 12,14,3 13,11,6 15,14,5 3,8,16 9,9,16 12,15,14 11,4,3 6,5,14 4,5,11 15,5,8 18,8,10 6,3,9 7,7,16 12,3,15 14,4,13 15,3,13 15,15,13 8,9,18 12,17,7 1,10,12 9,7,2 5,11,9 15,8,12 13,16,4 10,9,16 18,10,11 12,13,14 1,7,12 13,15,13 17,6,9 2,9,10 8,4,13 15,6,5 5,11,16 3,6,7 4,4,7 4,12,7 14,9,14 7,15,13 8,11,3 15,8,7 5,7,14 3,12,13 11,16,9 13,18,10 6,10,15 11,16,11 7,3,15 12,7,3 14,12,8 6,14,9 10,4,14 1,10,6 3,10,8 7,5,7 14,11,4 11,4,14 13,6,3 4,6,11 3,14,4 17,6,11 18,13,10 2,12,5 8,13,16 17,12,8 9,1,9 15,4,12 11,17,6 10,6,5 14,6,16 17,12,10 18,9,10 4,11,3 2,12,6 7,12,15 10,3,9 12,9,3 11,15,9 5,10,17 8,13,1 9,5,13 12,9,16 15,9,16 13,4,7 6,13,17 10,18,6 6,7,14 10,7,4 13,13,5 8,7,16 17,4,9 8,9,4 9,9,19 4,11,13 13,7,4 13,6,5 6,4,6 5,13,5 15,9,3 10,13,1 10,6,4 4,14,12 6,12,6 5,16,7 4,15,13 12,4,12 10,14,6 9,6,1 15,6,10 7,3,10 8,4,3 13,9,1 5,2,12 14,3,5 7,11,18 14,10,2 4,8,5 6,12,18 7,17,6 9,8,18 3,14,7 12,4,13 14,4,11 15,7,16 14,2,9 8,3,15 5,16,14 14,3,9 12,14,17 17,14,6 5,6,13 7,14,15 4,15,14 14,14,13 5,3,7 8,2,7 13,3,15 8,1,10 4,3,6 17,12,6 6,8,1 14,5,4 17,9,11 13,15,9 11,5,13 3,10,11 17,10,10 15,10,11 13,18,12 14,15,15 16,16,9 14,12,3 11,3,7 18,10,9 13,3,14 4,10,6 3,12,8 2,9,8 14,8,13 13,11,16 5,10,16 9,17,9 14,5,9 13,12,3 5,12,8 7,18,12 9,5,14 5,6,15 0,8,10 16,9,10 8,2,12 17,6,6 14,5,13 3,8,9 5,5,13 8,13,4 15,12,7 14,11,5 14,15,6 18,10,10 9,8,1 5,12,6 10,3,4 10,5,16 7,4,6 13,16,9 6,5,5 10,2,15 4,16,9 4,8,13 11,15,13 5,5,14 9,7,3 6,2,12 11,9,1 15,16,13 15,16,7 10,5,5 14,6,11 14,15,10 2,14,9 8,8,15 10,11,18 12,2,13 12,10,18 10,15,17 17,14,9 12,15,7 7,3,12 12,12,16 6,9,4 1,12,10 13,10,4 14,4,7 10,10,4 13,14,12 2,12,14 8,5,5 14,9,17 8,11,4 7,4,3 10,2,5 8,16,10 10,11,16 18,12,9 17,4,11 14,16,13 11,9,4 18,7,12 7,4,12 13,9,2 13,13,16 8,3,5 6,5,16 1,7,11 7,10,19 14,6,13 15,11,14 14,2,11 14,4,10 8,8,3 15,8,4 14,10,5 3,15,6 17,13,8 11,3,3 10,16,7 17,7,9 6,2,6 14,6,6 17,12,13 14,7,5 13,4,5 4,3,7 13,8,16 3,9,9 2,10,12 16,4,9 1,8,11 10,18,12 10,12,1 16,11,10 15,8,6 10,14,2 13,3,12 18,11,10 18,12,10 6,7,15 7,18,9 12,15,9 6,5,13 13,4,8 2,5,8 5,5,6 10,12,17 15,17,8 10,15,16 7,15,3 8,0,11 4,14,11 15,5,7 3,16,10 8,16,15 15,11,16 6,7,2 12,17,12 4,15,5 15,7,12 6,14,14 18,13,7 4,4,6 6,10,4 10,16,11 11,4,13 4,11,12 10,0,7 6,5,12 16,7,8 9,16,11 14,15,11 16,7,4 12,18,12 17,8,13 2,11,12 2,14,13 8,8,4 6,2,13 9,5,17 11,6,1 2,13,6 3,3,8 12,7,16 7,9,18 11,14,5 15,3,12 14,17,11 14,12,2 16,8,6 15,7,9 10,10,15 3,4,9 6,4,8 5,7,2 15,10,6 9,8,2 9,15,3 5,4,12 16,7,15 9,11,18 13,5,13 2,14,11 12,5,16 4,16,5 14,17,8 5,7,10 12,6,15 13,6,6 2,7,15 11,13,18 7,1,7 15,9,5 5,15,14 8,13,3 10,16,14 4,17,13 13,3,11 16,13,9 2,14,8 7,2,5 11,13,16 12,10,1 4,12,10 5,14,10 4,12,8 6,16,15 18,5,11 7,8,2 14,8,16 7,17,13 13,14,7 10,1,9 2,6,10 12,4,7 4,11,2 9,16,15 8,3,11 6,3,10 11,5,4 4,5,8 9,5,11 1,12,9 15,16,6 10,3,12 4,10,17 10,10,1 8,9,3 15,12,16 15,8,16 13,9,4 7,11,16 4,11,7 9,11,3 5,2,10 10,3,16 11,16,6 5,16,10 11,8,1 13,7,18 11,18,13 9,17,10 8,3,7 4,13,3 12,17,9 10,15,3 6,15,6 17,10,9 13,4,11 9,15,16 13,13,14 5,1,7 11,2,14 8,1,12 10,18,11 4,13,8 2,10,4 14,3,13 17,13,6 1,9,13 2,11,5 6,15,4 8,15,6 17,14,7 12,11,18 11,5,2 9,16,3 2,8,8 3,8,15 14,6,3 5,2,9 12,6,18 18,6,8 3,6,4 10,9,0 16,9,3 6,12,14 7,17,9 7,14,13 7,16,15 10,17,5 12,15,3 3,4,7 9,3,5 5,14,16 7,5,6 6,14,16 13,5,2 5,13,8 7,1,9 17,9,10 8,15,16 6,6,10 7,5,14"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day18Kt.class", "javap": "Compiled from \"Day18.kt\"\npublic final class cz.wrent.advent.Day18Kt {\n private static final java.lang.String test;\n\n private static final java.lang.String input;\n\n public static final void main();\n ...
Wrent__advent-of-code-2022__8230fce/cz.wrent.advent/Day5.kt
package cz.wrent.advent import java.util.* fun main() { val result = partOne(input) println("5a: $result") val resultTwo = partTwo(input) println("5b: $resultTwo") } private fun partOne(input: String): String { return moveCrates(input) { x, y, z -> moveCrates9000(x, y, z) } } private fun partTwo(input: String): String { return moveCrates(input) { x, y, z -> moveCrates9001(x, y, z) } } private fun moveCrates(input: String, fn: (from: Deque<String>, to: Deque<String>, num: Int) -> Unit): String { val (stacksInput, movesInput) = input.split("\n\n") val stacks = stacksInput.toStacks() val moves = movesInput.toMoves() moves.forEach { val from = stacks.get(it.from) val to = stacks.get(it.to) fn(from, to, it.num) } return stacks.map { it.peek() }.joinToString(separator = "") } private fun moveCrates9000(from: Deque<String>, to: Deque<String>, num: Int) { repeat(num) { val crate = from.pop() to.push(crate) } } private fun moveCrates9001(from: Deque<String>, to: Deque<String>, num: Int) { val crates = mutableListOf<String>() repeat(num) { crates.add(from.pop()) } crates.reversed().forEach { to.push(it) } } private fun String.toStacks(): List<Deque<String>> { val split = this.split("\n").dropLast(1) val cnt = (split.first().length + 1) / 4 val lists = (0 until cnt).map { mutableListOf<String>() } for (row in split) { var i = 1 var j = 0 while (i < row.length) { val char = row[i] if (char != ' ') { lists.get(j).add(char.toString()) } j++ i += 4 } } return lists.map { it.toDeque() } } private fun List<String>.toDeque(): Deque<String> { return LinkedList(this) } private data class Move(val num: Int, val from: Int, val to: Int) private fun String.toMoves(): List<Move> { val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") return this.split("\n") .map { regex.matchEntire(it) } .map { Move(it!!.groupValues.get(1).toInt(), it.groupValues.get(2).toInt() - 1, it.groupValues.get(3).toInt() - 1) } } private const val input = """[Q] [J] [H] [G] [S] [Q] [Z] [P] [P] [F] [M] [F] [F] [S] [R] [R] [P] [F] [V] [D] [L] [L] [W] [W] [D] [W] [S] [V] [G] [C] [H] [H] [T] [D] [L] [M] [B] [B] [T] [Q] [B] [S] [L] [C] [B] [J] [N] [F] [N] [F] [V] [Q] [Z] [Z] [T] [Q] 1 2 3 4 5 6 7 8 9 move 1 from 8 to 1 move 1 from 6 to 1 move 3 from 7 to 4 move 3 from 2 to 9 move 11 from 9 to 3 move 1 from 6 to 9 move 15 from 3 to 9 move 5 from 2 to 3 move 3 from 7 to 5 move 6 from 9 to 3 move 6 from 1 to 6 move 2 from 3 to 7 move 5 from 4 to 5 move 7 from 9 to 4 move 2 from 9 to 5 move 10 from 4 to 2 move 6 from 5 to 4 move 2 from 7 to 6 move 10 from 2 to 3 move 21 from 3 to 5 move 1 from 3 to 6 move 3 from 6 to 9 move 1 from 8 to 9 move 5 from 4 to 5 move 4 from 9 to 3 move 17 from 5 to 1 move 1 from 6 to 2 move 16 from 5 to 1 move 3 from 3 to 6 move 6 from 6 to 4 move 1 from 2 to 4 move 4 from 1 to 2 move 2 from 6 to 2 move 28 from 1 to 3 move 1 from 9 to 7 move 1 from 8 to 7 move 1 from 5 to 4 move 1 from 2 to 6 move 1 from 3 to 1 move 3 from 2 to 5 move 1 from 6 to 3 move 4 from 4 to 7 move 5 from 5 to 2 move 1 from 5 to 6 move 6 from 1 to 3 move 1 from 6 to 2 move 26 from 3 to 6 move 2 from 7 to 9 move 4 from 7 to 3 move 19 from 6 to 3 move 6 from 2 to 4 move 5 from 3 to 2 move 1 from 9 to 7 move 26 from 3 to 8 move 6 from 4 to 3 move 1 from 3 to 8 move 1 from 6 to 7 move 6 from 3 to 6 move 6 from 6 to 4 move 1 from 9 to 2 move 2 from 4 to 9 move 22 from 8 to 2 move 2 from 6 to 5 move 1 from 9 to 1 move 1 from 6 to 5 move 1 from 7 to 5 move 3 from 6 to 7 move 2 from 6 to 1 move 1 from 1 to 5 move 3 from 5 to 9 move 4 from 8 to 4 move 2 from 1 to 4 move 18 from 2 to 1 move 2 from 7 to 8 move 3 from 9 to 5 move 8 from 1 to 9 move 5 from 9 to 3 move 1 from 9 to 8 move 2 from 9 to 4 move 2 from 7 to 8 move 5 from 5 to 7 move 1 from 9 to 3 move 4 from 8 to 4 move 1 from 7 to 8 move 4 from 4 to 3 move 2 from 8 to 3 move 1 from 8 to 9 move 2 from 1 to 8 move 3 from 4 to 5 move 1 from 8 to 4 move 1 from 9 to 3 move 1 from 8 to 5 move 8 from 1 to 8 move 11 from 2 to 9 move 12 from 3 to 5 move 1 from 3 to 9 move 1 from 8 to 5 move 11 from 9 to 3 move 4 from 5 to 9 move 3 from 8 to 7 move 3 from 7 to 8 move 1 from 5 to 8 move 7 from 4 to 3 move 1 from 4 to 5 move 1 from 2 to 8 move 3 from 7 to 6 move 3 from 4 to 8 move 1 from 7 to 9 move 2 from 4 to 7 move 5 from 8 to 1 move 3 from 6 to 5 move 2 from 4 to 2 move 1 from 9 to 4 move 1 from 8 to 6 move 1 from 2 to 9 move 1 from 8 to 5 move 3 from 8 to 4 move 3 from 4 to 2 move 4 from 3 to 9 move 17 from 5 to 9 move 9 from 9 to 6 move 1 from 9 to 3 move 5 from 6 to 3 move 3 from 6 to 3 move 8 from 9 to 5 move 2 from 8 to 5 move 1 from 4 to 8 move 1 from 5 to 3 move 1 from 8 to 5 move 3 from 2 to 6 move 3 from 1 to 4 move 7 from 5 to 1 move 1 from 2 to 6 move 13 from 3 to 6 move 2 from 7 to 8 move 13 from 6 to 5 move 3 from 5 to 7 move 6 from 5 to 6 move 1 from 7 to 6 move 2 from 7 to 3 move 1 from 6 to 8 move 13 from 3 to 5 move 9 from 5 to 9 move 7 from 5 to 7 move 17 from 9 to 2 move 3 from 4 to 7 move 9 from 2 to 9 move 10 from 9 to 3 move 8 from 7 to 8 move 2 from 5 to 3 move 4 from 2 to 6 move 11 from 3 to 9 move 9 from 6 to 5 move 5 from 9 to 8 move 1 from 3 to 1 move 3 from 9 to 1 move 2 from 5 to 2 move 1 from 7 to 9 move 2 from 9 to 4 move 2 from 9 to 8 move 13 from 1 to 8 move 3 from 8 to 5 move 27 from 8 to 1 move 10 from 5 to 9 move 1 from 7 to 2 move 2 from 4 to 3 move 10 from 9 to 6 move 1 from 8 to 7 move 15 from 1 to 9 move 13 from 9 to 5 move 15 from 5 to 7 move 5 from 1 to 3 move 8 from 7 to 1 move 7 from 7 to 1 move 16 from 1 to 8 move 4 from 3 to 9 move 4 from 1 to 7 move 4 from 9 to 6 move 5 from 2 to 7 move 15 from 8 to 6 move 1 from 9 to 1 move 3 from 3 to 4 move 1 from 9 to 7 move 1 from 2 to 7 move 1 from 2 to 7 move 1 from 8 to 1 move 3 from 4 to 8 move 3 from 8 to 1 move 8 from 6 to 8 move 7 from 1 to 4 move 11 from 6 to 8 move 14 from 6 to 5 move 13 from 8 to 7 move 4 from 7 to 5 move 15 from 7 to 4 move 6 from 5 to 4 move 2 from 5 to 9 move 1 from 5 to 2 move 3 from 8 to 5 move 19 from 4 to 7 move 10 from 5 to 8 move 2 from 6 to 8 move 1 from 4 to 8 move 2 from 7 to 9 move 9 from 7 to 4 move 6 from 4 to 6 move 11 from 4 to 8 move 2 from 5 to 4 move 5 from 6 to 4 move 1 from 6 to 7 move 3 from 9 to 5 move 3 from 8 to 5 move 3 from 7 to 6 move 11 from 8 to 7 move 1 from 9 to 5 move 1 from 6 to 8 move 1 from 2 to 1 move 5 from 4 to 9 move 2 from 4 to 1 move 2 from 1 to 4 move 1 from 1 to 9 move 4 from 5 to 1 move 1 from 4 to 6 move 17 from 7 to 5 move 9 from 8 to 7 move 6 from 9 to 7 move 3 from 1 to 9 move 12 from 7 to 9 move 12 from 9 to 5 move 5 from 7 to 9 move 17 from 5 to 3 move 7 from 3 to 1 move 5 from 1 to 5 move 5 from 9 to 2 move 4 from 3 to 5 move 1 from 4 to 8 move 5 from 2 to 1 move 22 from 5 to 9 move 3 from 7 to 6 move 6 from 6 to 9 move 2 from 5 to 4 move 1 from 6 to 3 move 2 from 4 to 1 move 3 from 8 to 2 move 1 from 3 to 4 move 24 from 9 to 1 move 4 from 3 to 9 move 2 from 2 to 9 move 2 from 3 to 1 move 1 from 8 to 6 move 1 from 6 to 9 move 1 from 8 to 9 move 2 from 7 to 4 move 1 from 8 to 3 move 1 from 4 to 7 move 3 from 9 to 8 move 1 from 2 to 1 move 9 from 9 to 3 move 1 from 8 to 7 move 1 from 4 to 3 move 2 from 9 to 7 move 1 from 9 to 3 move 2 from 8 to 4 move 12 from 3 to 8 move 2 from 1 to 7 move 1 from 4 to 3 move 30 from 1 to 5 move 6 from 5 to 7 move 12 from 7 to 2 move 1 from 3 to 4 move 2 from 1 to 3 move 1 from 4 to 9 move 10 from 5 to 7 move 10 from 2 to 6 move 8 from 8 to 3 move 3 from 1 to 3 move 5 from 6 to 3 move 2 from 8 to 5 move 1 from 9 to 2 move 2 from 8 to 6 move 4 from 7 to 2 move 3 from 2 to 7 move 2 from 7 to 5 move 1 from 4 to 9 move 11 from 3 to 1 move 7 from 6 to 9 move 3 from 2 to 3 move 10 from 1 to 7 move 14 from 7 to 5 move 3 from 7 to 6 move 5 from 9 to 7 move 29 from 5 to 7 move 6 from 3 to 9 move 2 from 9 to 7 move 15 from 7 to 5 move 11 from 5 to 6 move 5 from 9 to 5 move 10 from 5 to 8 move 1 from 2 to 4 move 1 from 8 to 2 move 2 from 4 to 3 move 2 from 5 to 9 move 8 from 8 to 9 move 11 from 9 to 3 move 1 from 1 to 8 move 18 from 7 to 3 move 1 from 9 to 3 move 28 from 3 to 5 move 12 from 6 to 7 move 1 from 2 to 9 move 15 from 7 to 2 move 1 from 8 to 1 move 10 from 2 to 9 move 10 from 5 to 3 move 2 from 2 to 3 move 18 from 3 to 4 move 6 from 9 to 4 move 1 from 1 to 7 move 1 from 6 to 4 move 1 from 8 to 2 move 1 from 9 to 4 move 2 from 9 to 4 move 19 from 4 to 3 move 1 from 7 to 9 move 1 from 9 to 7 move 1 from 6 to 8 move 3 from 2 to 8 move 2 from 9 to 5 move 15 from 3 to 1 move 7 from 5 to 1 move 3 from 4 to 9 move 1 from 7 to 2 move 3 from 3 to 1 move 6 from 5 to 2 move 3 from 3 to 9 move 4 from 9 to 2 move 5 from 5 to 3 move 1 from 3 to 5 move 3 from 5 to 7 move 3 from 8 to 5 move 1 from 7 to 5 move 4 from 5 to 1 move 4 from 4 to 2 move 2 from 7 to 8 move 12 from 1 to 6 move 1 from 8 to 6 move 6 from 2 to 3 move 9 from 3 to 8 move 1 from 3 to 4 move 3 from 6 to 1 move 2 from 9 to 2 move 1 from 4 to 5 move 2 from 8 to 3 move 10 from 2 to 1 move 2 from 4 to 7 move 12 from 1 to 4 move 1 from 5 to 1 move 7 from 4 to 9 move 2 from 3 to 2 move 6 from 9 to 2 move 1 from 9 to 1 move 1 from 7 to 8 move 5 from 6 to 7 move 3 from 6 to 1 move 6 from 2 to 3 move 2 from 4 to 3 move 1 from 6 to 8 move 1 from 6 to 7 move 8 from 3 to 9 move 2 from 4 to 5 move 3 from 2 to 4 move 10 from 8 to 2 move 22 from 1 to 9 move 9 from 2 to 4 move 1 from 1 to 3 move 1 from 3 to 2 move 3 from 2 to 4 move 2 from 7 to 1 move 14 from 4 to 2 move 2 from 1 to 8 move 2 from 4 to 5 move 4 from 7 to 8 move 24 from 9 to 6 move 3 from 5 to 9 move 1 from 9 to 8 move 1 from 5 to 2 move 1 from 6 to 7 move 6 from 9 to 1 move 1 from 7 to 3 move 5 from 8 to 6 move 9 from 6 to 3 move 4 from 1 to 4 move 2 from 1 to 2 move 11 from 6 to 3 move 13 from 3 to 2 move 2 from 9 to 8 move 8 from 3 to 8 move 2 from 8 to 5 move 1 from 7 to 5 move 3 from 6 to 3 move 11 from 8 to 5 move 13 from 2 to 4 move 10 from 5 to 2 move 2 from 3 to 4 move 2 from 5 to 7 move 15 from 4 to 9 move 2 from 7 to 4 move 2 from 4 to 2 move 2 from 4 to 9 move 2 from 4 to 2 move 1 from 3 to 8 move 1 from 8 to 1 move 1 from 1 to 2 move 1 from 6 to 3 move 7 from 2 to 4 move 1 from 5 to 3 move 7 from 9 to 1 move 7 from 1 to 2 move 4 from 6 to 9 move 12 from 9 to 7 move 6 from 7 to 5 move 1 from 3 to 5 move 7 from 4 to 7 move 3 from 7 to 8 move 3 from 8 to 6 move 18 from 2 to 9 move 7 from 2 to 3 move 15 from 9 to 4 move 3 from 3 to 9 move 1 from 3 to 1 move 3 from 5 to 4 move 1 from 1 to 2 move 1 from 9 to 2 move 2 from 6 to 2 move 5 from 7 to 6 move 5 from 2 to 7 move 3 from 3 to 4 move 5 from 5 to 3 move 6 from 7 to 4 move 9 from 4 to 2 move 18 from 4 to 9 move 6 from 2 to 1 move 1 from 1 to 9 move 4 from 7 to 4 move 7 from 2 to 4 move 1 from 2 to 8 move 1 from 4 to 2 move 4 from 3 to 4 move 16 from 9 to 5 move 9 from 9 to 8 move 1 from 9 to 7 move 4 from 1 to 2 move 2 from 5 to 4 move 10 from 5 to 4 move 4 from 2 to 1 move 5 from 1 to 2 move 1 from 8 to 5 move 1 from 6 to 5 move 4 from 8 to 5 move 2 from 6 to 9 move 3 from 6 to 2 move 2 from 9 to 1 move 1 from 7 to 6 move 1 from 3 to 8 move 9 from 5 to 9 move 4 from 8 to 1 move 2 from 8 to 2 move 1 from 5 to 7 move 9 from 9 to 8 move 1 from 7 to 5 move 9 from 8 to 2 move 6 from 1 to 6 move 6 from 2 to 6 move 10 from 2 to 5 move 5 from 2 to 1 move 1 from 3 to 5 move 8 from 5 to 4 move 5 from 1 to 3 move 10 from 6 to 8 move 3 from 6 to 9 move 4 from 3 to 1 move 5 from 8 to 2 move 4 from 5 to 9 move 1 from 3 to 7 move 1 from 7 to 3 move 1 from 8 to 6 move 1 from 6 to 1 move 15 from 4 to 8 move 5 from 9 to 2 move 1 from 9 to 1 move 1 from 1 to 3 move 6 from 4 to 8 move 12 from 8 to 7 move 1 from 3 to 5 move 3 from 1 to 9 move 13 from 4 to 9 move 5 from 7 to 2 move 1 from 5 to 4 move 8 from 9 to 5 move 6 from 2 to 5 move 2 from 5 to 6"""
[ { "class_path": "Wrent__advent-of-code-2022__8230fce/cz/wrent/advent/Day5Kt.class", "javap": "Compiled from \"Day5.kt\"\npublic final class cz.wrent.advent.Day5Kt {\n private static final java.lang.String input;\n\n public static final void main();\n Code:\n 0: ldc #8 /...
warmthdawn__LeetCode__40dc158/lc004/src/main/kotlin/misc/Solution.kt
package misc; import kotlin.math.max import kotlin.system.measureTimeMillis import kotlin.time.ExperimentalTime import kotlin.time.measureTime data class State( val rank: Int, val star: Int, val continuousWin: Int, val preserveStars: Int ) class Solution { fun calc(starPerRank: Int, winPerPreserve: Int, totalWin: Int, targetRank: Int, gameRecord: String): Boolean { //缓存,好像除了浪费内存没啥用( val winCache = HashMap<State, State>() val failCache = HashMap<State, State>() //如果胜利,下一场次的状态 fun State.win(): State = winCache.computeIfAbsent(this) { if (star == starPerRank) { State( rank + 1, 1, (continuousWin + 1) % winPerPreserve, (continuousWin + 1) / winPerPreserve ) } else { State( rank, star + 1, (continuousWin + 1) % winPerPreserve, (continuousWin + 1) / winPerPreserve ) } } //如果失败,下一场次的状态 fun State.fail(): State = failCache.computeIfAbsent(this) { if (preserveStars > 0) { State( rank, star, 0, preserveStars - 1 ) } else if (star == 0) { State( if (rank == 1) 1 else rank - 1, starPerRank - 1, 0, 0 ) } else { State( rank, star + 1, 0, 0 ) } } //计算胜利场次数量 val restWins = totalWin - gameRecord.count { it == '1' } var maxRank = 1 //模拟 fun simulate(i: Int, currentState: State, chooseWins: Int) { if (chooseWins > restWins) { return } if (i >= gameRecord.length) { if (chooseWins == restWins) { maxRank = max(maxRank, currentState.rank) } return } when (gameRecord[i]) { '0' -> simulate(i + 1, currentState.fail(), chooseWins) '1' -> simulate(i + 1, currentState.win(), chooseWins) '?' -> { simulate(i + 1, currentState.fail(), chooseWins) simulate(i + 1, currentState.win(), chooseWins + 1) } else -> throw IllegalArgumentException("Game record should only contains '0', '1' and '?'") } } simulate(0, State(1, 1, 0, 0), 0) return maxRank >= targetRank } fun run() { val (m, d, B, C) = readLine()!!.split(" ").map { it.trim().toInt() } val S = readLine()!!.split(" ").filter { it.isNotEmpty() }.joinToString("") { it } val time = measureTimeMillis { val calc = calc(m, d, B, C, S) println(calc) } println("方法执行耗时 $time ms") } } fun main() { Solution().run() }
[ { "class_path": "warmthdawn__LeetCode__40dc158/misc/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class misc.Solution {\n public misc.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n...
emmabritton__advent-of-code__c041d14/kotlin/src/commonMain/kotlin/y2015/Day2.kt
package y2015 fun runY2015D2(input: String): Pair<String, String> { val result = input.lines() .map { parse(it) } .map { calc(it) } .reduce { acc, pair -> Pair(acc.first + pair.first, acc.second + pair.second) } return Pair(result.first.toString(), result.second.toString()) } private fun parse(input: String): List<Int> { val list = input.split("x").mapNotNull { it.toIntOrNull() } if (list.size == 3) { return list } else { throw IllegalStateException("Invalid number of sides: $input") } } private fun calc(input: List<Int>): Pair<Int, Int> { val highest = input.maxOrNull()!! val smallerSides = ArrayList(input).apply { remove(highest) } val paper = (2 * input[0] * input[1]) + (2 * input[1] * input[2]) + (2 * input[0] * input[2]) + (smallerSides[0] * smallerSides[1]) val ribbon = (smallerSides[0] + smallerSides[0] + smallerSides[1] + smallerSides[1]) + (input[0] * input[1] * input[2]) return Pair(paper, ribbon) }
[ { "class_path": "emmabritton__advent-of-code__c041d14/y2015/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class y2015.Day2Kt {\n public static final kotlin.Pair<java.lang.String, java.lang.String> runY2015D2(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 ...
emmabritton__advent-of-code__c041d14/kotlin/src/commonMain/kotlin/y2016/Day1.kt
package y2016 import kotlin.math.abs fun runY2016D1(input: String): Pair<String, String> { val steps = input.split(",") .map { parse(it.trim()) } val (distance, firstRepeat) = travel(steps) return Pair(distance.toString(), firstRepeat.toString()) } fun parse(input: String): Move { if (input.length == 1) { throw IllegalArgumentException("Too short: $input") } val number = input.substring(1).toIntOrNull() ?: throw IllegalArgumentException("Invalid number: $input") return when (input.first()) { 'R' -> Move.Right(number) 'L' -> Move.Left(number) else -> throw IllegalArgumentException("Invalid letter: $input") } } fun travel(moves: List<Move>): Pair<Int, Int> { val visited = HashSet<Coord>() val pos = Coord(0,0) var dir = Direction.North var firstRepeat: Coord? = null for (move in moves) { dir = dir.update(move) val walked = pos.walk(dir, move) for (step in walked) { if (firstRepeat == null) { if (visited.contains(step)) { firstRepeat = step } println("Visited ${step.x},${step.y}"); visited.add(step) } } } return Pair(pos.distance(), firstRepeat?.distance() ?: 0) } data class Coord( var x: Int, var y: Int ) { fun distance(): Int { return abs(x) + abs(y) } fun walk(dir: Direction, move: Move): List<Coord> { var list = listOf<Coord>() when (dir) { Direction.North -> { list = (1..move.dist).map { Coord(this.x, this.y + it) } this.y += move.dist } Direction.East -> { list = (1..move.dist).map { Coord(this.x + it, this.y) } this.x += move.dist } Direction.South -> { list = (1..move.dist).map { Coord(this.x, this.y - it) } this.y -= move.dist } Direction.West -> { list = (1..move.dist).map { Coord(this.x - it, this.y) } this.x -= move.dist } } return list } } enum class Direction { North, East, South, West; fun update(move: Move): Direction { return when (this) { North -> if (move is Move.Left) West else East East -> if (move is Move.Left) North else South South -> if (move is Move.Left) East else West West -> if (move is Move.Left) South else North } } } sealed class Move(val dist: Int) { class Left(dist: Int): Move(dist) class Right(dist: Int): Move(dist) }
[ { "class_path": "emmabritton__advent-of-code__c041d14/y2016/Day1Kt.class", "javap": "Compiled from \"Day1.kt\"\npublic final class y2016.Day1Kt {\n public static final kotlin.Pair<java.lang.String, java.lang.String> runY2016D1(java.lang.String);\n Code:\n 0: aload_0\n 1: ldc #10 ...
vorpal-research__kotlin-wheels__389f9c2/src/commonMain/kotlin/ru/spbstu/wheels/Comparables.kt
package ru.spbstu.wheels inline class ComparatorScope<T>(val comparator: Comparator<T>) { operator fun T.compareTo(that: T) = comparator.compare(this, that) fun Iterable<T>.maxOrNull() = maxWithOrNull(comparator) fun Iterable<T>.minOrNull() = minWithOrNull(comparator) fun Collection<T>.sorted() = sortedWith(comparator) fun MutableList<T>.sort() = sortWith(comparator) } inline fun <T, R> Comparator<T>.use(body: ComparatorScope<T>.() -> R) = ComparatorScope(this).body() fun combineCompares(cmp0: Int, cmp1: Int): Int = when { cmp0 != 0 -> cmp0 else -> cmp1 } fun combineCompares(cmp0: Int, cmp1: Int, cmp2: Int): Int = when { cmp0 != 0 -> cmp0 cmp1 != 0 -> cmp1 else -> cmp2 } fun combineCompares(vararg cmps: Int): Int = cmps.find { it != 0 } ?: 0 fun <A: Comparable<A>> Pair<A, A>.sorted() = when { first <= second -> this else -> second to first } fun <A> Pair<A, A>.sortedWith(cmp: Comparator<A>) = cmp.use { when { first <= second -> this@sortedWith else -> second to first } } fun <A> Triple<A, A, A>.sortedWith(cmp: Comparator<A>) = cmp.use { when { first <= second -> when { // first <= second && second <= third second <= third -> this@sortedWith // Triple(first, second, third) // first <= second && third < second && first <= third // => first <= third < second first <= third -> Triple(first, third, second) // first <= second && third < second && third < first // => third < first <= second else -> Triple(third, first, second) } // second < first else -> when { // second < first && third <= second // => third <= second < first third <= second -> Triple(third, second, first) // second < first && second < third && third <= first // => second < third <= first third <= first -> Triple(second, third, first) // second < first && second < third && first < third // => second < first < third else -> Triple(second, first, third) } } } fun <A: Comparable<A>> Triple<A, A, A>.sorted() = sortedWith(naturalOrder())
[ { "class_path": "vorpal-research__kotlin-wheels__389f9c2/ru/spbstu/wheels/ComparablesKt.class", "javap": "Compiled from \"Comparables.kt\"\npublic final class ru.spbstu.wheels.ComparablesKt {\n public static final <T, R> R use(java.util.Comparator<T>, kotlin.jvm.functions.Function1<? super ru.spbstu.wheels...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0126/WordLadder2.kt
package leetcode.problem0126 class WordLadder2 { fun findLadders(beginWord: String, endWord: String, wordList: List<String>): List<List<String>> { if (endWord !in wordList) return emptyList() val wordSet = setOf(beginWord) + wordList.toSet() val adjacentWordMap: HashMap<String, List<String>> = hashMapOf() wordSet.forEach { word -> adjacentWordMap[word] = wordSet.filter { it.isAdjacent(word) } } val queue = ArrayDeque<String>() val levelMap: HashMap<String, Int> = hashMapOf() val graph: HashMap<String, MutableSet<String>> = hashMapOf() levelMap[beginWord] = 0 queue.add(beginWord) while (queue.isNotEmpty()) { val currentWord = queue.removeFirst() val currentLevel = levelMap[currentWord] ?: throw IllegalStateException() if (!graph.containsKey(currentWord)) { graph[currentWord] = mutableSetOf() } adjacentWordMap[currentWord]?.forEach { graph[currentWord]?.add(it) if (!levelMap.containsKey(it)) { levelMap[it] = currentLevel + 1 queue.add(it) } } } if (!levelMap.containsKey(endWord)) { return emptyList() } val answerSet = mutableListOf<List<String>>() val stringPath = mutableListOf<String>() fun buildAnswer(word: String, level: Int) { if (word == beginWord) { answerSet.add(stringPath + listOf(word)) return } stringPath.add(word) graph[word]?.forEach { nextWord -> if (levelMap[nextWord] != level - 1) return@forEach buildAnswer(nextWord, level - 1) } stringPath.removeLast() } buildAnswer(endWord, levelMap[endWord]!!) return answerSet.map { it.reversed() } } private fun String.isAdjacent(target: String): Boolean { if (this.length != target.length) return false var count = 0 forEachIndexed { index, c -> if (target[index] != c) { count++ } } return count == 1 } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0126/WordLadder2.class", "javap": "Compiled from \"WordLadder2.kt\"\npublic final class leetcode.problem0126.WordLadder2 {\n public leetcode.problem0126.WordLadder2();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0120/Triangle.kt
package leetcode.problem0120 import kotlin.math.min class Triangle { fun minimumTotal(triangle: List<List<Int>>): Int = when (triangle.size) { 1 -> triangle[0][0] else -> { val array = Array(triangle.size) { intArrayOf() } array[0] = intArrayOf(triangle[0][0]) (1..triangle.lastIndex).forEach { array[it] = IntArray(it + 1) (0..array[it].lastIndex).forEach { index -> array[it][index] = triangle[it][index] + when (index) { 0 -> array[it - 1][index] array[it].lastIndex -> array[it - 1][index - 1] else -> min(array[it - 1][index], array[it - 1][index - 1]) } } } array[triangle.lastIndex].findMin() } } private fun IntArray.findMin(): Int { var minValue = this[0] for (i in 1..lastIndex) { val v = this[i] if (minValue > v) { minValue = v } } return minValue } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0120/Triangle.class", "javap": "Compiled from \"Triangle.kt\"\npublic final class leetcode.problem0120.Triangle {\n public leetcode.problem0120.Triangle();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Me...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0052/NQueens2.kt
package leetcode.problem0052 class NQueens2 { fun totalNQueens(n: Int): Int { val board = Array(n) { BooleanArray(n) { false } } return solve(board, 0) } private fun solve(board: Array<BooleanArray>, row: Int): Int { if (row == board.size) { return 1 } var count = 0 board[row].indices.forEach { column -> if (canPlace(board, row, column)) { board[row][column] = true count += solve(board, row + 1) board[row][column] = false } } return count } private fun canPlace(board: Array<BooleanArray>, row: Int, column: Int): Boolean { if (board[row].any { it }) { return false } if (board.map { it[column] }.any { it }) { return false } val leftDiagonal = (0 until row).mapNotNull { val diff = column - row if (it + diff >= 0 && it + diff <= board.lastIndex) board[it][it + diff] else null } if (leftDiagonal.any { it }) { return false } val rightDiagonal = (0 until row).mapNotNull { val sum = row + column if (it <= sum && sum - it <= board.lastIndex) board[it][sum - it] else null } if (rightDiagonal.any { it }) { return false } return true } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0052/NQueens2.class", "javap": "Compiled from \"NQueens2.kt\"\npublic final class leetcode.problem0052.NQueens2 {\n public leetcode.problem0052.NQueens2();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Me...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0047/Permutations2.kt
package leetcode.problem0047 class Permutations2 { fun permuteUnique(nums: IntArray): List<List<Int>> { val hashMap = hashMapOf<Int, Int>() nums.forEach { hashMap[it] = if (hashMap.containsKey(it)) { requireNotNull(hashMap[it]) + 1 } else { 1 } } return permute(hashMap) } private fun permute(hashMap: HashMap<Int, Int>): List<List<Int>> = if (hashMap.values.filter { it > 0 }.size == 1) { val tmp = hashMap.filterValues { it > 0 } listOf(IntArray(tmp.values.first()) { tmp.keys.first() }.toList()) } else { hashMap.flatMap { (key, value) -> if (value == 0) { return@flatMap emptyList<List<Int>>() } hashMap[key] = value - 1 try { permute(hashMap).map { val tmpList = mutableListOf<Int>() tmpList.add(key) tmpList.addAll(it) tmpList } } finally { hashMap[key] = value } } } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0047/Permutations2.class", "javap": "Compiled from \"Permutations2.kt\"\npublic final class leetcode.problem0047.Permutations2 {\n public leetcode.problem0047.Permutations2();\n Code:\n 0: aload_0\n 1: invokespecial #8 ...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0040/CombinationSumSecond.kt
package leetcode.problem0040 class CombinationSumSecond { fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { if (candidates.all { it > target }) { return emptyList() } val countMap = hashMapOf<Int, Int>() candidates.forEach { countMap[it] = (countMap[it] ?: 0) + 1 } return combinationSum(countMap, target).toList() } private fun combinationSum(hashMap: HashMap<Int, Int>, target: Int): Set<List<Int>> { val answer = mutableSetOf<List<Int>>() hashMap.forEach { (candidate, count) -> if (count == 0) return@forEach when { target == candidate -> answer.add(listOf(candidate)) target > candidate -> { hashMap[candidate] = count - 1 combinationSum(hashMap, target - candidate).forEach { if (it.isNotEmpty()) { answer.add(it.toMutableList().apply { add(candidate) }.sorted()) } } hashMap[candidate] = count } else -> Unit } } return answer } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0040/CombinationSumSecond.class", "javap": "Compiled from \"CombinationSumSecond.kt\"\npublic final class leetcode.problem0040.CombinationSumSecond {\n public leetcode.problem0040.CombinationSumSecond();\n Code:\n 0: aload_0\n ...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0085/MaximalRectangle.kt
package leetcode.problem0085 import java.util.Stack import kotlin.math.max class MaximalRectangle { fun maximalRectangle(matrix: Array<CharArray>): Int { val heights = Array(matrix.size) { IntArray(matrix[0].size) { 0 } } matrix.forEachIndexed { row, chars -> chars.indices.forEach { column -> heights[row][column] = when (matrix[row][column]) { '1' -> if (row == 0) 1 else heights[row - 1][column] + 1 '0' -> 0 else -> error("Invalid value") } } } var maxSize = 0 heights.forEach { maxSize = max(maxSize, largestRectangleArea(it)) } return maxSize } private fun largestRectangleArea(heights: IntArray): Int { val indexStack = Stack<Int>() var maxArea = 0 heights.forEachIndexed { index, i -> while (indexStack.isNotEmpty() && i < heights[indexStack.peek()]) { val currentIndex = indexStack.pop() val nextIndex = if (indexStack.isEmpty()) 0 else indexStack.peek() + 1 val area = heights[currentIndex] * (index - nextIndex) maxArea = max(maxArea, area) } indexStack.push(index) } while (indexStack.isNotEmpty()) { val currentIndex = indexStack.pop() val nextIndex = if (indexStack.isEmpty()) 0 else indexStack.peek() + 1 val area = heights[currentIndex] * (heights.size - nextIndex) maxArea = max(maxArea, area) } return maxArea } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0085/MaximalRectangle.class", "javap": "Compiled from \"MaximalRectangle.kt\"\npublic final class leetcode.problem0085.MaximalRectangle {\n public leetcode.problem0085.MaximalRectangle();\n Code:\n 0: aload_0\n 1: invokes...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0015/ThreeSum.kt
package leetcode.problem0015 class ThreeSum { fun threeSum(nums: IntArray): List<List<Int>> { if (nums.isEmpty()) { return emptyList() } val answerMap = HashMap<Int, Int>() val answerSet = mutableSetOf<List<Int>>() nums.forEachIndexed { index, num -> if (answerMap.containsKey(num)) { return@forEachIndexed } val tmpList = nums.toMutableList() tmpList.removeAt(index) val twoSumList = twoSum(tmpList.toIntArray(), -num) twoSumList.forEach { twoSum -> if (twoSum.size != 2) { return@forEach } val answer = listOf(num, twoSum[0], twoSum[1]).sorted() answerSet.add(answer) } answerMap[num] = index } return answerSet.toList() } private fun twoSum(nums: IntArray, target: Int): List<List<Int>> { val hashmap = HashMap<Int, Int>() val answerList = mutableListOf<List<Int>>() nums.forEachIndexed { index, value -> val missing = target - value if (hashmap.containsKey(missing) && hashmap[missing] != index) { hashmap[missing]?.let { answerList.add(listOf(nums[it], value)) } } hashmap[value] = index } return answerList } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0015/ThreeSum.class", "javap": "Compiled from \"ThreeSum.kt\"\npublic final class leetcode.problem0015.ThreeSum {\n public leetcode.problem0015.ThreeSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Me...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0123/BestTimeToBuyAndSellStock3.kt
package leetcode.problem0123 import java.lang.IllegalArgumentException import kotlin.math.max class BestTimeToBuyAndSellStock3 { fun maxProfit(prices: IntArray): Int { val dp: Map<Boolean, Array<IntArray>> = mapOf( true to Array(prices.size) { IntArray(MAX_PURCHASE_COUNT) { -1 } }, false to Array(prices.size) { IntArray(MAX_PURCHASE_COUNT) { -1 } } ) return solve(prices, 0, false, 0, dp) } private fun solve( prices: IntArray, index: Int, hasStock: Boolean, count: Int, dp: Map<Boolean, Array<IntArray>> ): Int { val map = dp[hasStock] ?: throw IllegalArgumentException() return when { index == prices.size || count == MAX_PURCHASE_COUNT -> 0 map[index][count] != -1 -> map[index][count] else -> { if (hasStock) { max( prices[index] + solve(prices, index + 1, false, count + 1, dp), solve(prices, index + 1, true, count, dp) ) } else { max( -prices[index] + solve(prices, index + 1, true, count, dp), solve(prices, index + 1, false, count, dp) ) } .also { map[index][count] = it } } } } companion object { private const val MAX_PURCHASE_COUNT = 2 } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0123/BestTimeToBuyAndSellStock3$Companion.class", "javap": "Compiled from \"BestTimeToBuyAndSellStock3.kt\"\npublic final class leetcode.problem0123.BestTimeToBuyAndSellStock3$Companion {\n private leetcode.problem0123.BestTimeToBuyAndS...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0051/NQueens.kt
package leetcode.problem0051 class NQueens { fun solveNQueens(n: Int): List<List<String>> { val answer = arrayListOf<List<String>>() val board = Array(n) { CharArray(n) { '.' } } solve(board, 0, answer) return answer } private fun solve(board: Array<CharArray>, row: Int, answer: ArrayList<List<String>>) { if (row == board.size) { answer.add(board.map { it.joinToString("") }) return } board[row].indices.forEach { column -> if (canPlace(board, row, column)) { board[row][column] = 'Q' solve(board, row + 1, answer) board[row][column] = '.' } } } private fun canPlace(board: Array<CharArray>, row: Int, column: Int): Boolean { if ('Q' in board[row]) { return false } if ('Q' in board.map { it[column] }) { return false } val leftDiagonal = (0 until row).mapNotNull { val diff = column - row if (it + diff >= 0 && it + diff <= board.lastIndex) board[it][it + diff] else null } if ('Q' in leftDiagonal) { return false } val rightDiagonal = (0 until row).mapNotNull { val sum = row + column if (it <= sum && sum - it <= board.lastIndex) board[it][sum - it] else null } if ('Q' in rightDiagonal) { return false } return true } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0051/NQueens.class", "javap": "Compiled from \"NQueens.kt\"\npublic final class leetcode.problem0051.NQueens {\n public leetcode.problem0051.NQueens();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0005/LongestPalindromicSubstring.kt
package leetcode.problem0005 import kotlin.math.max class LongestPalindromicSubstring { fun longestPalindrome(s: String): String { if (s.isEmpty()) { return "" } var startIndex = 0 var endIndex = 0 for (index in 0..s.length) { val temp1 = findPalindrome(s, index, index) val temp2 = findPalindrome(s, index, index + 1) val maxPalindromeLength = max(temp1, temp2) if (maxPalindromeLength > endIndex - startIndex) { startIndex = index - (maxPalindromeLength - 1) / 2 endIndex = index + maxPalindromeLength / 2 + 1 } } return s.substring(startIndex, endIndex) } private fun findPalindrome(s: String, start: Int, end: Int): Int { var length = end - start for (index in 0..s.length) { if (start - index < 0 || end + index >= s.length || s[start - index] != s[end + index]) { break } length += 2 } return length - 1 } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0005/LongestPalindromicSubstring.class", "javap": "Compiled from \"LongestPalindromicSubstring.kt\"\npublic final class leetcode.problem0005.LongestPalindromicSubstring {\n public leetcode.problem0005.LongestPalindromicSubstring();\n ...
ayukatawago__leetcode-kotlin__f9602f2/src/main/kotlin/leetcode/problem0018/FourSum.kt
package leetcode.problem0018 class FourSum { fun fourSum(nums: IntArray, target: Int): List<List<Int>> { val sortedNums = nums.sorted() return kSum(sortedNums, target, 4) } private fun kSum(sortedNums: List<Int>, target: Int, k: Int): List<List<Int>> { if (sortedNums.isEmpty()) { return emptyList() } val answerMap = HashMap<Int, List<List<Int>>>() sortedNums.forEachIndexed { index, num -> if (answerMap[num] != null) { return@forEachIndexed } val remainingNums = sortedNums.drop(index + 1) val answerList = if (k == 3) { twoSum(remainingNums, target - num) } else { kSum(remainingNums, target - num, k - 1) } answerMap[num] = answerList.map { getAnswer(num, it) } } return answerMap.flatMap { it.value }.distinct() } private fun getAnswer(num: Int, numList: List<Int>): List<Int> = mutableListOf(num).also { it.addAll(numList) } private fun twoSum(sortedNums: List<Int>, target: Int): List<List<Int>> { if (sortedNums.size < 2) { return emptyList() } val answerList = mutableListOf<List<Int>>() var left = 0 var right = sortedNums.lastIndex while (left < right) { val leftValue = sortedNums[left] val rightValue = sortedNums[right] when { leftValue + rightValue == target -> { answerList.add(listOf(leftValue, rightValue)) left += 1 } leftValue + rightValue < target -> left += 1 leftValue + rightValue > target -> right -= 1 } } return answerList } }
[ { "class_path": "ayukatawago__leetcode-kotlin__f9602f2/leetcode/problem0018/FourSum.class", "javap": "Compiled from \"FourSum.kt\"\npublic final class leetcode.problem0018.FourSum {\n public leetcode.problem0018.FourSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method...
catalintira__aquamarine__a55bb2a/aqua/app/src/main/java/com/garmin/android/aquamarine/Basic.kt
package com.garmin.android.aquamarine // Exercise 1 open class Account(var balance: Float) { open fun withdraw(sumToWithdraw: Float) { balance -= sumToWithdraw } fun deposit(sumToDeposit: Float) { balance += sumToDeposit } } class SavingAccount(balance: Float) : Account(balance) { override fun withdraw(sumToWithdraw: Float) { if (sumToWithdraw > balance) { throw IllegalArgumentException() } super.withdraw(sumToWithdraw) } } // Exercise 2 // N // W E // S fun getCardinalDirections(angle: Int): String { return when (angle) { in 45..134 -> "E" in 135..224 -> "S" in 225..314 -> "W" else -> "N" } } // Exercise 3 val vocals = listOf('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') fun getVocalsCount(input: String): Int = input.count { vocals.contains(it) } // Exercise 4 A class RectangularShape(var x: Int, var y: Int, var with: Int, var height: Int, var color: Int) { fun measure() {} fun render() {} } fun validateShape(shape: RectangularShape): Boolean { return when { shape.x < 0 || shape.y < 0 -> { print("invalid position"); false } shape.with > 1024 || shape.height > 1024 -> { print("shape too big"); false } shape.color < 0 || shape.color > 0xFFFFFF -> { print("invalid color"); false } else -> true } } // Exercise 4 B fun initShape(shape: RectangularShape?) { shape?.apply { x = 10 y = 20 with = 100 height = 200 color = 0xFF0066 } ?: throw IllegalArgumentException() } // Exercise 4 C fun drawShape(shape: RectangularShape?) { shape?.also { validateShape(it) it.measure() it.render() } } // Exercise 5 val data = listOf(4, 6, 34, 9, 2, 4, 7) fun solveExercise5() { // A print(data) // B print(data.reversed()) // C print(data.distinct()) // D print(data.subList(0, 3)) // E val min: Int? = data.min() if (min != null && min >= 0) print(data) // F print(data.map { it * it }) // G print(data.filter { it % 2 == 0 }) // H data.forEachIndexed { i, v -> if (v % 2 == 0) print(i) } // I fun isPrime(number: Int): Boolean { when (number) { in 0..1 -> return false 2 -> return true else -> { if(number % 2 == 0) return false for (i in 3 until number step 2) { if(number % i == 0) return false } } } return true } print( data.filter { isPrime(it) } ) // J data.last { isPrime(it) } } // Exercise 6 data class Student(val name: String, val address: String, val grade: Int) val students = listOf( Student("John", "Boston", 6), Student("Jacob", "Baltimore", 2), Student("Edward", "New York", 7), Student("William", "Providence", 6), Student("Alice", "Philadelphia", 4), Student("Robert", "Boston", 7), Student("Richard", "Boston", 10), Student("Steven", "New York", 3) ) fun solveExercise6() { // A print(students) // B print(students.sortedBy { it.name }) // C students.map { it.name } .sortedBy { it } .forEach { print(it) } // D students.sortedWith(compareBy({ it.grade }, { it.name })) .forEach { print(it) } // E print(students.groupBy { it.address }) } fun vineri6() { val str = "abcdef" str[0] str.subSequence(0, 2) for(l in str) print("$l ") fun isEven(input : Int): Boolean { return input % 2 == 0 } isEven(300) fun filterC(text : String) = text.filter { it !in "aeiouAEIOU" } filterC(str) fun String.consonants() = filter { it !in "aeiouAEIOU" } str.consonants() }
[ { "class_path": "catalintira__aquamarine__a55bb2a/com/garmin/android/aquamarine/BasicKt$solveExercise6$$inlined$sortedBy$2.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class com.garmin.android.aquamarine.BasicKt$solveExercise6$$inlined$sortedBy$2<T> implements java.util.Comparator {\n p...
pkleimann__livingdoc2__b81fe45/livingdoc-engine/src/main/kotlin/org/livingdoc/engine/algo/DamerauLevenshtein.kt
package org.livingdoc.engine.algo import java.lang.Math.min /** * Calculates the Damerau-Levenshtein distance, a string similarity metric used e.g. by spell checkers. * * By default, the algorithm calculates the minimum number of four different editing operations * required to turn one string into another. The four operations are * <ul> * <li><emph>insertion:</emph> a character is inserted</li> * <li><emph>deletion:</emph> a character is deleted</li> * <li><emph>substitution:</emph> a character is exchanged with another</li> * <li><emph>transposition:</emph> two adjacent characters are swapped</li> * </ul> * * It is possible to specify a weight for each of these operations to tune the metric. * * The implementation is linear in space, but O(n²) in time. To avoid expensive comparisons of long * strings, you can specify a cutoff distance, beyond which the algorithm will abort. * * @param cutoffDistance maximum distance at which the algorithm aborts (default: no cutoff) * @param weightInsertion weight of an insert operation (default: 1) * @param weightDeletion weight of a deletion operation (default: 1) * @param weightSubstitution weight of a substitution operation (default: 1) * @param weightTransposition weight of a transposition operation (default: 1) */ class DamerauLevenshtein( val cutoffDistance: Int = 0, val weightInsertion: Int = 1, val weightDeletion: Int = 1, val weightSubstitution: Int = 1, val weightTransposition: Int = 1 ) { /* * This dynamic programming algorithm calculates a m*n matrix of distance values. The * final result is the distance between the two given strings a and b. The values in between * are locally minimal distances for the respective substrings of a and b. * * L i v i n g D o c - b * 0 1 2 3 4 5 6 7 8 9 * L 1 0 2 3 4 5 6 7 8 9 * o 2 1 1 2 3 4 5 6 7 8 * v 3 2 2 1 2 3 4 5 6 7 * i 4 3 2 2 1 2 3 4 5 6 * g 5 4 3 3 2 2 3 4 5 6 * n 6 5 4 4 3 2 2 3 4 5 * D 7 6 5 5 4 3 3 2 3 4 * e 8 7 6 6 5 4 4 3 3 4 * a 9 8 7 7 6 5 5 4 4 4 * d 10 9 8 8 7 6 6 5 5 5 <-- distance result * | * a * * As only the last three rows are needed to calculate the next distance value, only those are kept * in memory. */ /** * Calculates the editing distance between the given strings. */ @Suppress("ComplexCondition") fun distance(a: String, b: String): Int { var secondToLastRow = IntArray(b.length + 1) var lastRow = IntArray(b.length + 1) var currentRow = IntArray(b.length + 1) for (j in 0..b.length) { lastRow[j] = j * weightInsertion } for (i in 0 until a.length) { var currentDistance = Int.MAX_VALUE currentRow[0] = (i + 1) * weightDeletion for (j in 0 until b.length) { currentRow[j + 1] = currentRow[j] + weightInsertion currentRow[j + 1] = min(currentRow[j + 1], lastRow[j + 1] + weightDeletion) currentRow[j + 1] = min(currentRow[j + 1], lastRow[j] + if (a[i] != b[j]) weightSubstitution else 0) if (i > 0 && j > 0 && a[i - 1] == b[j] && a[i] == b[j - 1]) { currentRow[j + 1] = min(currentRow[j + 1], secondToLastRow[j - 1] + weightTransposition) } currentDistance = min(currentDistance, currentRow[j + 1]) } // check cutoff if (cutoffDistance in 1..currentDistance) { return currentDistance } // rotate rows val tempRow = secondToLastRow secondToLastRow = lastRow lastRow = currentRow currentRow = tempRow } return lastRow[b.length] } }
[ { "class_path": "pkleimann__livingdoc2__b81fe45/org/livingdoc/engine/algo/DamerauLevenshtein.class", "javap": "Compiled from \"DamerauLevenshtein.kt\"\npublic final class org.livingdoc.engine.algo.DamerauLevenshtein {\n private final int cutoffDistance;\n\n private final int weightInsertion;\n\n private ...
olegthelilfix__MyKata__bf17d2f/src/main/java/me/olegthelilfix/leetcoding/old/LongestPalindrome.kt
package me.olegthelilfix.leetcoding.old //Given a string s, return the longest palindromic substring in s. fun isPalindrome(s: String): Boolean { if (s.isEmpty()) { return false } for (i in 0 .. s.length/2) { if(s[i] != s[s.length-i-1]) { return false } } return true } fun longestPalindrome(s: String): String { if (s.length == 1) { return s } if (isPalindrome(s)) { return s } var longest = s[0].toString() for (i in 0 until s.length - 1) { s.slice(0..10) var substring: String = s[i].toString() for (j in i + 1 until s.length) { substring += s[j] if (isPalindrome(substring) && substring.length > longest.length) { longest = substring } } } return longest } fun main() { // isPalindrome("abcba") var t = System.currentTimeMillis() longestPalindrome("<KEY>") var t2 = System.currentTimeMillis() print(t2-t) }
[ { "class_path": "olegthelilfix__MyKata__bf17d2f/me/olegthelilfix/leetcoding/old/LongestPalindromeKt.class", "javap": "Compiled from \"LongestPalindrome.kt\"\npublic final class me.olegthelilfix.leetcoding.old.LongestPalindromeKt {\n public static final boolean isPalindrome(java.lang.String);\n Code:\n ...
olegthelilfix__MyKata__bf17d2f/src/main/java/me/olegthelilfix/leetcoding/old/FindMedianSortedArrays.kt
package me.olegthelilfix.leetcoding.old /** * Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. * The overall run time complexity should be O(log (m+n)). */ class FindMedianSortedArrays { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val result = IntArray(nums1.size + nums2.size) var i = 0 var j = 0 var index = 0 val s1 = nums1.size val s2 = nums2.size while (index < result.size) { val n1 = if (s1 > i) nums1[i] else Int.MAX_VALUE val n2 = if (s2 > j) nums2[j] else Int.MAX_VALUE if(n1 < n2) { result[index] = nums1[i] i++ } else { result[index] = nums2[j] j++ } index++ } return if ((result.size) % 2 != 0) { result[(result.size) / 2].toDouble() } else { (result[result.size/2] +result[result.size/2 - 1])/2.0 } } } fun main() { println( FindMedianSortedArrays().findMedianSortedArrays( listOf(1, 2).toIntArray(), listOf(3, 4).toIntArray(), )) }
[ { "class_path": "olegthelilfix__MyKata__bf17d2f/me/olegthelilfix/leetcoding/old/FindMedianSortedArrays.class", "javap": "Compiled from \"FindMedianSortedArrays.kt\"\npublic final class me.olegthelilfix.leetcoding.old.FindMedianSortedArrays {\n public me.olegthelilfix.leetcoding.old.FindMedianSortedArrays()...
olegthelilfix__MyKata__bf17d2f/src/main/java/me/olegthelilfix/leetcoding/old/IntegerToRoman.kt
package me.olegthelilfix.leetcoding.old data class RomanNumber(val letter: String, val value: Int) val numberOrder : List<RomanNumber> = listOf( RomanNumber("M", 1000), RomanNumber("CM", 900), RomanNumber("D", 500), RomanNumber("CD", 400), RomanNumber("C", 100), RomanNumber("XC", 90), RomanNumber("L", 50), RomanNumber("XL", 40), RomanNumber("X", 10), RomanNumber("IX", 9), RomanNumber("V", 5), RomanNumber("IV", 4), RomanNumber("I", 1), ) fun intToRoman(num: Int): String { var result = "" var buffer = num var letterIndex = 0 var romanNumber = numberOrder[letterIndex++] while (buffer > 0) { if((buffer - romanNumber.value) < 0) { romanNumber = numberOrder[letterIndex++] } else { buffer -= romanNumber.value result += romanNumber.letter } } return result } val letters = mapOf( "M" to 1000, "CM" to 900, "D" to 500, "CD" to 400, "C" to 100, "XC" to 90, "L" to 50, "XL" to 40, "X" to 10, "IX" to 9, "V" to 5, "IV" to 4, "I" to 1 ) fun romanToInt(s: String): Int { var i = 0 var result = 0 while (i < s.length) { val l1 = letters[s[i].toString()] ?: 0 var l2 = 0 if (i < s.length - 1 && letters.containsKey(s[i].toString() + s[i+1].toString())) { l2 = letters[s[i].toString() + s[i+1].toString()] ?: 0 i++ } result += if (l1 > l2) l1 else l2 i++ } return result } fun main() { println(romanToInt("IV")) for (i in 1 .. 10000) { val n = intToRoman(i) val n2 = romanToInt(n) if (n2 != i) { println("$i!=$n2") } } }
[ { "class_path": "olegthelilfix__MyKata__bf17d2f/me/olegthelilfix/leetcoding/old/IntegerToRomanKt.class", "javap": "Compiled from \"IntegerToRoman.kt\"\npublic final class me.olegthelilfix.leetcoding.old.IntegerToRomanKt {\n private static final java.util.List<me.olegthelilfix.leetcoding.old.RomanNumber> nu...
jwgibanez__kotlin-number-base-converter__ea76a3c/Number Base Converter/task/src/converter/Main.kt
package converter import java.math.BigDecimal import java.math.BigInteger import java.util.* import kotlin.math.pow fun main() { val scanner = Scanner(System.`in`) while (true) { print("Enter two numbers in format: {source base} {target base} (To quit type /exit) ") when (val input1 = scanner.nextLine()) { "/exit" -> return else -> { val split = input1.split(" ") val sourceBase = split[0].toBigInteger() val targetBase = split[1].toBigInteger() loop@ while (true) { print("Enter number in base $sourceBase to convert to base $targetBase (To go back type /back) ") when(val input2 = scanner.nextLine()) { "/back" -> break@loop else -> { val decimal: BigDecimal = if (sourceBase != BigInteger.TEN) converter(input2, sourceBase).toBigDecimal() else input2.toBigDecimal() val target = if (targetBase == BigInteger.TEN) decimal else converter(decimal, targetBase, input2.contains(".")) println("Conversion result: $target\n") } } } } } } } fun converter(source: String, sourceBase: BigInteger): String { var sum = BigDecimal.ZERO val integer: String val fraction: String if (source.contains(".")) { val split = source.split(".") integer = split[0] fraction = split[1] } else { integer = source fraction = "" } // Integer part val reversed = integer.reversed() for (i in reversed.indices) { sum += if (reversed[i].isDigit()) reversed[i].toString().toBigDecimal() * sourceBase.toBigDecimal().pow(i) else (10 + reversed[i].code - 'a'.code).toBigDecimal() * sourceBase.toBigDecimal().pow(i) } // Fractional part val sourceBaseDecimal = sourceBase.toDouble() var fractionSum = 0.0 for (i in fraction.indices) { fractionSum += if (fraction[i].isDigit()) fraction[i].toString().toDouble() / sourceBaseDecimal.pow(i + 1) else (10 + fraction[i].code - 'a'.code).toDouble() / sourceBaseDecimal.pow(i + 1) } return (sum + fractionSum.toBigDecimal()).toString() } fun converter(base10: BigDecimal, target: BigInteger, contains: Boolean) : String { var resultInteger = "" var resultFraction = "" val split = base10.toString().split(".") val integer = split[0].toBigInteger() // Integer part var remaining = integer while (remaining >= target) { resultInteger += convert((remaining % target).toInt()) remaining /= target } resultInteger += convert(remaining.toInt()) // Fraction part var ctr = 0 var fraction = base10 - integer.toBigDecimal() if (contains) println(fraction) while (fraction > BigDecimal.ZERO) { if (ctr == 10) break val remainingDecimal = fraction * target.toBigDecimal() fraction = remainingDecimal - remainingDecimal.toInt().toBigDecimal() resultFraction += convert(remainingDecimal.toInt()) ctr++ } while (contains && resultFraction.length < 5) { // padding resultFraction += 0 } return if (!contains) resultInteger.reversed() else resultInteger.reversed() + if (resultFraction.isNotEmpty()) ".${resultFraction.substring(0, 5)}" else ".00000" } fun convert(value: Int): String { return if (value < 10) value.toString() else ('a'.code + (value-10)).toChar().toString() }
[ { "class_path": "jwgibanez__kotlin-number-base-converter__ea76a3c/converter/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class converter.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/util/Scanner\n 3: dup\n ...
ilyawaisman__distribute-amount-between-slots__aa5c75b/src/main/kotlin/xyz/prpht/distributeamountbetweenslots/Distributor.kt
package xyz.prpht.distributeamountbetweenslots import kotlin.math.floor import kotlin.random.Random fun main() { repeat(0x10) { println(distribute(100, 5, 1, Random).joinToString(" ") { "%2d".format(it) }) } } fun distribute(amount: Int, slots: Int, rollsNum: Int, random: Random): List<Int> { var leftAmount = amount return (slots downTo 1).map { leftSlots -> val slotAmount = random.generateSlotAmount(leftAmount, leftSlots, rollsNum) leftAmount -= slotAmount slotAmount } } private fun Random.generateSlotAmount(leftAmount: Int, leftSlots: Int, rollsNum: Int): Int { check(leftSlots > 0) { "Non-positive slots count: $leftSlots" } check(leftAmount > 0) { "Non-positive amount: $leftAmount" } check(leftAmount >= leftSlots) { "leftAmount ($leftAmount) is less than leftSlots ($leftSlots)" } if (leftSlots <= 1) return leftAmount if (leftAmount == leftSlots) return 1 /** * Magic formula ensures: * 1. Values distributed in `[1..(leftAmount-lestSlots+1)]` to guarantee that next `leftAmount >= next slotsAmount`. * 2. Estimation is `leftAmount/leftSlots`. * 3. Values are centered: those near `leftAmount/leftSlots` are more probable than values at the boundaries. * Bigger `rollsNum` leads to more centered result. */ val rollsSum = (0 until rollsNum).map { nextInt(1, leftAmount - leftSlots + 2) }.sum() return stochasticRound(2.0 * rollsSum / (rollsNum * leftSlots) + (leftSlots - 2.0) / leftSlots) } fun Random.stochasticRound(x: Double): Int { val floor = floor(x) var result = floor if (nextFloat() < (x - floor)) result += 1 return result.toInt() }
[ { "class_path": "ilyawaisman__distribute-amount-between-slots__aa5c75b/xyz/prpht/distributeamountbetweenslots/DistributorKt.class", "javap": "Compiled from \"Distributor.kt\"\npublic final class xyz.prpht.distributeamountbetweenslots.DistributorKt {\n public static final void main();\n Code:\n 0: ...
mtresnik__intel__46f23b3/src/main/kotlin/com/resnik/intel/similarity/Extensions.kt
package com.resnik.intel.similarity import java.util.* fun String.lcs(other: String): String { val numArray = Array(this.length + 1) { IntArray(other.length + 1) { 0 } } for (i in 1 until this.length + 1) { val c1 = this[i - 1] for (j in 1 until other.length + 1) { val c2 = other[j - 1] if (c1 == c2) { numArray[i][j] = numArray[i - 1][j - 1] + 1; } else { numArray[i][j] = numArray[i - 1][j].coerceAtLeast(numArray[i][j - 1]) } } } val retStack = Stack<Char>() var i = numArray.size - 1 var j = numArray[0].size - 1 var currNum = numArray[i][j] while (currNum != 0) { when { numArray[i - 1][j] == currNum -> { i-- } numArray[i][j - 1] == currNum -> { j-- } numArray[i - 1][j - 1] != currNum -> { i-- j-- retStack.push(this[i]) } } currNum = numArray[i][j] } var retString: String = "" while (!retStack.isEmpty()) { retString += retStack.pop() } return retString } fun String.lcsSimilarity(other: String): Double = this.lcs(other).length.toDouble() / this.length.coerceAtLeast(other.length) fun String.jaro(other: String): Double { if (this.isEmpty() && other.isEmpty()) return 1.0 val maxMatchDistance = this.length.coerceAtLeast(other.length) / 2 - 1 val thisMatchArray = BooleanArray(this.length) val otherMatchArray = BooleanArray(other.length) var matches = 0 for (i in this.indices) { val start = 0.coerceAtLeast(i - maxMatchDistance) val end = (i + maxMatchDistance + 1).coerceAtMost(other.length) (start until end).find { j -> !otherMatchArray[j] && this[i] == other[j] }?.let { thisMatchArray[i] = true otherMatchArray[it] = true matches++ } } if (matches == 0) return 0.0 var t = 0.0 var k = 0 (this.indices).filter { thisMatchArray[it] }.forEach { i -> while (!otherMatchArray[k]) k++ if (this[i] != other[k]) t += 0.5 k++ } val m = matches.toDouble() return (m / this.length + m / other.length + (m - t) / m) / 3.0 } fun String.jaroWinkler(other: String, scalingFactor: Double = 0.1): Double { val sJ = this.jaro(other) if (sJ <= 0.7) return sJ val prefix = (0 until this.length.coerceAtMost(other.length)) .count { this[it] == other[it] } .coerceAtMost(4) .toDouble() println(prefix) return sJ + scalingFactor * prefix * (1.0 - sJ) }
[ { "class_path": "mtresnik__intel__46f23b3/com/resnik/intel/similarity/ExtensionsKt.class", "javap": "Compiled from \"Extensions.kt\"\npublic final class com.resnik.intel.similarity.ExtensionsKt {\n public static final java.lang.String lcs(java.lang.String, java.lang.String);\n Code:\n 0: aload_0\n...
tomaszobac__aoc2023__e0ce68f/src/main/kotlin/day4/Day4.kt
package day4 import java.io.File fun part1(file: File): List<Int> { val pilePoints: MutableList<Int> = mutableListOf() val part2AmountOfNumbers: MutableList<Int> = mutableListOf() var index = 0 file.bufferedReader().useLines { readLines -> readLines.forEach { line -> val sets = (line.split(Regex(": +"))[1]).split(Regex(" +\\| +")) val winNumbers = (sets[0].split(Regex(" +")).map { it.toInt() }).toSet() val myNumbers = (sets[1].split(Regex(" +")).map { it.toInt() }).toSet() var points = 0 part2AmountOfNumbers.add(index,0) for (number in myNumbers) { if (winNumbers.contains(number)) { points = if (points == 0) 1 else points * 2 part2AmountOfNumbers[index] += 1 } } index++ pilePoints += points }} println(pilePoints.sum()) return part2AmountOfNumbers.toList() } fun part2(file: File) { val amountOfNumbers: List<Int> = part1(file) val numberOfCopies: MutableList<Int> = MutableList(amountOfNumbers.size) { 1 } for ((card, amount) in amountOfNumbers.withIndex()) { if (amount == 0) continue for (repeat in 1..numberOfCopies[card]) { for (index in card + 1..card + amount) { numberOfCopies[index]++ } } } println(numberOfCopies.sum()) } fun main() { val file = File("src/main/kotlin/day4/input.txt") part2(file) }
[ { "class_path": "tomaszobac__aoc2023__e0ce68f/day4/Day4Kt.class", "javap": "Compiled from \"Day4.kt\"\npublic final class day4.Day4Kt {\n public static final java.util.List<java.lang.Integer> part1(java.io.File);\n Code:\n 0: aload_0\n 1: ldc #12 // String file\n ...
tomaszobac__aoc2023__e0ce68f/src/main/kotlin/day2/Day2.kt
package day2 import java.io.File fun part1(file: File) { var correctGames: Array<Int> = arrayOf() lineLoop@ for ((currentGame, line) in file.readLines().withIndex()) { val sets = (line.split(": ")[1]).split("; ") for (set in sets) { val cubes = set.split(", ") for (colorAmount in cubes) { val amount = colorAmount.split(' ')[0].toInt() val color = colorAmount.split(' ')[1] if (amount > 14) continue@lineLoop if (amount > 13 && (color == "red" || color == "green")) continue@lineLoop if (amount > 12 && color == "red") continue@lineLoop } } correctGames += currentGame + 1 } println(correctGames.sum()) } fun part2(file: File) { var gamePower: Array<Int> = arrayOf() for (line in file.readLines()) { val sets = (line.split(": ")[1]).split("; ") val fewest = mutableMapOf(Pair("red", 1), Pair("green", 1), Pair("blue", 1)) var power = 1 for (set in sets) { val cubes = set.split(", ") for (colorAmount in cubes) { val amount = colorAmount.split(' ')[0].toInt() val color = colorAmount.split(' ')[1] if (amount > fewest[color]!!) fewest[color] = amount } } fewest.values.forEach { power *= it } gamePower += power } println(gamePower.sum()) } fun main() { val file = File("src/main/kotlin/day2/input.txt") part1(file) part2(file) }
[ { "class_path": "tomaszobac__aoc2023__e0ce68f/day2/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2Kt {\n public static final void part1(java.io.File);\n Code:\n 0: aload_0\n 1: ldc #9 // String file\n 3: invokestatic #15 ...
tomaszobac__aoc2023__e0ce68f/src/main/kotlin/day1/Day1.kt
package day1 import java.io.File fun part1(file: File) { var numbers: Array<Int> = arrayOf() for (line in file.readLines()) { val firstNum = line.indexOfFirst { it.isDigit() } val lastNum = line.indexOfLast { it.isDigit() } val number = "${line[firstNum]}${line[lastNum]}" numbers += number.toInt() } println(numbers.sum()) } fun part2(file: File) { val dictionary: Map<String, Int> = mapOf( Pair("one", 1), Pair("two", 2),Pair("three", 3), Pair("four", 4), Pair("five", 5),Pair("six", 6), Pair("seven", 7), Pair("eight", 8),Pair("nine", 9), Pair("1", 1), Pair("2", 2),Pair("3", 3), Pair("4", 4), Pair("5", 5),Pair("6", 6), Pair("7", 7), Pair("8", 8),Pair("9", 9), ) var numbers: Array<Int> = arrayOf() for (line in file.readLines()) { var firstNum = 0 var lastNum = 0 var minIndex = Int.MAX_VALUE var maxIndex = 0 for (key in dictionary.keys) { val firstIndex = line.indexOf(key) if (firstIndex == -1) continue val lastIndex = line.lastIndexOf(key) if (firstIndex <= minIndex) { firstNum = dictionary[key]!! minIndex = firstIndex } if (lastIndex >= maxIndex) { lastNum = dictionary[key]!! maxIndex = lastIndex } } numbers += ((firstNum * 10) + lastNum) } println(numbers.sum()) } fun main() { val file = File("src/main/kotlin/day1/input.txt") part1(file) part2(file) }
[ { "class_path": "tomaszobac__aoc2023__e0ce68f/day1/Day1Kt.class", "javap": "Compiled from \"Day1.kt\"\npublic final class day1.Day1Kt {\n public static final void part1(java.io.File);\n Code:\n 0: aload_0\n 1: ldc #9 // String file\n 3: invokestatic #15 ...
DaveTCode__aoc2021__2e31324/day9/src/Program.kt
package org.davetcode.aoc2021.day9 import java.io.File fun main() { val testData = processFile("c:\\code\\home\\aoc2021day9\\test.txt") val inputData = processFile("c:\\code\\home\\aoc2021day9\\input.txt") println(part1(testData)) println(part1(inputData)) println(part2(testData)) println(part2(inputData)) } fun processFile(file: String): Array<Array<Int>> { return File(file) .readLines() .map { line -> line.toCharArray().map { it - '0' }.toTypedArray() } .toTypedArray() } data class Point(val x: Int, val y: Int) fun getLowPoints(data: Array<Array<Int>>): List<Point> { val lowPoints = mutableListOf<Point>() for (y in data.indices) { for (x in data[0].indices) { val dataPoint = data[y][x] if (x > 0 && data[y][x - 1] <= dataPoint) continue if (x < data[0].size - 1 && data[y][x + 1] <= dataPoint) continue if (y > 0 && data[y - 1][x] <= dataPoint) continue if (y < data.size - 1 && data[y + 1][x] <= dataPoint) continue lowPoints.add(Point(x, y)) } } return lowPoints } fun calculateBasinSize(data: Array<Array<Int>>, startPoint: Point): Int { fun inner(currentPoint: Point, basinPoints: MutableSet<Point>) { val (x, y) = currentPoint // Up if (y > 0 && data[y][x] < data[y - 1][x] && data[y - 1][x] != 9) { basinPoints.add(Point(x, y - 1)) inner(Point(currentPoint.x, currentPoint.y - 1), basinPoints) } // Down if (y < (data.size - 1) && data[y][x] < data[y + 1][x] && data[y + 1][x] != 9) { basinPoints.add(Point(x, y + 1)) inner(Point(currentPoint.x, currentPoint.y + 1), basinPoints) } // Left if (x > 0 && data[y][x] < data[y][x - 1] && data[y][x - 1] != 9) { basinPoints.add(Point(x - 1, y)) inner(Point(currentPoint.x - 1, currentPoint.y), basinPoints) } // Right if (x < (data[y].size - 1) && data[y][x] < data[y][x + 1] && data[y][x + 1] != 9) { basinPoints.add(Point(x + 1, y)) inner(Point(currentPoint.x + 1, currentPoint.y), basinPoints) } } val basinPoints = mutableSetOf(startPoint) inner(startPoint, basinPoints) return basinPoints.size } fun part2(data: Array<Array<Int>>): Int { val lowPoints = getLowPoints(data) val basins = lowPoints .map { calculateBasinSize(data, it) } .sortedDescending() println(basins) // Assume that all low points are in their own basin, no saddles return lowPoints .map { calculateBasinSize(data, it) } .sortedDescending() .take(3) .reduce { acc, i -> acc * i } } fun part1(data: Array<Array<Int>>): Int { val lowPoints = getLowPoints(data) return lowPoints.sumOf { data[it.y][it.x] + 1 } }
[ { "class_path": "DaveTCode__aoc2021__2e31324/org/davetcode/aoc2021/day9/ProgramKt.class", "javap": "Compiled from \"Program.kt\"\npublic final class org.davetcode.aoc2021.day9.ProgramKt {\n public static final void main();\n Code:\n 0: ldc #8 // String c:\\\\code\\\\home...
youness-1__AlgoView__f420e99/app/src/main/java/com/example/algoview/ui/algoview/Graph.kt
package com.example.algoview.ui.algoview import java.util.* import kotlin.math.abs import kotlin.math.sqrt class Edge(var destination: Vertex, var weight: Double) class Vertex( var id: Int, var i: Int, var j: Int ) : Comparable<Vertex> { var parent: Vertex? = null var distance = Double.POSITIVE_INFINITY var edges: LinkedList<Edge> = LinkedList<Edge>() var discovered = false var heuristic = 0.0 var f = Double.POSITIVE_INFINITY override operator fun compareTo(other: Vertex): Int { return distance.compareTo(other.distance) } } class Graph(heuristicType: Heuristic) { private var heuristicType: Heuristic private var vertex = ArrayList<Vertex>() init { this.heuristicType=heuristicType } fun addVertex(id: Int, i: Int, j: Int) { val v1 = Vertex(id, i, j) vertex.add(v1) } fun addEdge(source: Vertex, destination: Vertex?, weight: Double) { source.edges.add(Edge(destination!!, weight)) } fun getVertex(i: Int, j: Int): Vertex? { for (c in vertex.indices) if (vertex[c].i == i && vertex[c].j == j) return vertex[c] return null } fun heuristic(v: Vertex, destination: Vertex) { if (heuristicType == Heuristic.EUCLIDEAN){ v.heuristic = sqrt(((v.i - destination.i) * (v.i - destination.i) + (v.j - destination.j) * (v.j - destination.j)).toDouble()) } else{ v.heuristic = abs(destination.i.toDouble() - v.i.toDouble()) + abs(destination.j.toDouble() - v.j.toDouble()) } } } enum class Algorithm(val type: Int) { DIJKSTRA(1), ASTAR(2) } enum class Heuristic { MANHATTAN, EUCLIDEAN }
[ { "class_path": "youness-1__AlgoView__f420e99/com/example/algoview/ui/algoview/Graph.class", "javap": "Compiled from \"Graph.kt\"\npublic final class com.example.algoview.ui.algoview.Graph {\n private com.example.algoview.ui.algoview.Heuristic heuristicType;\n\n private java.util.ArrayList<com.example.alg...
TomPlum__advent-of-code-libs__c026ab7/library/src/main/kotlin/io/github/tomplum/libs/algorithm/DijkstrasAlgorithm.kt
package io.github.tomplum.libs.algorithm import java.util.* /** * A single node in a graph traversed by Dijkstra's algorithm. * * @param value The value of the node. Usually contains cartesian positional information. * @param distance The distance to this node from the starting point. */ data class Node<T>(val value: T, val distance: Int): Comparable<Node<T>> { override fun compareTo(other: Node<T>): Int { return distance.compareTo(other.distance) } } /** * Calculates the shortest distance to all nodes in a weighted-graph from the given [startingPositions] * and terminates based on the given [terminates] predicate. * * @param startingPositions A collection of nodes to start from. * @param evaluateAdjacency A function that is passed an instance of the current node and should return a collection of all adjacent nodes or "neighbours" that should be evaluated as part of the pathfinding. * @param processNode An optional function that is applied after the adjacency evaluation for each neighbouring node. Can be used to mutate the state of the node before evaluation. * @param terminates A boolean predicate used to determine when the destination node has been reached. When it evaluates as true, the algorithm is terminated and the shortest path for the current node is returned. * @return The shortest path from the starting nodes to the node that produces true when passed into the [terminates] predicate. */ fun <N> dijkstraShortestPath( startingPositions: Collection<N>, evaluateAdjacency: (currentNode: Node<N>) -> Collection<Node<N>>, processNode: (currentNode: Node<N>, adjacentNode: Node<N>) -> Node<N>, terminates: (currentNode: Node<N>) -> Boolean ): Int { // A map of nodes and the shortest distance from the given starting positions to it val distance = mutableMapOf<N, Int>() // Unsettled nodes that are yet to be evaluated. Prioritised by their distance from the start val next = PriorityQueue<Node<N>>() // Settled nodes whose shortest path has been calculated and need not be evaluated again val settled = mutableSetOf<N>() startingPositions.forEach { startingPosition -> next.offer(Node(startingPosition, 0)) } while(next.isNotEmpty()) { // Take the next node from the queue, ready for evaluation val currentNode = next.poll() // Considered the current node settled now settled.add(currentNode.value) // If the terminal condition has been met // (I.e. the current node is the location we want to find the shortest path to) // then we stop and return the current known shortest distance to it if (terminates(currentNode)) { return currentNode.distance } // Find all the adjacent nodes to the current one (as per the given predicate) // and evaluate each one evaluateAdjacency(currentNode).forEach { adjacentNode -> // Perform any additional processing on the adjacent node before evaluation val evaluationNode = processNode(currentNode, adjacentNode) if (!settled.contains(evaluationNode.value)) { // The new shortest path to the adjacent node is the current nodes distance // plus the weight of the node being evaluated val updatedDistance = currentNode.distance + evaluationNode.distance // If the distance of this new path is shorter than the shortest path we're // already aware of, then we can update it since we've found a shorter one if (updatedDistance < distance.getOrDefault(evaluationNode.value, Int.MAX_VALUE)) { // Track the new shortest path distance[evaluationNode.value] = updatedDistance // Queue up the adjacent node to continue down that path next.add(Node(evaluationNode.value, updatedDistance)) } } } } val message = "Could not find a path from the given starting positions to the node indicated by the terminates predicate." throw IllegalStateException(message) }
[ { "class_path": "TomPlum__advent-of-code-libs__c026ab7/io/github/tomplum/libs/algorithm/DijkstrasAlgorithmKt.class", "javap": "Compiled from \"DijkstrasAlgorithm.kt\"\npublic final class io.github.tomplum.libs.algorithm.DijkstrasAlgorithmKt {\n public static final <N> int dijkstraShortestPath(java.util.Col...
TomPlum__advent-of-code-libs__c026ab7/library/src/main/kotlin/io/github/tomplum/libs/extensions/CollectionExtensions.kt
package io.github.tomplum.libs.extensions import kotlin.math.pow /** * Returns the product of all the integers in the given list. */ fun List<Int>.product(): Int = if (isNotEmpty()) reduce { product, next -> product * next } else 0 fun List<Long>.product(): Long = if (isNotEmpty()) reduce { product, next -> product * next } else 0 /** * Converts the [IntArray] into its decimal equivalent. * This assumes the array contains only 1s and 0s. * @return The decimal representation. */ fun IntArray.toDecimal(): Long = reversed() .mapIndexed { i, bit -> if (bit == 1) 2.0.pow(i) else 0 } .sumOf { integer -> integer.toLong() } /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given set, meaning A and B are [this] and [other]. * * @see cartesianProductQuadratic for a variant that returns the product of itself. */ fun <S, T> List<S>.cartesianProduct(other: List<T>): List<Pair<S, T>> = this.flatMap { value -> List(other.size){ i -> Pair(value, other[i]) } } /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself, meaning both A and B are simply [this]. * * @see cartesianProductCubic for a variant that accepts another set. */ fun <T> List<T>.cartesianProductQuadratic(): List<Pair<T, T>> = this.flatMap { value -> List(this.size){ i -> Pair(value, this[i]) } } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning that A, B & C are all [this]. * * @see cartesianProductQuadratic for a variation that simply finds the product of itself. */ fun <T> List<T>.cartesianProductCubic(): List<Triple<T, T, T>> = cartesianProduct(this, this, this).map { set -> Triple(set[0], set[1], set[2]) } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning both A, B and C are [this], * [second] and [third] respectively. */ fun <T> List<T>.cartesianProductCubic(second: List<T>, third: List<T>): List<Triple<T, T, T>> = cartesianProduct(this, second, third).map { set -> Triple(set[0], set[1], set[2]) } /** * Finds the Cartesian Product of any number of given [sets]. */ private fun <T> cartesianProduct(vararg sets: List<T>): List<List<T>> = sets.fold(listOf(listOf())) { acc, set -> acc.flatMap { list -> set.map { element -> list + element } } } /** * Produces a list of all distinct pairs of elements from the given collection. * Pairs are considered distinct irrespective of their order. * * For example, given a collection of [A, B, C]: * - [A, A] is NOT considered distinct * - [A, B] and [B, A] are considered equal * - The output for this collection would be [[A, B], [A, C], [B, C]]. * * @return A list of all distinct pairs of elements. */ fun <T> Collection<T>.distinctPairs(): List<Pair<T, T>> = this.flatMapIndexed { i, element -> this.drop(i + 1).map { otherElement -> element to otherElement } } /** * Splits a collection based on the given [predicate]. * @param predicate A boolean predicate to determine when to split the list. * @return A collection of collections after splitting. */ fun <T> Collection<T>.split(predicate: (element: T) -> Boolean): Collection<Collection<T>> { var i = 0 val data = mutableMapOf<Int, List<T>>() var current = mutableListOf<T>() this.forEachIndexed { index, element -> if (index == this.size - 1) { current.add(element) data[i] = current } else if (predicate(element)) { data[i] = current i++ current = mutableListOf() } else { current.add(element) } } return data.values.toList() } /** * Calculates the lowest common multiple of * all the long values of this given list. */ fun List<Long>.lcm(): Long { if (this.isNotEmpty()) { var result = this[0] this.forEachIndexed { i, _ -> result = lcm(result, this[i]) } return result } throw IllegalArgumentException("Cannot find the LCM of an empty list.") } private fun lcm(a: Long, b: Long) = a * (b / gcd(a, b)) private fun gcd(a: Long, b: Long): Long { var n1 = a var n2 = b while (n1 != n2) { if (n1 > n2) n1 -= n2 else n2 -= n1 } return n1 }
[ { "class_path": "TomPlum__advent-of-code-libs__c026ab7/io/github/tomplum/libs/extensions/CollectionExtensionsKt.class", "javap": "Compiled from \"CollectionExtensions.kt\"\npublic final class io.github.tomplum.libs.extensions.CollectionExtensionsKt {\n public static final int product(java.util.List<java.la...
TomPlum__advent-of-code-2020__73b3eac/implementation/common/src/main/kotlin/io/github/tomplum/aoc/extensions/CollectionExtensions.kt
package io.github.tomplum.aoc.extensions import kotlin.math.pow /** * Returns the product of all of the integers in the given list. */ fun List<Int>.product(): Int = if (isNotEmpty()) reduce { product, next -> product * next } else 0 fun List<Long>.product(): Long = if (isNotEmpty()) reduce { product, next -> product * next } else 0 /** * Converts the [IntArray] into its decimal equivalent. * This assumes the array contains only 1s and 0s. * @return The decimal representation. */ fun IntArray.toDecimal(): Long = reversed() .mapIndexed { i, bit -> if (bit == 1) 2.0.pow(i) else 0 } .map { integer -> integer.toLong() } .sum() /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given set, meaning A and B are [this] and [other]. * * @see cartesianProductQuadratic for a variant that returns the product of itself. */ fun <S, T> List<S>.cartesianProduct(other: List<T>): List<Pair<S, T>> = this.flatMap { value -> List(other.size){ i -> Pair(value, other[i]) } } /** * For two sets A and B, the Cartesian product of A and B is denoted by A×B and defined as: * A×B = { (a,b) | aϵA and bϵB } * * Put simply, the Cartesian Product is the multiplication of two sets to form the set of all ordered pairs. * This function returns the cartesian product of itself, meaning both A and B are simply [this]. * * @see cartesianProductCubic for a variant that accepts another set. */ fun <T> List<T>.cartesianProductQuadratic(): List<Pair<T, T>> = this.flatMap { value -> List(this.size){ i -> Pair(value, this[i]) } } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning that A, B & C are all [this]. * * @see cartesianProductQuadratic for a variation that simply finds the product of itself. */ fun <T> List<T>.cartesianProductCubic(): List<Triple<T, T, T>> = cartesianProduct(this, this, this).map { set -> Triple(set[0], set[1], set[2]) } /** * For three sets A, B and C, the Cartesian product of A, B and C is denoted by A×B×C and defined as: * A×B×C = { (p, q, r) | pϵA and qϵB and rϵC } * * Put simply, the Cartesian Product is the multiplication of three sets to form the set of all ordered pairs. * This function returns the cartesian product of itself and the given sets, meaning both A, B and C are [this], * [second] and [third] respectively. */ fun <T> List<T>.cartesianProductCubic(second: List<T>, third: List<T>): List<Triple<T, T, T>> = cartesianProduct(this, second, third).map { set -> Triple(set[0], set[1], set[2]) } /** * Finds the Cartesian Product of any number of given [sets]. */ private fun <T> cartesianProduct(vararg sets: List<T>): List<List<T>> = sets.fold(listOf(listOf())) { acc, set -> acc.flatMap { list -> set.map { element -> list + element } } }
[ { "class_path": "TomPlum__advent-of-code-2020__73b3eac/io/github/tomplum/aoc/extensions/CollectionExtensionsKt.class", "javap": "Compiled from \"CollectionExtensions.kt\"\npublic final class io.github.tomplum.aoc.extensions.CollectionExtensionsKt {\n public static final int product(java.util.List<java.lang...
TomPlum__advent-of-code-2020__73b3eac/implementation/src/main/kotlin/io/github/tomplum/aoc/ferry/docking/program/BitMask.kt
package io.github.tomplum.aoc.ferry.docking.program /** * A bit-mask consisting of either 0, 1 or X. * * An X indicates a 'Floating Bit' that is in a state of super-position and is therefore * simultaneously a 0 and a 1. This means that every [mask] with a floating-bit has * 2^N permutations wheres N is the number of floating-bits. * * @param mask The string of bits. */ data class BitMask(private val mask: String) { /** * Masks the given [value] with the [mask] bits. * Any floating-bits (X) are ignored. * * E.g; * [value]: 000000000000000000000000000000001011 (decimal 11) * [mask]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X * result: 000000000000000000000000000001001001 (decimal 73) * * @return The binary representation of the masked [value]. */ fun applyTo(value: Int): String { return mask.zip(value.to36bit()) { mask, bit -> when (mask) { '0', '1' -> mask else -> bit } }.joinToString("") } /** * Masks the given [value] with the [mask] bits. * Floating-bits are taken into account and so all mask permutations are applied. * * E.g; * * First, [applyIgnoreFloating] masks the [value] and ignores floating-bits. * [value]: 000000000000000000000000000000101010 (decimal 42) * [mask]: 000000000000000000000000000000X1001X * result: 000000000000000000000000000000X1101X * * Then, [getFloatingPermutations] generates all combinations of masks. * 000000000000000000000000000000011010 (decimal 26) * 000000000000000000000000000000011011 (decimal 27) * 000000000000000000000000000000111010 (decimal 58) * 000000000000000000000000000000111011 (decimal 59) * * @return The binary representations of all the masked values. */ fun applyFloatingTo(value: Int): List<String> { val floatingMask = applyIgnoreFloating(value) return getFloatingPermutations(floatingMask, mutableListOf()) } /** * Masks the given [value] with only literal floating and 1 bits. * 0 bits are ignored. * * E.g; * [value]: 000000000000000000000000000000101010 (decimal 42) * [mask]: 000000000000000000000000000000X1001X * result: 000000000000000000000000000000X1101X * * @return The masked value with floating bits intact. */ private fun applyIgnoreFloating(value: Int): String { return mask.zip(value.to36bit()) { mask, bit -> when (mask) { 'X', '1' -> mask else -> bit } }.joinToString("") } /** * Generates all the combinations of masks by resolving the floating-bits state of * super-position. For a [mask] with N floating-bits, 2^N masks will be produced. * @param mask The mask containing 'X' floating-bit values. * @param masks The list to collect the mask combinations in. * @return A list of all mask combinations. */ private fun getFloatingPermutations(mask: String, masks: MutableList<String>): List<String> { if (mask.contains('X')) { val firstCandidate = mask.replaceFirst('X', '0') if (!masks.contains(firstCandidate)) { getFloatingPermutations(firstCandidate, masks) } val secondCandidate = mask.replaceFirst('X', '1') if (!masks.contains(secondCandidate)) { getFloatingPermutations(secondCandidate, masks) } } if (!mask.contains('X')) masks.add(mask) return masks } /** * Pads a binary string with 0s until it is 36 bits in length. * @return A 36-bit representation of the given binary string. */ private fun Int.to36bit(): String = toString(2).padStart(36, '0') }
[ { "class_path": "TomPlum__advent-of-code-2020__73b3eac/io/github/tomplum/aoc/ferry/docking/program/BitMask.class", "javap": "Compiled from \"BitMask.kt\"\npublic final class io.github.tomplum.aoc.ferry.docking.program.BitMask {\n private final java.lang.String mask;\n\n public io.github.tomplum.aoc.ferry....
DPNT-Sourcecode__CHK-edzx01__b1947b8/src/main/kotlin/solutions/CHK/CheckoutSolution.kt
package solutions.CHK import kotlin.jvm.internal.Intrinsics.Kotlin object CheckoutSolution { fun checkout(skus: String): Int { var total = 0 val counts = mutableMapOf<Char, Int>() val groupDiscountItems = listOf('S', 'T', 'X', 'Y', 'Z') val individualPrices = mapOf('S' to 20, 'T' to 20, 'X' to 17, 'Y' to 20, 'Z' to 21) for (item in skus) { when (item) { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' -> counts[item] = counts.getOrDefault(item, 0) + 1 else -> return -1 } } // Handle group discount offers var groupDiscountCount = groupDiscountItems.sumBy { counts.getOrDefault(it, 0) } while (groupDiscountCount >= 3) { total += 45 groupDiscountCount -= 3 // Remove the items that were part of the group discount from the counts map for (item in groupDiscountItems) { if (counts.getOrDefault(item, 0) > 0) { counts[item] = counts.getOrDefault(item, 0) - 1 } } } total += groupDiscountItems.sumBy { counts.getOrDefault(it, 0) * individualPrices.getOrDefault(it, 0) } // Handle E offers while (counts.getOrDefault('E', 0) >= 2) { total += 80 counts['E'] = counts.getOrDefault('E', 0) - 2 if (counts.getOrDefault('B', 0) > 0) { counts['B'] = counts.getOrDefault('B', 0) - 1 } } total += counts.getOrDefault('E', 0) * 40 // Handle F offers while (counts.getOrDefault('F', 0) >= 3) { total += 20 counts['F'] = counts.getOrDefault('F', 0) - 3 } total += counts.getOrDefault('F', 0) * 10 // Handle H offers while (counts.getOrDefault('H', 0) >= 10) { total += 80 counts['H'] = counts.getOrDefault('H', 0) - 10 } while (counts.getOrDefault('H', 0) >= 5) { total += 45 counts['H'] = counts.getOrDefault('H', 0) - 5 } total += counts.getOrDefault('H', 0) * 10 // Handle K offers while (counts.getOrDefault('K', 0) >= 2) { total += 120 counts['K'] = counts.getOrDefault('K', 0) - 2 } total += counts.getOrDefault('K', 0) * 70 // Handle N offers while (counts.getOrDefault('N', 0) >= 3) { total += 120 counts['N'] = counts.getOrDefault('N', 0) - 3 if (counts.getOrDefault('M', 0) > 0) { counts['M'] = counts.getOrDefault('M', 0) - 1 } } total += counts.getOrDefault('N', 0) * 40 // Handle P offers while (counts.getOrDefault('P', 0) >= 5) { total += 200 counts['P'] = counts.getOrDefault('P', 0) - 5 } total += counts.getOrDefault('P', 0) * 50 // Handle R offers while (counts.getOrDefault('R', 0) >= 3) { total += 150 counts['R'] = counts.getOrDefault('R', 0) - 3 if (counts.getOrDefault('Q', 0) > 0) { counts['Q'] = counts.getOrDefault('Q', 0) - 1 } } total += counts.getOrDefault('R', 0) * 50 // Handle Q offers while (counts.getOrDefault('Q', 0) >= 3) { total += 80 counts['Q'] = counts.getOrDefault('Q', 0) - 3 } total += counts.getOrDefault('Q', 0) * 30 // Handle U offers while (counts.getOrDefault('U', 0) >= 4) { total += 120 counts['U'] = counts.getOrDefault('U', 0) - 4 } total += counts.getOrDefault('U', 0) * 40 // Handle V offers while (counts.getOrDefault('V', 0) >= 3) { total += 130 counts['V'] = counts.getOrDefault('V', 0) - 3 } while (counts.getOrDefault('V', 0) >= 2) { total += 90 counts['V'] = counts.getOrDefault('V', 0) - 2 } total += counts.getOrDefault('V', 0) * 50 // Handle A offers total += (counts.getOrDefault('A', 0) / 5) * 200 counts['A'] = counts.getOrDefault('A', 0) % 5 total += (counts.getOrDefault('A', 0) / 3) * 130 counts['A'] = counts.getOrDefault('A', 0) % 3 total += counts.getOrDefault('A', 0) * 50 // Handle B offers total += (counts.getOrDefault('B', 0) / 2) * 45 counts['B'] = counts.getOrDefault('B', 0) % 2 total += counts.getOrDefault('B', 0) * 30 // Handle C and D total += counts.getOrDefault('C', 0) * 20 total += counts.getOrDefault('D', 0) * 15 // Handle G, I, J, L, O, S, T, W, Y, Z total += counts.getOrDefault('G', 0) * 20 total += counts.getOrDefault('I', 0) * 35 total += counts.getOrDefault('J', 0) * 60 total += counts.getOrDefault('L', 0) * 90 total += counts.getOrDefault('M', 0) * 15 total += counts.getOrDefault('O', 0) * 10 total += counts.getOrDefault('W', 0) * 20 return total } }
[ { "class_path": "DPNT-Sourcecode__CHK-edzx01__b1947b8/solutions/CHK/CheckoutSolution.class", "javap": "Compiled from \"CheckoutSolution.kt\"\npublic final class solutions.CHK.CheckoutSolution {\n public static final solutions.CHK.CheckoutSolution INSTANCE;\n\n private solutions.CHK.CheckoutSolution();\n ...
TimCastelijns__aoc2017__656f2a4/src/day3/p2.kt
package day3 enum class Direction { RIGHT, UP, LEFT, DOWN } var n = 100 val grid = Array(n) { Array(n, { "" }) } fun surroundingsSum(x: Int, y: Int): Int { var sum = 0 if (y > 0 && x > 0) { if (grid[y - 1][x - 1] != "") { val add = grid[y - 1][x - 1].trim().toInt() sum += add } } if (y > 0 && x <= n - 1) { if (grid[y - 1][x] != "") { val add = grid[y - 1][x].trim().toInt() sum += add } } if (y > 0 && x < n - 1) { if (grid[y - 1][x + 1] != "") { val add = grid[y - 1][x + 1].trim().toInt() sum += add } } if (x > 0 && y <= n - 1) { if (grid[y][x - 1] != "") { val add = grid[y][x - 1].trim().toInt() sum += add } } if (x < n - 1 && y <= n - 1) { if (grid[y][x + 1] != "") { val add = grid[y][x + 1].trim().toInt() sum += add } } if (y < n - 1 && x > 0) { if (grid[y + 1][x - 1] != "") { val add = grid[y + 1][x - 1].trim().toInt() sum += add } } if (x <= n - 1 && y < n - 1) { if (grid[y + 1][x] != "") { val add = grid[y + 1][x].trim().toInt() sum += add } } if (y < n - 1 && x < n - 1) { if (grid[y + 1][x + 1] != "") { val add = grid[y + 1][x + 1].trim().toInt() sum += add } } return sum } fun main(args: Array<String>) { var dir = Direction.RIGHT var y = n / 2 var x = if (n % 2 == 0) y - 1 else y var iteration = 0; for (j in 1..n * n - 1 + 1) { iteration++; if (iteration == 1) { grid[y][x] = "1" } else { val s = surroundingsSum(x, y) if (s > 265149) { println(s) break } grid[y][x] = "%d".format(s) } when (dir) { Direction.RIGHT -> if (x <= n - 1 && grid[y - 1][x].none() && j > 1) dir = Direction.UP Direction.UP -> if (grid[y][x - 1].none()) dir = Direction.LEFT Direction.LEFT -> if (x == 0 || grid[y + 1][x].none()) dir = Direction.DOWN Direction.DOWN -> if (grid[y][x + 1].none()) dir = Direction.RIGHT } when (dir) { Direction.RIGHT -> x++ Direction.UP -> y-- Direction.LEFT -> x-- Direction.DOWN -> y++ } } for (row in grid) println(row.joinToString("") { s -> "[%6d]".format(s.toInt()) }) println() }
[ { "class_path": "TimCastelijns__aoc2017__656f2a4/day3/P2Kt$WhenMappings.class", "javap": "Compiled from \"p2.kt\"\npublic final class day3.P2Kt$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n static {};\n Code:\n 0: invokestatic #14 // Method day3/Direction.v...
TimCastelijns__aoc2017__656f2a4/src/day7/day7.kt
package day7 import java.io.File fun main(args: Array<String>) { p1(File("src/day7/input")) p2(File("src/day7/input")) } fun p1(file: File) { val programs = mutableListOf<String>() val subPrograms = mutableListOf<String>() file.forEachLine { line -> val parts = line.split(" ") val program = parts[0] programs.add(program) val weight = parts[1].trim('(', ')').toInt() if ("->" in parts) { parts.subList(3, parts.size) .map { it -> it.trim(',') } .forEach { s -> subPrograms.add(s) } } } programs.forEach { program -> if (!subPrograms.contains(program)) { println(program) } } } val programWeights = mutableMapOf<String, Int>() val directSubs = mutableMapOf<String, List<String>>() fun p2(file: File) { val programs = mutableListOf<String>() val subPrograms = mutableListOf<String>() file.forEachLine { line -> val parts = line.split(" ") val program = parts[0] programs.add(program) val weight = parts[1].trim('(', ')').toInt() programWeights.put(program, weight) if ("->" in parts) { val subs = parts.subList(3, parts.size) .map { it -> it.trim(',') } subs.forEach { s -> subPrograms.add(s) } directSubs.put(program, subs) } } val programTotalWeights = mutableMapOf<String, Int>() for (p: String in programs) { if (directSubs.containsKey(p)) { programTotalWeights.put(p, getWeightOfProgramAndSubs(p)) } else { programTotalWeights.put(p, programWeights[p]!!) } } for (p: String in programs.filter { directSubs.containsKey(it) }) { val weights = directSubs[p]!!.map { programTotalWeights[it]!! } if (weights.toSet().size != 1) { println(programTotalWeights[p]) println(weights) directSubs[p]!!.forEach { t: String? -> print("${programWeights[t]} - ") } println() println(programWeights[p]) println() } } } fun getWeightOfProgramAndSubs(name: String): Int { var weight = 0 weight += programWeights[name]!! // start with weight of the program itself // recursively add weights of sub programs if (directSubs.containsKey(name)) { for (sub: String in directSubs[name]!!) { weight += getWeightOfProgramAndSubs(sub) } } return weight }
[ { "class_path": "TimCastelijns__aoc2017__656f2a4/day7/Day7Kt.class", "javap": "Compiled from \"day7.kt\"\npublic final class day7.Day7Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> programWeights;\n\n private static final java.util.Map<java.lang.String, java.util.List<java....
TimCastelijns__aoc2017__656f2a4/src/day8/day8.kt
package day8 import java.io.File fun main(args: Array<String>) { val lines = File("src/day8/input").readLines() p1(lines) p2(lines) } fun p1(lines: List<String>) { val values = mutableMapOf<String, Int>() for (line in lines) { values.put(line.split(" ")[0], 0) } for (line in lines) { val parts = line.split(" ") val subject = parts[0] val operator = parts[1] val n = parts[2].toInt() val condition = parts.subList(4, parts.size) if (checkCondition(condition, values)) { val currentValue = values[subject]!! if (operator == "inc") { values[subject] = currentValue + n } else if (operator == "dec") { values[subject] = currentValue - n } } } println(values.values.max()) } fun p2(lines: List<String>) { val values = mutableMapOf<String, Int>() var max = 0; for (line in lines) { values.put(line.split(" ")[0], 0) } for (line in lines) { val parts = line.split(" ") val subject = parts[0] val operator = parts[1] val n = parts[2].toInt() val condition = parts.subList(4, parts.size) if (checkCondition(condition, values)) { val currentValue = values[subject]!! if (operator == "inc") { values[subject] = currentValue + n } else if (operator == "dec") { values[subject] = currentValue - n } if (values[subject]!! > max) { max = values[subject]!! } } } println(max) } fun checkCondition(condition: List<String>, values: Map<String, Int>): Boolean { val a = values[condition[0]]!!.toInt() val b = condition[2].toInt() return when (condition[1]) { "==" -> a == b "!=" -> a != b ">" -> a > b "<" -> a < b ">=" -> a >= b "<=" -> a <= b else -> false } }
[ { "class_path": "TimCastelijns__aoc2017__656f2a4/day8/Day8Kt.class", "javap": "Compiled from \"day8.kt\"\npublic final class day8.Day8Kt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String args\n 3: invokestatic ...
ykrytsyn__leetcode-in-kotlin__0acf2a6/src/main/kotlin/leetcode/TwoSum.kt
package leetcode /** * # 1. Two Sum * [https://leetcode.com/problems/two-sum/](https://leetcode.com/problems/two-sum/) * * ### Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. * ### You may assume that each input would have exactly one solution, and you may not use the same element twice. * ### You can return the answer in any order. * */ class TwoSum { /** * Brute Force */ fun bruteForce(nums: IntArray, target: Int): IntArray? { for (i in nums.indices) { for (j in i + 1 until nums.size) { if (nums[j] == target - nums[i]) { return intArrayOf(i, j) } } } // In case there is no solution, we'll just return null return null } /** * Two-pass Hash Table */ fun twoPassHashTable(nums: IntArray, target: Int): IntArray? { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { map[nums[i]] = i } for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement) && map[complement] != i) { return intArrayOf(i, map[complement]!!) } } // In case there is no solution, we'll just return null return null } /** * One-pass Hash Table */ fun onePassHashTable(nums: IntArray, target: Int): IntArray? { val map: MutableMap<Int, Int> = HashMap() for (i in nums.indices) { val complement = target - nums[i] if (map.containsKey(complement)) { return intArrayOf(map[complement]!!, i) } map[nums[i]] = i } // In case there is no solution, we'll just return null return null } }
[ { "class_path": "ykrytsyn__leetcode-in-kotlin__0acf2a6/leetcode/TwoSum.class", "javap": "Compiled from \"TwoSum.kt\"\npublic final class leetcode.TwoSum {\n public leetcode.TwoSum();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
ykrytsyn__leetcode-in-kotlin__0acf2a6/src/main/kotlin/leetcode/UniquePaths.kt
package leetcode /** * # 62. Unique Paths * [https://leetcode.com/problems/unique-paths/](https://leetcode.com/problems/unique-paths/) * * ### A robot is located at the top-left corner of 'm x n' grid (marked 'Start' in the diagram below). * ### The robot can only move either down or right at any point in time. * ### The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). * * ### How many possible unique paths are there? * */ class UniquePaths { fun dynamicProgramming(m: Int, n: Int): Int { val grid: Array<IntArray> = Array(m) { IntArray(n) } for (i in m - 1 downTo 0) { for (j in n - 1 downTo 0) { if (i == m - 1 || j == n - 1) { grid[i][j] = 1 } else { grid[i][j] = grid[i + 1][j] + grid[i][j + 1] } } } return grid[0][0]; } fun recursive(m: Int, n: Int): Int { if (m == 1 || n == 1) { return 1 } return recursive(m - 1, n) + recursive(m, n - 1) } }
[ { "class_path": "ykrytsyn__leetcode-in-kotlin__0acf2a6/leetcode/UniquePaths.class", "javap": "Compiled from \"UniquePaths.kt\"\npublic final class leetcode.UniquePaths {\n public leetcode.UniquePaths();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"...
ykrytsyn__leetcode-in-kotlin__0acf2a6/src/main/kotlin/leetcode/ArrangingCoins.kt
package leetcode /** * # 441. Arranging Coins * [https://leetcode.com/problems/arranging-coins/](https://leetcode.com/problems/arranging-coins/) * * ### You have n coins and you want to build a staircase with these coins. * ### The staircase consists of k rows where the ith row has exactly i coins. * ### The last row of the staircase may be incomplete. * ### Given the integer n, return the number of complete rows of the staircase you will build. * * ### Constraints: * 1 <= n <= 2^31 - 1 */ class ArrangingCoins { /** * Brute force solution: checking every step one by one while we have enough coins for step's capacity */ fun bruteForce(n: Int): Int { var coins = n if (coins <= 1) { return coins } var completedSteps = 0 var currentStep = 1 while (currentStep <= coins) { completedSteps = currentStep coins -= currentStep currentStep++ } return completedSteps } /** * Find the maximum K such that (K*(K+1))/2 <= N * Using Long type due to constraints */ fun binarySearch(n: Int): Int { var left: Long = 0 var right = n.toLong() var k: Long var curr: Long while (left <= right) { k = left + (right - left) / 2 curr = k * (k + 1) / 2 if (curr == n.toLong()) { return k.toInt() } if (n < curr) { right = k - 1 } else { left = k + 1 } } return right.toInt() } }
[ { "class_path": "ykrytsyn__leetcode-in-kotlin__0acf2a6/leetcode/ArrangingCoins.class", "javap": "Compiled from \"ArrangingCoins.kt\"\npublic final class leetcode.ArrangingCoins {\n public leetcode.ArrangingCoins();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/la...
SanderSmee__adventofcode-2018__e5fc4ae/src/main/kotlin/adventofcode/day2/Day2.kt
package adventofcode.day2 import java.io.File /** * */ fun main(args: Array<String>) { val input = File(ClassLoader.getSystemResource("day-02-input.txt").file).readLines() // part 1 val (twos, threes, checksum) = calculateChecksum(input) println("$twos x $threes = $checksum") // part 2 val firstDiff = findCloseIds(input).first() val result = firstDiff.first.removeRange(firstDiff.indices.first()..firstDiff.indices.first()) println("${result}") } private fun calculateChecksum(input: List<String>): Triple<Int, Int, Int> { val countedBoxIds = input.map { toLetterCount(it) } val twosCount = countedBoxIds.filter { it.countsForTwo() }.size val threesCount = countedBoxIds.filter { it.countsForThree() }.size return Triple(twosCount, threesCount, twosCount * threesCount) } private fun toLetterCount(boxId: String): BoxIdLetterCount { val letterCounts = boxId.toList() .groupingBy { it } .eachCount() .map { LetterCount(it.key, it.value) } return BoxIdLetterCount(boxId, letterCounts) } data class BoxIdLetterCount(val boxId: String, val letters: List<LetterCount>) { fun countsForTwo() = letters.find { it.count == 2 } != null fun countsForThree() = letters.find { it.count == 3 } != null } class LetterCount(val letter: Char, val count: Int) { } private fun findCloseIds(boxIds: List<String>): MutableList<Diff> { val boxIdsDifferentBy1 = mutableListOf<Diff>() for (first in boxIds) { for (second in boxIds) { val diff = first.diff(second) if (diff.indices.size == 1) { boxIdsDifferentBy1.add(diff) } } } return boxIdsDifferentBy1 } fun String.diff(other: String): Diff { val indices = mutableListOf<Int>() for (i in 0 until Math.min(this.length, other.length)) { if (this[i] != other[i]) { indices.add(i) } } return Diff(this, other, indices) } data class Diff(val first:String, val second:String, val indices:List<Int>)
[ { "class_path": "SanderSmee__adventofcode-2018__e5fc4ae/adventofcode/day2/Day2Kt$toLetterCount$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class adventofcode.day2.Day2Kt$toLetterCount$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.Character...
fwcd__kotlin-language-server__eee8afa/shared/src/main/kotlin/org/javacs/kt/util/StringUtils.kt
package org.javacs.kt.util /** * Computes a string distance using a slightly modified * variant of the SIFT4 algorithm in linear time. * Note that the function is asymmetric with respect to * its two input strings and thus is not a metric in the * mathematical sense. * * Based on the JavaScript implementation from * https://siderite.dev/blog/super-fast-and-accurate-string-distance.html/ * * @param candidate The first string * @param pattern The second string * @param maxOffset The number of characters to search for matching letters */ fun stringDistance(candidate: CharSequence, pattern: CharSequence, maxOffset: Int = 4): Int = when { candidate.length == 0 -> pattern.length pattern.length == 0 -> candidate.length else -> { val candidateLength = candidate.length val patternLength = pattern.length var iCandidate = 0 var iPattern = 0 var longestCommonSubsequence = 0 var localCommonSubstring = 0 while (iCandidate < candidateLength && iPattern < patternLength) { if (candidate[iCandidate] == pattern[iPattern]) { localCommonSubstring++ } else { longestCommonSubsequence += localCommonSubstring localCommonSubstring = 0 if (iCandidate != iPattern) { // Using max to bypass the need for computer transpositions ("ab" vs "ba") val iMax = Math.max(iCandidate, iPattern) iCandidate = iMax iPattern = iMax if (iMax >= Math.min(candidateLength, patternLength)) { break } } searchWindow@ for (i in 0 until maxOffset) { when { (iCandidate + i) < candidateLength -> { if (candidate[iCandidate + i] == pattern[iPattern]) { iCandidate += i localCommonSubstring++ break@searchWindow } } (iPattern + i) < patternLength -> { if (candidate[iCandidate] == pattern[iPattern + i]) { iPattern += i localCommonSubstring++ break@searchWindow } } else -> break@searchWindow } } } iCandidate++ iPattern++ } longestCommonSubsequence += localCommonSubstring Math.max(candidateLength, patternLength) - longestCommonSubsequence } } /** Checks whether the candidate contains the pattern in order. */ fun containsCharactersInOrder(candidate: CharSequence, pattern: CharSequence, caseSensitive: Boolean): Boolean { var iCandidate = 0 var iPattern = 0 while (iCandidate < candidate.length && iPattern < pattern.length) { var patternChar = pattern[iPattern] var testChar = candidate[iCandidate] if (!caseSensitive) { patternChar = patternChar.lowercaseChar() testChar = testChar.lowercaseChar() } if (patternChar == testChar) { iPattern++ } iCandidate++ } return iPattern == pattern.length }
[ { "class_path": "fwcd__kotlin-language-server__eee8afa/org/javacs/kt/util/StringUtilsKt.class", "javap": "Compiled from \"StringUtils.kt\"\npublic final class org.javacs.kt.util.StringUtilsKt {\n public static final int stringDistance(java.lang.CharSequence, java.lang.CharSequence, int);\n Code:\n ...
poblish__BabyNamesKotlin__2935612/src/org/hiatusuk/BabyNamesBoys.kt
package org.hiatusuk fun main(args: Array<String>) { val foreNames = arrayOf("Rohan","Nathaniel","Anthony","Chris","Jonathan","Lemur","Harry","Percy","Peregrine","James","Jamie","Sidney","Gabriel","Leyton","Curtley","Jarvis"); val middleNames = arrayOf("Rohan","Nathaniel","Tony","Chris","Jonathan","Lemur","Harry","Percy","Peregrine","James","Jamie","Sidney","Gabriel","Leyton","Curtley","Jarvis"); foreNames.sort() middleNames.sort() var count = 0 for (name1 in foreNames) { count++ println("" + count + " ... " + name1 + " Jordan-Regan") val syllables1 = syllableCount(name1) for (name2 in middleNames) { if (name1 != name2) { val syllables2 = syllableCount(name2) if (name1[0] == name2[0] || (syllables1 == 1 && syllables2 == 1) || (syllables1 == 1 && syllables2 >= 3) || (syllables1 >= 3 && syllables2 >= 3) || (syllables1 >= 3 && syllables2 == 1)) { continue } count++ println("" + count + " ... " + name1 + " " + name2 + " Jordan-Regan") } } } } fun isVowel(inChar: Char) : Boolean { return (inChar == 'a' || inChar == 'e' || inChar == 'i' || inChar == 'o' || inChar == 'u') } fun syllableCount(inStr: String): Int { if (inStr == "Anthony" || inStr == "Gabriel") { return 3 } if (inStr == "James") { return 1 } var syllables = 0 var lastChar = '.' var wasVowel = false for (idx in inStr.indices) { val c = inStr[idx] if (wasVowel && ((lastChar == 'u' && c == 'a') || (lastChar == 'i' && c == 'a'))) { syllables++ } else if (isVowel(c) || c == 'y') { if (!wasVowel && (!(c == 'e') || idx < inStr.length - 1)) { syllables++ wasVowel = true } } else { wasVowel = false } lastChar = c } return if (syllables == 0) 1 else syllables }
[ { "class_path": "poblish__BabyNamesKotlin__2935612/org/hiatusuk/BabyNamesBoysKt.class", "javap": "Compiled from \"BabyNamesBoys.kt\"\npublic final class org.hiatusuk.BabyNamesBoysKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ...
MBM1607__matrix-calculator__9619a1b/Main.kt
package processor import java.util.Scanner import kotlin.math.min import kotlin.math.pow val scanner = Scanner(System.`in`) fun readMatrix(messageInfix: String = ""): Array<DoubleArray> { print("Enter size of ${messageInfix}matrix: ") val row = scanner.nextInt() val col = scanner.nextInt() val matrix = Array(row) { DoubleArray(col) } println("Enter ${messageInfix}matrix:") for (i in 0 until row) { for (j in 0 until col) { matrix[i][j] = scanner.nextDouble() } } return matrix } fun printMatrix(matrix: Array<DoubleArray>) { for (i in matrix.indices) { var line = "" for (j in matrix[0].indices) { line += "${matrix[i][j]} " } println(line) } } fun addMatrices(matrix1: Array<DoubleArray>, matrix2: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val sumMatrix = Array(matrix1[0].size) { DoubleArray(matrix2.size) } if (matrix1.size == matrix2.size && matrix1[0].size == matrix2[0].size) { for (i in matrix1.indices) { for (j in matrix1[0].indices) sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j] } } else { if (log) println("The operation cannot be performed.") } return sumMatrix } fun multiplyMatrices(matrix1: Array<DoubleArray>, matrix2: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val productMatrix = Array(matrix1.size) { DoubleArray(matrix2[0].size) } if (matrix1[0].size == matrix2.size) { for (i in matrix1.indices) { for (j in matrix2[0].indices) { var sum = 0.0 for (k in matrix1[0].indices) { sum += matrix1[i][k] * matrix2[k][j] } productMatrix[i][j] = sum } } } else { if (log) println("The operation cannot be performed.") } return productMatrix } fun multiplyByConstant(constant: Double, matrix: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val productMatrix = Array(matrix.size) { DoubleArray(matrix[0].size) } for (i in matrix.indices) { for (j in matrix[0].indices) { productMatrix[i][j] = constant * matrix[i][j] } } return productMatrix } fun transposeMatrix() { println() println("1. Main diagonal\n" + "2. Side diagonal\n" + "3. Vertical line\n" + "4. Horizontal line") print("Your choice: ") val choice = readLine()!! println("The result is:") when (choice) { "1" -> printMatrix(transposeMain(readMatrix())) "2" -> printMatrix(transposeSide(readMatrix())) "3" -> printMatrix(transposeVertical(readMatrix())) "4" -> printMatrix(transposeHorizontal(readMatrix())) else -> println("Invalid choice") } } fun transposeMain(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[j][i] = matrix[i][j] } } return transpose } fun transposeSide(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[matrix.lastIndex - j][matrix[0].lastIndex - i] = matrix[i][j] } } return transpose } fun transposeVertical(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[i][matrix[0].lastIndex - j] = matrix[i][j] } } return transpose } fun transposeHorizontal(matrix: Array<DoubleArray>): Array<DoubleArray> { val transpose = Array(matrix[0].size) { DoubleArray(matrix.size) } for (i in matrix.indices) { for (j in matrix[0].indices) { transpose[matrix.lastIndex - i][j] = matrix[i][j] } } return transpose } // Get the minor matrix from the original matrix after excluding the given row and column fun getCofactor(matrix: Array<DoubleArray>, row: Int, col: Int): Double { val minor = Array(matrix[0].size - 1) { DoubleArray(matrix.size - 1) } val temp = matrix.filterIndexed { i, _ -> i != row }.toTypedArray() for (i in temp.indices) { minor[i] = temp[i].filterIndexed { j, _ -> j != col }.toDoubleArray() } return determinant(minor) * (-1.0).pow(row + col) } // Get the determinant of a matrix fun determinant(matrix: Array<DoubleArray>): Double { return if (matrix.size == 2) { matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0] } else { var result = 0.0 for (j in matrix.indices) result += getCofactor(matrix, 0, j) * matrix[0][j] result } } fun calcDeterminant() { val matrix = readMatrix() println("The result is:") if (matrix.size == matrix[0].size) { println(determinant(matrix)) } else { println("The operation cannot be performed.") } } fun getAdjoint(matrix: Array<DoubleArray>): Array<DoubleArray> { val adjoint = Array(matrix.size) { DoubleArray(matrix[0].size) } for (i in matrix.indices) { for (j in matrix[0].indices) { adjoint[i][j] = getCofactor(matrix, i, j) } } return transposeMain(adjoint) } fun inverseMatrix(matrix: Array<DoubleArray>, log: Boolean = true): Array<DoubleArray> { if (log) println("The result is:") val det = determinant(matrix) return if (det != 0.0) { multiplyByConstant(1 / det, getAdjoint(matrix), false) } else { if (log) println("This matrix doesn't have an inverse.") Array(matrix.size) { DoubleArray(matrix[0].size) } } } fun main() { while (true) { println("1. Add matrices\n" + "2. Multiply matrix by a constant\n" + "3. Multiply matrices\n" + "4. Transpose matrix\n" + "5. Calculate a determinant\n" + "6. Inverse matrix\n" + "0. Exit") print("Your choice: ") when (readLine()) { "0" -> return "1" -> printMatrix(addMatrices(readMatrix("first "), readMatrix("second "))) "2" -> { val matrix = readMatrix() print("Enter constant:") printMatrix(multiplyByConstant(scanner.nextDouble(), matrix)) } "3" -> printMatrix(multiplyMatrices(readMatrix("first "), readMatrix("second "))) "4" -> transposeMatrix() "5" -> calcDeterminant() "6" -> printMatrix(inverseMatrix(readMatrix())) else -> println("Invalid choice") } println() } }
[ { "class_path": "MBM1607__matrix-calculator__9619a1b/processor/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class processor.MainKt {\n private static final java.util.Scanner scanner;\n\n public static final java.util.Scanner getScanner();\n Code:\n 0: getstatic #11 ...
henopied__road-runner__19d7799/core/src/main/kotlin/com/acmerobotics/roadrunner/util/MathUtil.kt
package com.acmerobotics.roadrunner.util import kotlin.math.* /** * Various math utilities. */ object MathUtil { /** * Returns the real solutions to the quadratic [a]x^2 + [b]x + [c] = 0. */ @JvmStatic fun solveQuadratic(a: Double, b: Double, c: Double): DoubleArray { if (a epsilonEquals 0.0) { return doubleArrayOf(-c / b) } val disc = b * b - 4 * a * c return when { disc epsilonEquals 0.0 -> doubleArrayOf(-b / (2 * a)) disc > 0.0 -> doubleArrayOf( (-b + sqrt(disc)) / (2 * a), (-b - sqrt(disc)) / (2 * a) ) else -> doubleArrayOf() } } /** * Similar to Java cbrt, but implemented with kotlin math (preserves sign) */ @JvmStatic fun cbrt(x: Double) = sign(x) * abs(x).pow(1.0 / 3.0) /** * Returns real solutions to the cubic [a]x^3 + [b]x^2 + [c]x + [d] = 0 * [Reference](https://github.com/davidzof/wattzap/blob/a3065da/src/com/wattzap/model/power/Cubic.java#L125-L182) */ @JvmStatic fun solveCubic(a: Double, b: Double, c: Double, d: Double): DoubleArray { if (a epsilonEquals 0.0) { return solveQuadratic(b, c, d) } val a2 = b / a val a1 = c / a val a0 = d / a val lambda = a2 / 3.0 val Q = (3.0 * a1 - a2 * a2) / 9.0 val R = (9.0 * a1 * a2 - 27.0 * a0 - 2.0 * a2 * a2 * a2) / 54.0 val Q3 = Q * Q * Q val R2 = R * R val D = Q3 + R2 return when { D < 0.0 -> { // 3 unique reals val theta = acos(R / sqrt(-Q3)) val sqrtQ = sqrt(-Q) doubleArrayOf( 2.0 * sqrtQ * cos(theta / 3.0) - lambda, 2.0 * sqrtQ * cos((theta + 2.0 * PI) / 3.0) - lambda, 2.0 * sqrtQ * cos((theta + 4.0 * PI) / 3.0) - lambda ) } D > 0.0 -> { // 1 real val sqrtD = sqrt(D) val S = cbrt(R + sqrtD) val T = cbrt(R - sqrtD) doubleArrayOf(S + T - lambda) } else -> { // 2 unique (3 total) reals val cbrtR = cbrt(R) doubleArrayOf(2.0 * cbrtR - lambda, -cbrtR - lambda) } } } } const val EPSILON = 1e-6 infix fun Double.epsilonEquals(other: Double) = abs(this - other) < EPSILON
[ { "class_path": "henopied__road-runner__19d7799/com/acmerobotics/roadrunner/util/MathUtil.class", "javap": "Compiled from \"MathUtil.kt\"\npublic final class com.acmerobotics.roadrunner.util.MathUtil {\n public static final com.acmerobotics.roadrunner.util.MathUtil INSTANCE;\n\n private com.acmerobotics.r...
binkley__kotlin-dice__072d4cb/src/main/kotlin/hm/binkley/dice/rolling/KeepCount.kt
package hm.binkley.dice.rolling import java.util.Objects.hash sealed class KeepCount(protected val value: Int) { override fun toString() = "${this::class.simpleName}($value)" override fun equals(other: Any?) = this === other || other is KeepCount && javaClass == other.javaClass && value == other.value override fun hashCode() = hash(javaClass, value) /** Splits sorted list of results into those to keep and those to drop. */ protected abstract fun partition(other: List<Int>): Pair<List<Int>, List<Int>> companion object { fun List<Int>.keep(count: KeepCount) = count.partition(this) } } /** * Keeps the highest dice rolls. */ class KeepHigh(value: Int) : KeepCount(value) { override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { val (kept, dropped) = other.withIndex().partition { (index, _) -> other.size - value <= index } return kept.withoutIndex() to dropped.withoutIndex() } } /** * Keeps the lower middle dice rolls. * When there are even/odd numbers of dice, and even/odd numbers to keep: * - Even / even -- middle low and high are the same * - Even /odd -- picks up an extra low roll * - Odd / even -- picks up an extra low roll * - Odd / odd -- middle low and high are the same */ class KeepMiddleLow(value: Int) : KeepMiddle(value) { override fun splitKeep(listEven: Boolean, keepEven: Boolean) = if (listEven && keepEven) value / 2 else value / 2 + 1 } /** * Keeps the upper middle dice rolls. * When there are even/odd numbers of dice, and even/odd numbers to keep: * - Even / even -- middle low and high are the same * - Even /odd -- picks up an extra high roll * - Odd / even -- picks up an extra high roll * - Odd / odd -- middle low and high are the same */ class KeepMiddleHigh(value: Int) : KeepMiddle(value) { override fun splitKeep(listEven: Boolean, keepEven: Boolean) = if (!listEven && !keepEven) value / 2 + 1 else value / 2 } abstract class KeepMiddle( value: Int, ) : KeepCount(value) { protected abstract fun splitKeep( listEven: Boolean, keepEven: Boolean, ): Int override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { if (0 == value || other.isEmpty()) return emptyList<Int>() to other val listEven = 0 == other.size % 2 val keepEven = 0 == value % 2 val lowerSize = if (listEven) other.size / 2 else other.size / 2 + 1 val lowerKeep = splitKeep(listEven, keepEven) val upperKeep = value - lowerKeep val (lower, upper) = other.keep(KeepLow(lowerSize)) val (lowerKept, lowerDropped) = lower.keep(KeepHigh(lowerKeep)) val (upperKept, upperDropped) = upper.keep(KeepLow(upperKeep)) return (lowerKept + upperKept) to (lowerDropped + upperDropped) } } /** * Keeps the lowest dice rolls. */ class KeepLow(value: Int) : KeepCount(value) { override fun partition(other: List<Int>): Pair<List<Int>, List<Int>> { val (kept, dropped) = other.withIndex().partition { (index, _) -> value > index } return kept.withoutIndex() to dropped.withoutIndex() } } private fun <T> List<IndexedValue<T>>.withoutIndex() = map { (_, it) -> it }
[ { "class_path": "binkley__kotlin-dice__072d4cb/hm/binkley/dice/rolling/KeepCountKt.class", "javap": "Compiled from \"KeepCount.kt\"\npublic final class hm.binkley.dice.rolling.KeepCountKt {\n private static final <T> java.util.List<T> withoutIndex(java.util.List<? extends kotlin.collections.IndexedValue<? ...
ansonxing23__mt-metrics__2f5a970/src/main/kotlin/com/newtranx/eval/utils/func.kt
package com.newtranx.eval.utils import kotlin.math.ln import kotlin.math.min /** * @Author: anson * @Date: 2022/1/29 11:41 PM */ inline fun <T> zip(vararg lists: List<T>): List<List<T>> { return zip(*lists, transform = { it }) } inline fun <T, V> zip(vararg lists: List<T>, transform: (List<T>) -> V): List<V> { val minSize = lists.map(List<T>::size).minOrNull() ?: return emptyList() val list = ArrayList<V>(minSize) val iterators = lists.map { it.iterator() } var i = 0 while (i < minSize) { list.add(transform(iterators.map { it.next() })) i++ } return list } /** * Extracts all ngrams (min_order <= n <= max_order) from a sentence. * @param line: A string sentence. * @param minOrder: Minimum n-gram order. * @param maxOrder: Maximum n-gram order. * @return a Counter object with n-grams counts and the sequence length. */ fun extractAllWordNgrams( line: String, minOrder: Int, maxOrder: Int ): Pair<Counter<List<String>>, Double> { val counter = Counter<List<String>>() val tokens = line.split(" ") (minOrder until maxOrder + 1).forEach { n -> val nGrams = extractNgrams(tokens, n) counter.update(nGrams) } return Pair(counter, tokens.size.toDouble()) } fun extractNgrams( tokens: List<String>, n: Int = 1 ): List<List<String>> { return (0 until (tokens.size - n + 1)).map { i -> tokens.subList(i, i + n) } } class Counter<T>( data: List<T>? = null ) { private val store = mutableMapOf<T, Int>() private val keys = mutableSetOf<T>() init { if (data != null) this.update(data) } fun update(data: List<T>) { data.forEach { key -> val count = store[key] ?: 0 if (count == 0) { keys.add(key) } store[key] = count + 1 } } private fun add(key: T, count: Int) { store[key] = count keys.add(key) } fun keys(): Set<T> { return keys } fun values(): List<Int> { return store.values.toList() } fun count(key: T): Int { return store[key] ?: 0 } fun exist(key: T): Boolean { return store.containsKey(key) } fun intersect(counter: Counter<T>): Counter<T> { val iKeys = this.keys intersect counter.keys val newCounter = Counter<T>() iKeys.forEach { val cur = count(it) val income = counter.count(it) val value = min(cur, income) newCounter.add(it, value) } return newCounter } operator fun set(key: T, count: Int) { if (!store.containsKey(key)) { keys.add(key) } store[key] = 0.takeIf { count < 0 } ?: count } } inline fun <T, V> Counter<T>.map(transform: (key: T, count: Int) -> V): List<V> { val array = mutableListOf<V>() this.keys().forEach { val item = transform.invoke(it, this.count(it)) array.add(item) } return array } inline fun <T> Counter<T>.forEach(action: (key: T, count: Int) -> Unit) { this.keys().forEach { action.invoke(it, this.count(it)) } } /** * Floors the log function * @param num: the number * @return log(num) floored to a very low number */ fun myLog(num: Double): Double { if (num == 0.0) return -9999999999.0 return ln(num) } /** * Aggregates list of numeric lists by summing. */ fun sumOfLists(lists: List<List<Double>>): List<Double> { // Aggregates list of numeric lists by summing. if (lists.size == 1) { return lists[0] } // Preserve datatype val size = lists[0].size val total = DoubleArray(size) { 0.0 } lists.forEach { ll -> (0 until size).forEach { i -> total[i] = total[i].plus(ll[i]) } } return total.toList() }
[ { "class_path": "ansonxing23__mt-metrics__2f5a970/com/newtranx/eval/utils/FuncKt.class", "javap": "Compiled from \"func.kt\"\npublic final class com.newtranx.eval.utils.FuncKt {\n public static final <T> java.util.List<java.util.List<T>> zip(java.util.List<? extends T>...);\n Code:\n 0: aload_0\n ...
vengateshm__Android-Kotlin-Jetpack-Compose-Practice__40d2c85/kotlin_practice/src/main/java/dev/vengateshm/kotlin_practice/programs/AnagramSubStringSearchHashMapImpl.kt
package dev.vengateshm.kotlin_practice.programs fun main() { // println(findAnagramsPatternsStartIndicesInString("", "abc").toString()) // println(findAnagramsPatternsStartIndicesInString("abc", "abca").toString()) println(findAnagramsPatternsStartIndicesInString("abczzbcabcadeb", "abc").toString()) // println(findAnagramsPatternsStartIndicesInString("abacab", "ab").toString()) } fun findAnagramsPatternsStartIndicesInString(str: String, pattern: String): List<Int>? { // Handle corner cases if (isInvalid(str, pattern)) { println("Invalid string or pattern") return null } if (pattern.length > str.length) { println("Pattern is larger than string") return null } val windowSize = pattern.length val strLength = str.length val patternCharCountMap = mutableMapOf<Char, Int>() val stringCharCountMap = mutableMapOf<Char, Int>() val indices = mutableListOf<Int>() // Generate count map for first window in str and pattern for (i in 0 until windowSize) { generateWindowCharCountMap(pattern[i], patternCharCountMap) generateWindowCharCountMap(str[i], stringCharCountMap) } // Start at the end of the first window for (windowRightBound in windowSize until strLength) { if (compareMap(patternCharCountMap, stringCharCountMap)) { indices.add(windowRightBound - windowSize) } // Remove first character in the window val oldCharIndex = windowRightBound - windowSize val oldChar = str[oldCharIndex] var oldCharCount = stringCharCountMap[oldChar]!! if (oldCharCount == 1) { stringCharCountMap.remove(oldChar) } else { oldCharCount-- stringCharCountMap[oldChar] = oldCharCount } // Add the new char to the window generateWindowCharCountMap(str[windowRightBound], stringCharCountMap) } // At this point last window comparison remains // so compare one last time if (compareMap(patternCharCountMap, stringCharCountMap)) { indices.add(strLength - windowSize) } return indices } fun generateWindowCharCountMap(char: Char, map: MutableMap<Char, Int>) { var count = map[char] if (count == null) { count = 0; } count++ map[char] = count } fun isInvalid(str: String?, pattern: String?): Boolean { return str.isNullOrEmpty() || pattern.isNullOrEmpty() } fun compareMap(patternMap: Map<Char, Int>, strMap: Map<Char, Int>): Boolean { for (entry in patternMap) { val char = entry.key val count = entry.value if (strMap[char] == null || strMap[char] != count) { return false } } return true }
[ { "class_path": "vengateshm__Android-Kotlin-Jetpack-Compose-Practice__40d2c85/dev/vengateshm/kotlin_practice/programs/AnagramSubStringSearchHashMapImplKt.class", "javap": "Compiled from \"AnagramSubStringSearchHashMapImpl.kt\"\npublic final class dev.vengateshm.kotlin_practice.programs.AnagramSubStringSearc...
bsautner__Advent-of-Code-2022__5f53cb1/AOC2022/src/main/kotlin/AOC9.kt
package com.yp.day9 import java.io.File import kotlin.math.abs class AOC9 { fun process() { val input = File("/home/ben/aoc/input-9.txt") val instructions = input.useLines { it.toList() } val p1 = (0..1).map { Pair(0, 0) }.toMutableList() val p2 = (0..9).map { Pair(0, 0) }.toMutableList() println("Part1: ${scan(p1, instructions)}") println("Part2: ${scan(p2, instructions)}") } private fun scan(rope: MutableList<Pair<Int, Int>>, input: List<String>): Int { val visitedPositions = mutableSetOf<Pair<Int, Int>>() visitedPositions.add(rope.last()) input.forEach { instruction -> val cmd = instruction.split(" ") (1..cmd[1].toInt()).forEach { _ -> rope[0] = processStep(cmd[0], rope[0]) (0 until rope.size - 1).forEachIndexed { index, _ -> val newPositions = tail(rope[index], rope[index + 1]) rope[index + 1] = newPositions } visitedPositions.add(rope.last()) } } return visitedPositions.size } private fun tail( headPosition: Pair<Int, Int>, tailPosition: Pair<Int, Int> ): Pair<Int, Int> { return when { abs((headPosition.first - tailPosition.first)) > 1 || abs((headPosition.second - tailPosition.second)) > 1 -> { when { headPosition.first == tailPosition.first -> { Pair( tailPosition.first, if (headPosition.second > tailPosition.second) tailPosition.second + 1 else tailPosition.second - 1 ) } headPosition.second == tailPosition.second -> { Pair( if (headPosition.first > tailPosition.first) tailPosition.first + 1 else tailPosition.first - 1, tailPosition.second ) } else -> { val xDiff = (headPosition.first - tailPosition.first) val yDiff = (headPosition.second - tailPosition.second) val changeX = abs(xDiff) > 1 || (abs(xDiff) > 0 && abs(yDiff) > 1) val changeY = abs(yDiff) > 1 || (abs(yDiff) > 0 && abs(xDiff) > 1) Pair( if (changeX) tailPosition.first + (if (xDiff < 0) -1 else 1) else tailPosition.first, if (changeY) tailPosition.second + (if (yDiff < 0) -1 else 1) else tailPosition.second, ) } } } else -> tailPosition } } private fun processStep(step: String, headPosition: Pair<Int, Int>): Pair<Int, Int> { val (x, y) = headPosition return when (step) { "U" -> headPosition.copy(second = y - 1) "D" -> headPosition.copy(second = y + 1) "L" -> headPosition.copy(first = x - 1) "R" -> headPosition.copy(first = x + 1) else -> { throw IllegalStateException() } } } }
[ { "class_path": "bsautner__Advent-of-Code-2022__5f53cb1/com/yp/day9/AOC9.class", "javap": "Compiled from \"AOC9.kt\"\npublic final class com.yp.day9.AOC9 {\n public com.yp.day9.AOC9();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n ...
Chopinsky__-Exercises--Kotlin_with_Java__2274ef8/src/com/company/AStar.kt
package com.company import java.util.* import kotlin.collections.ArrayList val D1 = 1.0 val D2 = Math.sqrt(2.0) val p = 1/1000 fun aStarSearch(start: Pair<Int, Int>, goal: Pair<Int, Int>, map: HashMap<Pair<Int, Int>, Int>): ArrayList<Pair<Int, Int>> { val failure = ArrayList<Pair<Int, Int>>() // set of node already evaluated val closedSet = HashSet<Pair<Int, Int>>() // set of currently discovered nodes var openSet = ArrayList<Pair<Int, Int>>() openSet.add(start) val cameFrom = HashMap<Pair<Int, Int>, Pair<Int, Int>>() val gScore = HashMap<Pair<Int, Int>, Double>() val fScore = HashMap<Pair<Int, Int>, Double>() for (pos: Pair<Int, Int> in map.keys) { if (pos.first == start.first && pos.second == start.second) continue gScore[pos] = Double.NEGATIVE_INFINITY fScore[pos] = Double.NEGATIVE_INFINITY } gScore[start] = 0.0 fScore[start] = -1 * heuristicCostEstimate(start, start, goal) var current: Pair<Int, Int> var result: Pair<Pair<Int, Int>, ArrayList<Pair<Int, Int>>> var neighbors: ArrayList<Pair<Int, Int>> var tempGScore: Double while (!openSet.isEmpty()) { result = getNextNode(openSet, fScore) current = result.first openSet = result.second if (current.first == goal.first && current.second == goal.second) { return reconstructPath(cameFrom, current) } openSet = removeNode(openSet, current, fScore) closedSet.add(current) neighbors = getNeighbors(current, map) for (neighbor: Pair<Int, Int> in neighbors) { // Ignore the neighbor which is already evaluated. if (closedSet.contains(neighbor)) continue // Discover a new node if (!openSet.contains(neighbor)) openSet = insertNode(openSet, neighbor, fScore) // The distance from start to a neighbor tempGScore = gScore[current]!! + Math.sqrt(0.0 + (current.first - neighbor.first) * (current.first - neighbor.first) + (current.second - neighbor.second) * (current.second - neighbor.second)) if (tempGScore >= gScore[neighbor]!!) continue // This path is the best until now. Record it! cameFrom[neighbor] = current gScore[neighbor] = tempGScore fScore[neighbor] = -1 * (gScore[neighbor]!! + heuristicCostEstimate(neighbor, start, goal)) } } return failure } fun heuristicCostEstimate(pos: Pair<Int, Int>, start: Pair<Int, Int>, goal: Pair<Int, Int>, option: Int = 0): Double { val dx = (goal.first - pos.first).toDouble() val dy = Math.abs(goal.second - pos.second).toDouble() val result = when(option) { 1 -> D1 * (dx + dy) 2 -> D1 * Math.max(dx, dy) + (D2 - 1) * Math.min(dx, dy) 3 -> D1 * Math.sqrt((dx * dx) + (dy * dy)) // euclidean distance else -> D1 * (dx + dy) + (D2 - 2 * D1) * Math.min(dx, dy) // octile distance } // Method 1 to break tie: return result * (1.0 + p) // Method 2 to break tie: //val cross = Math.abs(dx * (start.first - goal.first) - dy * (start.second - goal.second)) //return result + cross * p } fun findNextNode(openSet: HashSet<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): Pair<Int, Int> { if (openSet.isEmpty()) { return Pair(0, 0) } if (openSet.size == 1) { return openSet.elementAt(0) } var lowScore = Double.MAX_VALUE var nextNode = openSet.elementAt(0) for (node: Pair<Int, Int> in openSet) { if (fScore[node]!! < lowScore) { lowScore = fScore[node]!! nextNode = node } } return nextNode } fun insertNode(openSet: ArrayList<Pair<Int, Int>>, node: Pair<Int, Int>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { openSet.add(node) var child = openSet.size - 1 var parent = (child - 1) / 2 var temp: Pair<Int, Int> while (child != 0 && fScore[openSet[child]]!! > fScore[openSet[parent]]!!) { temp = openSet[child] openSet[child] = openSet[parent] openSet[parent] = temp child = parent parent = (parent - 1) / 2 } return openSet } fun removeNode(openSet: ArrayList<Pair<Int, Int>>, node: Pair<Int, Int>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { openSet.remove(node) return buildMaxHeap(openSet, fScore) } fun getNextNode(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): Pair<Pair<Int, Int>, ArrayList<Pair<Int, Int>>> { val nextNode = Pair(openSet[0].first, openSet[0].second) val newSet: ArrayList<Pair<Int, Int>> if (openSet.size == 1) { newSet = openSet } else { // replacing the first node with the last node. openSet[0] = openSet.removeAt(openSet.size-1) // heapify the remaining array-list newSet = buildMaxHeap(openSet, fScore) } return Pair(nextNode, newSet) } fun buildMaxHeap(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>): ArrayList<Pair<Int, Int>> { var middle = openSet.size / 2 - 1 var heapSet = openSet while (middle >= 0) { heapSet = heapifyArray(heapSet, fScore, middle, openSet.size - 1) middle -= 1 } return heapSet } fun heapifyArray(openSet: ArrayList<Pair<Int, Int>>, fScore: HashMap<Pair<Int, Int>, Double>, root: Int, last: Int): ArrayList<Pair<Int, Int>> { val left = 2 * root + 1 val right = left + 1 var largest = root val temp: Pair<Int, Int> if (left <= last && fScore[openSet[left]]!! > fScore[openSet[largest]]!!) largest = left if (right <= last && fScore[openSet[right]]!! > fScore[openSet[largest]]!!) largest = right return when (largest != root) { true -> { temp = openSet[largest] openSet[largest] = openSet[root] openSet[root] = temp heapifyArray(openSet, fScore, largest, last) //return value } else -> { openSet //return value } } } fun reconstructPath(cameFrom: HashMap<Pair<Int, Int>, Pair<Int, Int>>, current: Pair<Int, Int>): ArrayList<Pair<Int, Int>> { val path = ArrayList<Pair<Int, Int>>() path.add(current) var pos = current while (cameFrom.containsKey(pos)) { pos = cameFrom[pos]!! path.add(pos) } return path } fun getNeighbors(current: Pair<Int, Int>, map: HashMap<Pair<Int, Int>, Int>): ArrayList<Pair<Int, Int>> { var neighbor: Pair<Int, Int> val neighbors: ArrayList<Pair<Int, Int>> = ArrayList() for (i in -1..1) { for (j in -1..1) { if (i == 0 && j == 0) continue neighbor = Pair(current.first + i, current.second + j) if (map.containsKey(neighbor) && map[neighbor] == 1) { neighbors.add(neighbor) } } } return neighbors }
[ { "class_path": "Chopinsky__-Exercises--Kotlin_with_Java__2274ef8/com/company/AStarKt.class", "javap": "Compiled from \"AStar.kt\"\npublic final class com.company.AStarKt {\n private static final double D1;\n\n private static final double D2;\n\n private static final int p;\n\n public static final doubl...
Lysoun__advent-of-code-2023__96ecbce/day3/src/main/kotlin/part2.kt
package day3 import java.io.File fun computeGearRatio(maybeGearPosition: Pair<Int, Int>, numbers: MutableMap<Pair<Int, Int>, Int>): Int { val neighbourNumbers = listOf( maybeGearPosition.first to maybeGearPosition.second -1, maybeGearPosition.first + 1 to maybeGearPosition.second -1, maybeGearPosition.first - 1 to maybeGearPosition.second -1, maybeGearPosition.first to maybeGearPosition.second +1, maybeGearPosition.first + 1 to maybeGearPosition.second +1, maybeGearPosition.first - 1 to maybeGearPosition.second +1, maybeGearPosition.first + 1 to maybeGearPosition.second, maybeGearPosition.first - 1 to maybeGearPosition.second ).mapNotNull { numbers[it] }.toSet() return if (neighbourNumbers.size == 2) { neighbourNumbers.reduce(Int::times) } else { 0 } } fun main() { val inputFileName = "day3/input.txt" val numbers: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() val hopefullyGears: MutableList<Pair<Int, Int>> = mutableListOf() var lineNumber = 0 File(inputFileName).forEachLine { var number = "" var digitsIndices = mutableListOf<Pair<Int, Int>>() it.forEachIndexed { index, c -> if (c.isDigit()) { number += c.toString() digitsIndices.add(lineNumber to index) } else if(number != "") { digitsIndices.forEach {digitIndex -> numbers[digitIndex] = number.toInt() } number = "" digitsIndices = mutableListOf() } if (c == '*') { hopefullyGears.add(lineNumber to index) } } if(number != "") { digitsIndices.forEach {digitIndex -> numbers[digitIndex] = number.toInt() } number = "" digitsIndices = mutableListOf() } ++lineNumber } println(hopefullyGears.sumOf { computeGearRatio(it, numbers) }) }
[ { "class_path": "Lysoun__advent-of-code-2023__96ecbce/day3/Part2Kt.class", "javap": "Compiled from \"part2.kt\"\npublic final class day3.Part2Kt {\n public static final int computeGearRatio(kotlin.Pair<java.lang.Integer, java.lang.Integer>, java.util.Map<kotlin.Pair<java.lang.Integer, java.lang.Integer>, j...
Lysoun__advent-of-code-2023__96ecbce/day3/src/main/kotlin/part1.kt
package day3 import java.io.File fun isSymbol(char: Char): Boolean = !char.isDigit() && char != '.' fun isNextToASymbol(position: Pair<Int, Int>, engineSchematic: Map<Pair<Int, Int>, Char>): Boolean { val neighbourPositions = listOf( position.first to position.second -1, position.first + 1 to position.second -1, position.first - 1 to position.second -1, position.first to position.second +1, position.first + 1 to position.second +1, position.first - 1 to position.second +1, position.first + 1 to position.second, position.first - 1 to position.second ) return neighbourPositions.mapNotNull { engineSchematic[it] }.any { isSymbol(it) } } fun main() { val inputFileName = "day3/input.txt" val engineSchematic: MutableMap<Pair<Int, Int>, Char> = mutableMapOf() val numbers: MutableList<Pair<Int, List<Pair<Int, Int>>>> = mutableListOf() var lineNumber = 0 File(inputFileName).forEachLine { var number = "" var digitsIndices = mutableListOf<Pair<Int, Int>>() it.forEachIndexed { index, c -> engineSchematic[lineNumber to index] = c if (c.isDigit()) { number += c.toString() digitsIndices.add(lineNumber to index) } else if(number != "") { numbers.add( number.toInt() to digitsIndices ) number = "" digitsIndices = mutableListOf() } } if(number != "") { numbers.add( number.toInt() to digitsIndices ) number = "" digitsIndices = mutableListOf() } ++lineNumber } println(numbers.filter { val nextToASymbol = it.second.any { digitsIndices -> isNextToASymbol(digitsIndices, engineSchematic) } println("number: ${it.first} indices: ${it.second} nextToASymbol: $nextToASymbol") nextToASymbol }.sumOf { it.first }) }
[ { "class_path": "Lysoun__advent-of-code-2023__96ecbce/day3/Part1Kt.class", "javap": "Compiled from \"part1.kt\"\npublic final class day3.Part1Kt {\n public static final boolean isSymbol(char);\n Code:\n 0: iload_0\n 1: invokestatic #11 // Method java/lang/Character.isDigit:(...
nickperov__Algorithms__6696f5d/combinatorics/src/main/kotlin/com/nickperov/stud/combinatorics/CombinatorialUtils.kt
package com.nickperov.stud.combinatorics import java.math.BigInteger object CombinatorialUtils { /** * Number of ordered samples of size m, without replacement, from n objects. */ fun calculateNumberOfVariationsInt(n: Int, m: Int): Int { val number = calculateNumberOfVariations(n, m) if (number > BigInteger.valueOf(Int.MAX_VALUE.toLong())) { throw IllegalArgumentException("Value is too big") } else { return number.toInt() } } /** * Number of ordered samples of size m, without replacement, from n objects. */ fun calculateNumberOfVariationsLong(n: Int, m: Int): Long { val number = calculateNumberOfVariations(n, m) if (number > BigInteger.valueOf(Long.MAX_VALUE)) { throw IllegalArgumentException("Value is too big") } else { return number.toLong() } } private fun calculateNumberOfVariations(n: Int, m: Int): BigInteger { val numerator = factorial(n) val denominator = factorial(n - m) return numerator.divide(denominator) } fun calculateNumberOfPermutationsInt(n: Int): Int { val f = factorial(n) if (f > BigInteger.valueOf(Int.MAX_VALUE.toLong())) { throw IllegalArgumentException("Value is too big") } else { return f.toInt() } } fun calculateNumberOfPermutationsLong(n: Int): Long { val f = factorial(n) if (f > BigInteger.valueOf(Long.MAX_VALUE)) { throw IllegalArgumentException("Value is too big") } else { return f.toLong() } } private fun factorial(n: Int): BigInteger { var result = BigInteger.ONE for (i in 1..n) { result = result.multiply(BigInteger.valueOf(i.toLong())) } return result } /** * Provides all permutations of the elements in the given array. * recursive implementation, uses list invariant * returns array of arrays */ fun <T> getAllPermutations(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = MutableList(0) { listOf<T>() } val used = BooleanArray(elements.size) collectAllPermutations(result, used, elements, arrayListOf()) return result.toTypedArray() } private fun <T> collectAllPermutations(result: MutableList<List<T>>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>) { if (selection.size == elements.size) { result.add(selection.toList()) } else { for (i in used.indices) { if (!used[i]) { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) collectAllPermutations(result, usedCopy, elements, selectionCopy) } } } } data class CombinationsInvariant<T>(val value: Array<List<T>>, var index: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as CombinationsInvariant<*> if (!value.contentEquals(other.value)) return false if (index != other.index) return false return true } override fun hashCode(): Int { var result = value.contentHashCode() result = 31 * result + index return result } } }
[ { "class_path": "nickperov__Algorithms__6696f5d/com/nickperov/stud/combinatorics/CombinatorialUtils$CombinationsInvariant.class", "javap": "Compiled from \"CombinatorialUtils.kt\"\npublic final class com.nickperov.stud.combinatorics.CombinatorialUtils$CombinationsInvariant<T> {\n private final java.util.Li...
nickperov__Algorithms__6696f5d/knapsack/src/main/kotlin/com/nickperov/stud/algorithms/knapsack/KnapSackProblem.kt
package com.nickperov.stud.algorithms.knapsack import kotlin.random.Random data class KnapSack(val weightLimit: Int) data class Item(val weight: Int, val price: Int) data class ProblemParameters(val knapSackSize: Int, val itemListSize: Int, val itemWeightLimit: Int, val itemPriceLimit: Int) data class Problem(val knapSack: KnapSack, val items: List<Item>) // Default values const val knapsackDefaultSize = 100 const val itemListDefaultSize = 50 const val itemWeightDefaultLimit = 10 const val itemPriceDefaultLimit = 20 fun main(args: Array<String>) { val problem = initProblemFromArgs(args) printItems(problem.items) } private fun initProblemFromArgs(args: Array<String>): Problem { println("Init from command line arguments") val (knapsackSize, itemListSize, itemWeightLimit, itemPriceLimit) = initParameters(args) println("Knapsack size: $knapsackSize; product list size: $itemListSize; product limits: (weight: $itemWeightLimit, price: $itemPriceLimit)") val knapSack = KnapSack(knapsackSize) val items = initItems(itemListSize, itemWeightLimit, itemPriceLimit) return Problem(knapSack, items) } private fun initParameters(args: Array<String>): ProblemParameters { return if (args.isNotEmpty()) { if (args.size != 4) throw RuntimeException("Wrong number of arguments") ProblemParameters(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt()) } else { println("Command line arguments are empty, use default values") ProblemParameters(knapsackDefaultSize, itemListDefaultSize, itemWeightDefaultLimit, itemPriceDefaultLimit) } } private fun printItems(items: List<Item>) { val itemPrintFormat = "%5s %10s %10s" println("Items list") println("----------------------------------------------") print("|") println(itemPrintFormat.format("Number", "Weight", "Price")) println("----------------------------------------------") items.forEachIndexed { index, item -> print("|"); println(itemPrintFormat.format(index, item.weight, item.price)) } } private fun initItems(number: Int, weightLimit: Int, priceLimit: Int): List<Item> { return generateSequence(0) { i -> i + 1 }.take(number).map { initItem(weightLimit, priceLimit) }.toList() } private fun initItem(weightLimit: Int, priceLimit: Int) = Item(Random.nextInt(weightLimit) + 1, Random.nextInt(priceLimit) + 1)
[ { "class_path": "nickperov__Algorithms__6696f5d/com/nickperov/stud/algorithms/knapsack/KnapSackProblemKt.class", "javap": "Compiled from \"KnapSackProblem.kt\"\npublic final class com.nickperov.stud.algorithms.knapsack.KnapSackProblemKt {\n public static final int knapsackDefaultSize;\n\n public static fi...
nickperov__Algorithms__6696f5d/monty-hall/src/main/kotlin/com/nickperov/stud/algorithms/montyhall/MontyHallSimulator.kt
package com.nickperov.stud.algorithms.montyhall import kotlin.random.Random enum class Prize { GOAT, CAR } enum class Strategy { KEEP, CHANGE, GUESS } object MontyHallApp { @JvmStatic fun main(args: Array<String>) { println("Simulate monty hall game with different strategies") val rounds = generateRounds(1_000_000) /*println(rounds.contentDeepToString())*/ Strategy.values().forEach { strategy -> val percentageWins = play(rounds, strategy) println("Strategy %{strategy.name} wins:$percentageWins%") } } } private fun play(rounds: Array<Array<Prize>>, strategy: Strategy): Double { val result = rounds.map { play(it, strategy) }.toTypedArray() val totalWins = result.filter { it }.count() return (totalWins / (rounds.size / 100).toDouble()).toDouble() } private fun play(round: Array<Prize>, strategy: Strategy): Boolean { val firstTry = Random.nextInt(3) val openedDoor = openDoor(round, firstTry) val secondTry = makeSecondTry(firstTry, openedDoor, strategy) return round[secondTry] == Prize.CAR } private fun makeSecondTry(firstTry: Int, openedDoor: Int, strategy: Strategy): Int { return when (strategy) { Strategy.KEEP -> firstTry Strategy.CHANGE -> nextDoor(firstTry, openedDoor) Strategy.GUESS -> if (Random.nextBoolean()) nextDoor(firstTry, openedDoor) else firstTry } } private fun nextDoor(currentDoor: Int, openedDoor: Int): Int { for (i in 0..2) { if (i != currentDoor && i != openedDoor) { return i; } } throw RuntimeException("Fatal error") } private fun openDoor(round: Array<Prize>, firstTry: Int): Int { round.forEachIndexed { index, prize -> if (index != firstTry && prize == Prize.GOAT) { return index } } throw RuntimeException("Fatal error") } private fun generateRounds(size: Int): Array<Array<Prize>> { return Array(size) { generateRound() } } private fun generateRound(): Array<Prize> { return when (Random.nextInt(3)) { 0 -> { arrayOf(Prize.CAR, Prize.GOAT, Prize.GOAT) } 1 -> { arrayOf(Prize.GOAT, Prize.CAR, Prize.GOAT) } else -> { arrayOf(Prize.GOAT, Prize.GOAT, Prize.CAR) } } }
[ { "class_path": "nickperov__Algorithms__6696f5d/com/nickperov/stud/algorithms/montyhall/MontyHallSimulatorKt$WhenMappings.class", "javap": "Compiled from \"MontyHallSimulator.kt\"\npublic final class com.nickperov.stud.algorithms.montyhall.MontyHallSimulatorKt$WhenMappings {\n public static final int[] $En...
nickperov__Algorithms__6696f5d/fibonacci/src/main/kotlin/com/nickperov/stud/algorithms/fibonacci/FibonacciLargeGenerator.kt
package com.nickperov.stud.algorithms.fibonacci import java.math.BigInteger fun main() { println("Hello, large Fibonacci numbers") println(FibonacciLargeTailRecursiveOptimisedGenerator().calculate(1000000)) /*for (number in 93..150) { println("====================>$number<==================") println(FibonacciLargeTailRecursiveOptimisedGenerator().calculate(number)) println(FibonacciLargeIterativeGenerator02().calculate(number)) println(FibonacciLargeMatrixGenerator().calculate(number)) }*/ } /** * Generator to calculate fibonacci number greater than 7540113804746346429 (92nd number) */ abstract class FibonacciLargeGenerator { abstract fun calculate(number: Int): BigInteger } class FibonacciLargeTailRecursiveOptimisedGenerator : FibonacciLargeGenerator() { override fun calculate(number: Int): BigInteger { return if (number == 0) BigInteger.ZERO else if (number == 1 || number == 2) BigInteger.ONE else calculate(BigInteger.ONE, BigInteger.ONE, 3, number) } private tailrec fun calculate(antePenultimate: BigInteger, penultimate: BigInteger, current: Int, target: Int): BigInteger { return if (current == target) antePenultimate.add(penultimate) else calculate(penultimate, antePenultimate.add(penultimate), current + 1, target) } } class FibonacciLargeIterativeGenerator02 : FibonacciLargeGenerator() { override fun calculate(number: Int): BigInteger { val numberPair = arrayOf(BigInteger.ZERO, BigInteger.ZERO) for (i in 0..number) { calculate(i, numberPair) } return numberPair[1] } private fun calculate(number: Int, prev: Array<BigInteger>) { when (number) { 0 -> { prev[1] = BigInteger.ZERO } 1 -> { prev[1] = BigInteger.ONE } 2 -> { prev[0] = BigInteger.ONE } else -> { val next = prev[0].add(prev[1]) prev[0] = prev[1] prev[1] = next } } } } class FibonacciLargeMatrixGenerator : FibonacciLargeGenerator() { /** * Matrix: | 0 1 | | 1 1 | */ private val matrix = arrayOf(arrayOf(BigInteger.ZERO, BigInteger.ONE), arrayOf(BigInteger.ONE, BigInteger.ONE)) override fun calculate(number: Int): BigInteger { if (number == 0 || number == 1) { return BigInteger.valueOf(number.toLong()) } else if (number == 2) { return BigInteger.ONE } else { var currMatrix = matrix val power = number - 1 currMatrix = powerOf(currMatrix, power) return currMatrix[1][1] } } private fun powerOf(m: Array<Array<BigInteger>>, n: Int): Array<Array<BigInteger>> { return when { n == 1 -> { m } n % 2 == 0 -> { val mP = powerOf(m, n / 2) multiply(mP, mP) } else -> { val mP = powerOf(m, n - 1) multiply(mP, m) } } } private fun multiply(m1: Array<Array<BigInteger>>, m2: Array<Array<BigInteger>>): Array<Array<BigInteger>> { val l = m1.size val n = m2.size val result = Array(l) { Array(n) { BigInteger.ZERO } } for (i in 0 until l) { for (k in 0 until n) { var sum = BigInteger.ZERO for (j in 0 until m1[i].size) { sum = sum.add(m1[i][j].multiply(m2[k][j])) } result[i][k] = sum } } return result } }
[ { "class_path": "nickperov__Algorithms__6696f5d/com/nickperov/stud/algorithms/fibonacci/FibonacciLargeGeneratorKt.class", "javap": "Compiled from \"FibonacciLargeGenerator.kt\"\npublic final class com.nickperov.stud.algorithms.fibonacci.FibonacciLargeGeneratorKt {\n public static final void main();\n Co...
nickperov__Algorithms__6696f5d/combinatorics/src/main/kotlin/com/nickperov/stud/combinatorics/experiment/PermutationsCalculatorExperiment.kt
package com.nickperov.stud.combinatorics.experiment import com.nickperov.stud.combinatorics.CombinatorialUtils import java.util.* /** * Test sample to try different approaches to calculate permutations */ object PermutationsCalculatorExperiment { /** * Provides all permutations of the elements in the given array. * recursive implementation, uses array invariant of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV1(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val used = BooleanArray(elements.size) collectAllPermutations(result, used, elements, arrayListOf()) return result.value } private fun <T> collectAllPermutations(result: CombinatorialUtils.CombinationsInvariant<T>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>) { if (selection.size == elements.size) { result.value[result.index] = selection.toList() result.index += 1 } else { for (i in used.indices) { if (!used[i]) { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) collectAllPermutations(result, usedCopy, elements, selectionCopy) } } } } /** * Provides all permutations of the elements in the given array. * recursive implementation, uses list invariant * returns array of arrays * * Default one - look into utils class */ @JvmStatic fun <T> getAllPermutationsV2(elements: Array<T>): Array<List<T>> { return CombinatorialUtils.getAllPermutations(elements) } /** * Provides all permutations of the elements in the given array. * recursive implementation, optimized (reduced number of array copy operations), uses array invariant of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV3(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val used = BooleanArray(elements.size) collectAllPermutations(result, used, elements, arrayListOf(), used.size) return result.value } private fun <T> collectAllPermutations(result: CombinatorialUtils.CombinationsInvariant<T>, used: BooleanArray, elements: Array<T>, selection: MutableList<T>, count: Int) { if (selection.size == elements.size) { result.value[result.index] = selection.toList() result.index += 1 } else { var k = 1 for (i in used.indices) { if (!used[i]) { if (k++ == count) { // Do not copy arrays used[i] = true selection.add(elements[i]) collectAllPermutations(result, used, elements, selection, count - 1) } else { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) collectAllPermutations(result, usedCopy, elements, selectionCopy, count - 1) } } } } } /** * Provides all permutations of the elements in the given array. * non-recursive implementation, optimized (reduced number of array copy operations), uses array of pre-calculated size * returns array of arrays */ @JvmStatic fun <T> getAllPermutationsV4(elements: Array<T>): Array<List<T>> { if (elements.isEmpty()) { return arrayOf() } val result = CombinatorialUtils.CombinationsInvariant(Array(CombinatorialUtils.calculateNumberOfPermutationsInt(elements.size)) { listOf<T>() }, 0) val stack: Deque<RecursiveState<T>> = ArrayDeque(elements.size) var state: RecursiveState<T>? = RecursiveState(BooleanArray(elements.size), arrayListOf(), elements.size, 0, 1) stack.push(state) MAIN_LOOP@ while (true) { if (state == null) { break } else { val used = state.used val selection = state.selection val count = state.count var k = state.currCount var i = state.index while (i < elements.size) { if (!used[i]) { if (k++ == count) { // Do not copy arrays used[i] = true selection.add(elements[i]) // Update state index state?.index = i + 1 state?.currCount = k if (selection.size == elements.size) { // Save the result result.value[result.index] = selection.toList() result.index += 1 break } state = RecursiveState(used, selection, count - 1, 0, 1) stack.push(state) continue@MAIN_LOOP } else { val usedCopy = used.clone() usedCopy[i] = true val selectionCopy = selection.toMutableList() selectionCopy.add(elements[i]) // Update state index and count state?.index = i + 1 state?.currCount = k state = RecursiveState(usedCopy, selectionCopy, count - 1, 0, 1) stack.push(state) continue@MAIN_LOOP } } i++ // Update state index and count state?.index = i state?.currCount = k } stack.remove() state = stack.peek() } } return result.value } data class RecursiveState<T>(val used: BooleanArray, val selection: MutableList<T>, val count: Int, var index: Int, var currCount: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RecursiveState<*> if (!used.contentEquals(other.used)) return false if (selection != other.selection) return false if (count != other.count) return false if (index != other.index) return false if (currCount != other.currCount) return false return true } override fun hashCode(): Int { var result = used.contentHashCode() result = 31 * result + selection.hashCode() result = 31 * result + count result = 31 * result + index result = 31 * result + currCount return result } } }
[ { "class_path": "nickperov__Algorithms__6696f5d/com/nickperov/stud/combinatorics/experiment/PermutationsCalculatorExperiment.class", "javap": "Compiled from \"PermutationsCalculatorExperiment.kt\"\npublic final class com.nickperov.stud.combinatorics.experiment.PermutationsCalculatorExperiment {\n public st...
Feng-12138__LooSchedule__f8db57b/backend/src/main/kotlin/services/utilities/RequirementsParser.kt
package services.utilities import java.util.concurrent.ConcurrentHashMap class RequirementsParser { // requirementsData example: // ["1:CS 115,CS 135,CS 145;1:CS 136,CS 146;1:MATH 127,MATH 137,MATH 147;1:MATH 128,MATH 138,MATH 148;1:MATH 135,MATH 145;1:MATH 136,MATH 146;1:MATH 239,MATH 249;1:STAT 230,STAT 240;1:STAT 231,STAT 241;1:CS 136L;1:CS 240,CS 240E;1:CS 241,CS 241E;1:CS 245,CS 245E;1:CS 246,CS 246E;1:CS 251,CS 251E;1:CS 341;1:CS 350;3:CS 340-CS 398,CS 440-CS 489;2:CS 440-CS 489;1:CO 487,CS 440-CS 498,CS 499T,STAT 440,CS 6xx,CS 7xx"] fun parseRequirements(requirementsData: List<String>): Requirements { return finalizeRequirements(initialReqParse(requirementsData)) } private fun parseBoundedRangeCourses(course: String, courses: MutableSet<Course>): Unit { val courseRange = course.split("-") val courseLowerBound = courseRange[0].split(" ") val courseUpperBound = courseRange[1].split(" ") val courseSubject = courseLowerBound[0] val courseLowerCode = courseLowerBound[1].toInt() val courseUpperCode = courseUpperBound[1].toInt() // Add all possible course codes now. Invalid ones will be filter out when querying DB. for (i in courseLowerCode..courseUpperCode) { courses.add( Course( subject = courseSubject, code = i.toString(), ) ) } } // Parse a single requirement clause. Eg. requirement = "1:CS 115,CS 135,CS 145" private fun parseSingleReqClause(requirement: String, optionalCourses: MutableSet<OptionalCourses>, mandatoryCourses: MutableSet<Course>): Unit { val courses = mutableSetOf<Course>() val temp = requirement.split(":") val nOf = temp[0] val courseList = temp[1].split(",") for (course in courseList) { // Eg. CS 440-CS 489 if (course.contains("-")) { parseBoundedRangeCourses(course, courses) } else { val newCourse = course.split(" ") // Eg. CS 7xx if (newCourse[1].contains("xx")) { // Add all possible values of xx as course. These courses will be filtered when querying DB. for (i in 0..9) { courses.add( Course( subject = newCourse[0], code = newCourse[1][0] + "0" + i.toString(), ) ) } for (i in 10..99) { courses.add( Course( subject = newCourse[0], code = newCourse[1][0] + i.toString(), ) ) } } else { courses.add( Course( subject = newCourse[0], code = newCourse[1], ) ) } } } if (nOf.toInt() == courses.size) { mandatoryCourses.addAll(courses) } else { optionalCourses.add( OptionalCourses( nOf = nOf.toInt(), courses = courses, ) ) } } // Extract all courses needed based on requirement. fun initialReqParse(requirementsData: List<String>): Requirements { val optionalCourses = mutableSetOf<OptionalCourses>() val mandatoryCourses = mutableSetOf<Course>() for (requirements in requirementsData) { val requirement = requirements.split(";") for (r in requirement) { parseSingleReqClause(r, optionalCourses, mandatoryCourses) } } return Requirements( optionalCourses = optionalCourses, mandatoryCourses = mandatoryCourses, ) } // Finalize requirements by restraining some optional choices of courses as mandatory private fun finalizeRequirements(requirements: Requirements): Requirements { val optionalCoursesList = requirements.optionalCourses.toMutableList() val mandatoryCourses = requirements.mandatoryCourses.toMutableList() val commonTable: ConcurrentHashMap<Course, Int> = ConcurrentHashMap() for (i in 0 until optionalCoursesList.size) { for (j in i + 1 until optionalCoursesList.size) { val coursesI = optionalCoursesList[i] val coursesJ = optionalCoursesList[j] val commonCourses = coursesJ.courses.filter { coursesI.courses.contains(it) }.toSet() for (commonCourse in commonCourses) { commonTable.compute(commonCourse) { _, count -> count?.plus(1) ?: 1 } } } } val remainingOptionalCourses = mutableListOf<OptionalCourses>() for (optionalCourses in optionalCoursesList) { var commonCourses = optionalCourses.courses.filter { it in commonTable.keys }.toSet() if (commonCourses.size < optionalCourses.nOf) { optionalCourses.nOf -= commonCourses.size optionalCourses.courses.removeAll(commonCourses) remainingOptionalCourses.add(optionalCourses) } else { commonCourses = commonTable.filterKeys { it in commonCourses } .toList() .sortedBy { (_, value) -> value } .map { it.first } .take(optionalCourses.nOf) .toSet() mandatoryCourses.addAll(commonCourses) } } remainingOptionalCourses.removeIf { optionalCourses -> mandatoryCourses.containsAll(optionalCourses.courses) } // add breadth and depth mandatoryCourses.addAll( listOf( Course("ECON", "101"), Course("ECON", "102"), Course("ECON", "371"), ) ) mandatoryCourses.addAll( listOf( Course("MUSIC", "116"), Course("PHYS", "111"), Course("CHEM", "102"), ) ) return Requirements( optionalCourses = remainingOptionalCourses.toMutableSet(), mandatoryCourses = mandatoryCourses.toMutableSet(), ) } fun combineOptionalRequirements( requirements: Requirements, checkCourses: List<String>, ): CommonRequirementsData { var commonSize = 0 if (checkCourses.isNotEmpty()) { val iterator = requirements.optionalCourses.iterator() while (iterator.hasNext()) { val optionalReq = iterator.next() val commonCourses = optionalReq.courses.filter { "${it.subject} ${it.code}" in checkCourses } commonSize = commonCourses.size if (commonSize >= optionalReq.nOf) { iterator.remove() } else { optionalReq.nOf -= commonSize optionalReq.courses.removeAll(commonCourses.toSet()) } } } return CommonRequirementsData( requirements = requirements, commonSize = commonSize, ) } } data class Course ( val subject: String, val code: String, ) data class OptionalCourses ( var nOf: Int = 1, val courses: MutableSet<Course> = mutableSetOf(), ) data class Requirements ( val optionalCourses: MutableSet<OptionalCourses> = mutableSetOf(), val mandatoryCourses: MutableSet<Course> = mutableSetOf(), ) data class CommonRequirementsData ( val requirements: Requirements, val commonSize: Int, )
[ { "class_path": "Feng-12138__LooSchedule__f8db57b/services/utilities/RequirementsParser$finalizeRequirements$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class services.utilities.RequirementsParser$finalizeRequirements$$inlined$sortedBy$1<T> implements java.util.Compa...
d-costa__acacia__35aa2f3/src/commonMain/kotlin/com/github/d_costa/acacia/BinaryTree.kt
package com.github.d_costa.acacia data class BNode<T>( val value: T, val left: BNode<T>? = null, val right: BNode<T>? = null ) /** * A Binary Tree * * Supports insertion, deletion, and iteration */ class BinaryTree<T : Comparable<T>>: Iterable<T> { var root: BNode<T>? = null fun insert(value: T) { root = internalInsert(root, value) } fun exists(value: T): Boolean = findNode(root, value) != null fun find(value: T): BNode<T>? = findNode(root, value) fun delete(value: T) { root = deleteNode(root, value) } override fun iterator(): Iterator<T> = BinaryTreeIterator(root) } class BinaryTreeIterator<T : Comparable<T>>(private val bt: BNode<T>?) : Iterator<T> { private val queue = ArrayDeque<BNode<T>>() init { var current = bt while(current != null) { queue.add(current) current = current.left } } override fun hasNext(): Boolean { return queue.isNotEmpty() } override fun next(): T { if (!hasNext()) throw RuntimeException() val current = queue.removeLast() var next = current.right if(next != null) { queue.add(next) next = next.left while(next != null) { queue.add(next) next = next.left } } return current.value } } private fun <T : Comparable<T>> internalInsert(tree: BNode<T>?, value: T): BNode<T> { return if (tree == null) { BNode(value) } else if (tree.value > value) { BNode(tree.value, internalInsert(tree.left, value), tree.right) } else if (tree.value < value) { BNode(tree.value, tree.left, internalInsert(tree.right, value)) } else { BNode(tree.value, tree.left, tree.right) } } private tailrec fun <T : Comparable<T>> findNode(tree: BNode<T>?, value: T): BNode<T>? { if (tree == null) { return null } return if (tree.value > value) { findNode(tree.left, value) } else if (tree.value < value) { findNode(tree.right, value) } else { tree } } private fun <T: Comparable<T>> deleteNode(tree: BNode<T>?, value: T): BNode<T>? { if (tree == null) { return tree } var newValue = tree.value var leftSubtree = tree.left var rightSubtree = tree.right if (tree.value > value) { leftSubtree = deleteNode(tree.left, value) } else if (tree.value < value) { rightSubtree = deleteNode(tree.right, value) } else { // Found it! if (tree.left == null && tree.right == null) return null if (tree.right != null) { newValue = findSmallest(tree.right) rightSubtree = deleteNode(tree.right, newValue) } else if (tree.left != null) { newValue = findLargest(tree.left) leftSubtree = deleteNode(tree.left, newValue) } } return BNode(newValue, leftSubtree, rightSubtree) } private tailrec fun <T: Comparable<T>> findLargest(tree: BNode<T>): T { return if (tree.right != null) { findLargest(tree.right) } else { tree.value } } private tailrec fun <T: Comparable<T>> findSmallest(tree: BNode<T>): T { return if (tree.left != null) { findSmallest(tree.left) } else { tree.value } }
[ { "class_path": "d-costa__acacia__35aa2f3/com/github/d_costa/acacia/BinaryTree.class", "javap": "Compiled from \"BinaryTree.kt\"\npublic final class com.github.d_costa.acacia.BinaryTree<T extends java.lang.Comparable<? super T>> implements java.lang.Iterable<T>, kotlin.jvm.internal.markers.KMappedMarker {\n...
Devastus__aoc-2021__69f6c22/day10/app/src/main/kotlin/day10/App.kt
package day10 import java.io.File import java.util.ArrayDeque val INPUT = "input.txt" fun old() { val scoreMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val chars: CharSequence = "([{<)]}>" val charMap = mapOf('(' to 0, ')' to 4, '[' to 1, ']' to 5, '{' to 2, '}' to 6, '<' to 3, '>' to 7) var syntaxScore = 0 var complScores = ArrayList<Long>() var stack = ArrayDeque<Int>() File(INPUT).forEachLine { stack.clear() var complScore: Long = 0 var discard = false for (char in it) { var value = charMap.getValue(char) when (value) { in 0..3 -> { stack.push(value) print(char) } in 4..7 -> { var eval = stack.pop() if (eval - (value - 4) != 0) { syntaxScore += scoreMap.getValue(char) discard = true print("\u001b[31m" + char + "\u001b[0m") break; } else { print(char) } } } } if (!discard) { val len = stack.size for (i in 0..(len - 1)) { val value = (stack.pop() + 4) val char = chars[value] complScore = (complScore * 5) + (value - 3).toLong() print("\u001b[32m" + char + "\u001b[0m") } complScores.add(complScore) } print('\n') } complScores.sort() println("Syntax score: ${syntaxScore}") println("Mid score: ${complScores[(complScores.size / 2.0).toInt()]}") } fun new() { val scoreMap = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) val pairs = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val pairKeys = pairs.keys var syntaxScore = 0 var complScores = mutableListOf<Long>() var stack = mutableListOf<Char>() File(INPUT).forEachLine { line -> stack.clear() for (char in line) { if (char in pairKeys) { stack.add(char) } else if (char == pairs[stack.lastOrNull()]) { stack.removeLast() } else { syntaxScore += scoreMap[char]!!; stack.clear(); break } } if (stack.size > 0) complScores.add(stack.reversed().map { pairKeys.indexOf(it) + 1 }.fold(0L) { acc, x -> acc * 5 + x}) } println("Syntax score: ${syntaxScore}, Mid score: ${complScores.sorted()[(complScores.size / 2.0).toInt()]}") } fun main() { old() println("===================================") new() }
[ { "class_path": "Devastus__aoc-2021__69f6c22/day10/AppKt.class", "javap": "Compiled from \"App.kt\"\npublic final class day10.AppKt {\n private static final java.lang.String INPUT;\n\n public static final java.lang.String getINPUT();\n Code:\n 0: getstatic #11 // Field INPUT:L...
gouthamhusky__leetcode-journey__a0e158c/neetcode/src/main/java/org/linkedlist/LinkedList.kt
package org.linkedlist class ListNode(var `val`: Int) { var next: ListNode? = null } fun deleteDuplicates(head: ListNode?): ListNode? { var node = head ?: return null while (node!!.next != null){ if(node.`val` == node.next!!.`val`) node.next = node.next!!.next else node = node.next!! } return head } fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { var f = list1 var s = list2 var tail: ListNode? = null var mergedLL: ListNode? = null while (f != null && s != null){ if (f.`val` < s.`val`){ if (mergedLL == null){ mergedLL = ListNode(f.`val`) tail = mergedLL } else{ tail!!.next = ListNode(f.`val`) tail = tail.next } f = f.next } else{ if (mergedLL == null){ mergedLL = ListNode(s.`val`) tail = mergedLL } else{ tail!!.next = ListNode(s.`val`) tail = tail.next } s = s.next } } if (f != null){ while (f != null){ if(tail == null){ mergedLL = ListNode(f.`val`) tail = mergedLL } else{ tail.next = ListNode(f.`val`) tail = tail.next } f = f.next } } if (s != null){ while (s != null){ if(tail == null){ mergedLL = ListNode(s.`val`) tail = mergedLL } else{ tail.next = ListNode(s.`val`) tail = tail.next } s = s.next } } return mergedLL } /* https://leetcode.com/problems/linked-list-cycle/ */ fun hasCycle(head: ListNode?): Boolean { var fast = head var slow = head while (fast?.next != null){ slow = slow!!.next fast = fast.next?.next if (fast == slow) return true } return false } // find length of cycle fun lengthCycle(head: ListNode?): Int { var fast = head var slow = head while (fast?.next != null){ slow = slow!!.next fast = fast.next?.next if (fast == slow){ var length = 0 do { length++ slow = slow?.next }while (slow != fast) } } return 0 } // https://leetcode.com/problems/linked-list-cycle-ii/ fun detectCycle(head: ListNode?): ListNode? { var fast = head var slow = head var length = 0 while (fast?.next != null){ slow = slow?.next fast = fast.next!!.next if (fast == slow){ do { length++ fast = fast?.next }while (fast != slow) break; } } if (length == 0) return null var first = head var second = head while (length > 0){ second = second?.next length-- } while (first != second){ first = first?.next second = second?.next } return second } fun isHappy(n: Int): Boolean { var slow = n var fast = n do { slow = findSquare(slow) fast = findSquare(findSquare(fast)) }while (fast != slow) return slow == 1 } private fun findSquare(n: Int): Int{ var ans = 0 var num = n while (num > 0){ var rem = num % 10 ans += rem * rem num /= 10 } return ans } fun middleNode(head: ListNode?): ListNode? { var fast = head var slow = head while (fast?.next != null){ slow = slow?.next fast = fast.next?.next } return slow } /* https://leetcode.com/problems/reverse-linked-list/ in reversal */ fun reverseList(head: ListNode?): ListNode? { var prev: ListNode? = null var pres = head var next = head?.next while (pres != null){ pres.next = prev prev = pres pres = next next = next?.next } return prev } // https://leetcode.com/problems/reverse-linked-list-ii/ fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? { var h = head if (left == right) return head // skip the first left - 1 nodes var current = head var prev: ListNode? = null for (i in 0..<left - 1){ prev = current current = current?.next } val last = prev val newEnd = current // reverse between left and right var next = current?.next for (i in 0 ..< right - left +1){ current?.next = prev prev = current current = next next = next?.next } if (last != null) last.next = prev else h = prev newEnd?.next = current return h } fun isPalindrome(head: ListNode?): Boolean { var node = head // find middle var mid = middleNode(head) // reverse second half var secondHead = reverseList(mid) var reReverseHead = secondHead // compare while (node != null && secondHead != null){ if (node.`val` != secondHead.`val`) break node = node.next secondHead = secondHead.next } // re-reverse reverseList(reReverseHead) return node == null || secondHead == null } fun reorderList(head: ListNode?): Unit { if(head?.next == null) return val mid = middleNode(head) var hs = reverseList(mid) var hf = head while (hf != null && hs != null){ var temp = hf.next hf.next = hs hf = temp temp = hs.next hs.next = hf hs = temp } if (hf != null) hf.next = null }
[ { "class_path": "gouthamhusky__leetcode-journey__a0e158c/org/linkedlist/LinkedListKt.class", "javap": "Compiled from \"LinkedList.kt\"\npublic final class org.linkedlist.LinkedListKt {\n public static final org.linkedlist.ListNode deleteDuplicates(org.linkedlist.ListNode);\n Code:\n 0: aload_0\n ...
gouthamhusky__leetcode-journey__a0e158c/neetcode/src/main/java/org/slidingwindow/SlidingWindowNeet.kt
package org.slidingwindow import kotlin.math.abs // https://leetcode.com/problems/minimum-size-subarray-sum/ fun minSubArrayLen(target: Int, nums: IntArray): Int { var i = 0; var j = 0; var sum = 0; var min = Int.MAX_VALUE while (j < nums.size){ sum += nums[j] if (sum >= target){ while (sum >= target){ min = Math.min(min, j - i + 1) sum -= nums[i] i++ } } j++ } return if (min == Int.MAX_VALUE) 0 else min } fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> { var i = 0; var j = 0 // create map with key as diff and value as list of elements val map = sortedMapOf<Int, MutableList<Int>>() while(j < arr.size){ val diff = Math.abs(arr[j] - x) if (map.containsKey(diff)){ map[diff]?.add(arr[j]) } else{ map.put(diff, mutableListOf(arr[j])) } j++ } var rem = k val ans = mutableListOf<Int>() for (key in map.keys){ while (rem > 0){ map[key]?.let { it -> if (it.size > 1){ ans.add(it.removeAt(0)) rem-- } } } } return ans.sorted() } fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean { var i = 0; var j = 0 val set = mutableSetOf<Int>() while (j < nums.size){ if (set.contains(nums[j])) return true set.add(nums[j]) if (j - i + 1> k){ set.remove(nums[i]) i++ } j++ } return false } fun checkInclusion(s1: String, s2: String): Boolean { val mapForS1 = hashMapOf<Char, Int>() val mapForS2 = hashMapOf<Char, Int>() val k = s1.length for (c in s1.toCharArray()) mapForS1[c] = mapForS1.getOrDefault(c, 0) + 1 var count = mapForS1.size var i = 0 var j = 0 while (j < s2.length){ val current = s2[j] mapForS2.put(current, mapForS2.getOrDefault(current, 0) + 1) if (j -i + 1 < k) j++ else if (j - i + 1 == k){ if(compareMaps(mapForS1, mapForS2)) return true else{ mapForS2.put(s2[i], mapForS2.get(s2[i])!! - 1) if(mapForS2.get(s2[i]) == 0) mapForS2.remove(s2[i]) i++ j++ } } } return false } private fun compareMaps(map1 : Map<Char, Int>, map2: Map<Char, Int>): Boolean { for (key in map1.keys){ if (! (map2.containsKey(key) && map2.get(key) == map1.get(key))) return false } return true } fun main() { checkInclusion("adc", "dcda") }
[ { "class_path": "gouthamhusky__leetcode-journey__a0e158c/org/slidingwindow/SlidingWindowNeetKt.class", "javap": "Compiled from \"SlidingWindowNeet.kt\"\npublic final class org.slidingwindow.SlidingWindowNeetKt {\n public static final int minSubArrayLen(int, int[]);\n Code:\n 0: aload_1\n 1: ...
toddharrison__tdcreator__269b3f2/src/main/kotlin/com/eharrison/game/tdcreator/AStar.kt
package com.eharrison.game.tdcreator import java.util.PriorityQueue import java.util.ArrayList typealias Neighbors<Node> = (Node) -> List<Node> typealias Cost<Node> = (Node, Node) -> Double typealias Exclude<Node> = (Node) -> Boolean typealias Heuristic<Node> = (Node, Node) -> Double fun <Node> aStar( start: Node, goal: Node, neighbors: Neighbors<Node>, cost: Cost<Node> = { _, _ -> 1.0 }, exclude: Exclude<Node> = { _ -> false }, heuristic: Heuristic<Node> = { _, _ -> 0.0 } // Dijkstra's algorithm, only for positive costs ): List<Node> { val closedSet = mutableSetOf<Node>() // The set of nodes already evaluated. val cameFrom = mutableMapOf<Node, Node>() // The map of navigated nodes. val gScore = mutableMapOf<Node, Double>() // Cost from start along best known path. gScore[start] = 0.0 // Estimated total cost from start to goal through y. val fScore = mutableMapOf<Node, Double>() fScore[start] = heuristic(start, goal) // The set of tentative nodes to be evaluated, initially containing the start node val openSet = PriorityQueue<Node> {o1, o2 -> when { fScore[o1] ?: Double.MAX_VALUE < fScore[o2] ?: Double.MAX_VALUE -> -1 fScore[o2] ?: Double.MAX_VALUE < fScore[o1] ?: Double.MAX_VALUE -> 1 else -> 0 } } openSet.add(start) while (openSet.isNotEmpty()) { val current = openSet.poll()!! if (current == goal) { return reconstructPath(cameFrom, goal) } closedSet.add(current) for (neighbor in neighbors(current)) { if (closedSet.contains(neighbor) || exclude(neighbor)) { continue // Ignore the neighbor which is already evaluated or shouldn't be. } val tentativeGScore = gScore[current]!! + cost(current, neighbor) // Cost of this path. if (!openSet.contains(neighbor)) { openSet.add(neighbor) // Discovered a new node } else if (tentativeGScore >= gScore[neighbor]!!) { continue // Found worse path, ignore. } // This path is the best until now. Record it! cameFrom[neighbor] = current gScore[neighbor] = tentativeGScore val estimatedFScore = tentativeGScore + heuristic(neighbor, goal) fScore[neighbor] = estimatedFScore } } return emptyList() } private fun <Node> reconstructPath( cameFrom: Map<Node, Node>, current: Node? ): List<Node> { var cur = current val totalPath = ArrayList<Node>() while (cur != null) { val previous = cur cur = cameFrom[cur] if (cur != null) { totalPath.add(previous) } } totalPath.reverse() return totalPath }
[ { "class_path": "toddharrison__tdcreator__269b3f2/com/eharrison/game/tdcreator/AStarKt.class", "javap": "Compiled from \"AStar.kt\"\npublic final class com.eharrison.game.tdcreator.AStarKt {\n public static final <Node> java.util.List<Node> aStar(Node, Node, kotlin.jvm.functions.Function1<? super Node, ? e...
tohuwabohu-io__librefit__031d34c/librefit-service/src/main/kotlin/io/tohuwabohu/calc/Tdee.kt
package io.tohuwabohu.calc import kotlin.math.pow import kotlin.math.round /** * Calculation of basic metabolic rate (BMR) and total daily energy expenditure (TDEE) based on the Harris-Benedict * formula. */ data class Tdee( val age: Number, val sex: CalculationSex, val weight: Number, val height: Number, val activityLevel: Number, val weeklyDifference: Number, val calculationGoal: CalculationGoal ) { val bmr = when (sex) { CalculationSex.MALE -> { round(66 + (13.7 * weight.toFloat()) + (5 * height.toFloat()) - (6.8 * age.toFloat())) } CalculationSex.FEMALE -> { round(655 + (9.6 * weight.toFloat()) + (1.8 * height.toFloat()) - (4.7 * age.toFloat())) } } val tdee = round(activityLevel.toFloat() * bmr) val deficit = weeklyDifference.toFloat() / 10 * 7000 / 7 val target: Float = when (calculationGoal) { CalculationGoal.GAIN -> { tdee.toFloat() + deficit } CalculationGoal.LOSS -> { tdee.toFloat() - deficit; } } val bmi: Float = round(weight.toFloat() / ((height.toFloat() / 100).pow(2))) val bmiCategory: BmiCategory = when (sex) { CalculationSex.FEMALE -> { when (bmi) { in 0f..18f -> BmiCategory.UNDERWEIGHT in 19f..24f -> BmiCategory.STANDARD_WEIGHT in 25f..30f -> BmiCategory.OVERWEIGHT in 31f..40f -> BmiCategory.OBESE else -> BmiCategory.SEVERELY_OBESE } } CalculationSex.MALE -> { when (bmi) { in 0f..19f -> BmiCategory.UNDERWEIGHT in 20f..25f -> BmiCategory.STANDARD_WEIGHT in 26f..30f -> BmiCategory.OVERWEIGHT in 31f..40f -> BmiCategory.OBESE else -> BmiCategory.SEVERELY_OBESE } } } val targetBmi = when (age) { in 19..24 -> arrayOf(19,24) in 25..34 -> arrayOf(20,25) in 35..44 -> arrayOf(21,26) in 45..54 -> arrayOf(22,27) in 55..64 -> arrayOf(23,28) else -> arrayOf(24,29) } val targetWeight = round(((targetBmi[0] + targetBmi[1]).toFloat() / 2) * (height.toFloat() / 100).pow(2)) val durationDays = when (calculationGoal) { CalculationGoal.GAIN -> { (targetWeight - weight.toFloat()) * 7000 / deficit } CalculationGoal.LOSS -> { (weight.toFloat() - targetWeight) * 7000 / deficit } } } enum class CalculationGoal { GAIN, LOSS } enum class CalculationSex { MALE, FEMALE } enum class BmiCategory { UNDERWEIGHT, STANDARD_WEIGHT, OVERWEIGHT, OBESE, SEVERELY_OBESE, }
[ { "class_path": "tohuwabohu-io__librefit__031d34c/io/tohuwabohu/calc/Tdee$WhenMappings.class", "javap": "Compiled from \"Tdee.kt\"\npublic final class io.tohuwabohu.calc.Tdee$WhenMappings {\n public static final int[] $EnumSwitchMapping$0;\n\n public static final int[] $EnumSwitchMapping$1;\n\n static {}...
AZenhom__Problem-Solving__a2ea0dd/CF_892_2_B/CF_892_2_B.kt
package com.ahmedzenhom.problem_solving.cf_892_2_b var input = mutableListOf<String>( // Not to be included in your submitting "3", "2", "2", "1 2", "2", "4 3", "1", "3", "100 1 6", "3", "4", "1001 7 1007 5", "3", "8 11 6", "2", "2 9" ) fun readLine(): String? { // Not to be included in your submitting val line = input.firstOrNull() input.removeAt(0) return line } // You answer goes here fun main() { val tests = readLine()?.toInt()!! repeat(tests) { val noOfarrays = readLine()?.toInt()!! val arrays = mutableListOf<List<Long>>() var minFirst = -1L var minSecond = Pair(-1L, -1L) for (i in 0 until noOfarrays) { readLine() val array = readLine()!!.split(" ").toList().map { it.toLong() }.sorted() arrays.add(array) val firstSmallest = array[0] if (minFirst == -1L || firstSmallest < minFirst) { minFirst = firstSmallest } val secondSmallest = array[1] if (minSecond.first == -1L || secondSmallest < minSecond.second) { minSecond = Pair(i.toLong(), secondSmallest) } } var sum = 0L for (i in 0 until noOfarrays) { sum += (if (i.toLong() != minSecond.first) arrays[i][1] else minFirst) } println(sum) } }
[ { "class_path": "AZenhom__Problem-Solving__a2ea0dd/com/ahmedzenhom/problem_solving/cf_892_2_b/CF_892_2_BKt.class", "javap": "Compiled from \"CF_892_2_B.kt\"\npublic final class com.ahmedzenhom.problem_solving.cf_892_2_b.CF_892_2_BKt {\n private static java.util.List<java.lang.String> input;\n\n public sta...
mhiew__translation-tool__8261d9e/src/main/kotlin/com/minhiew/translation/Analyzer.kt
package com.minhiew.translation object Analyzer { fun compare(androidStrings: Map<String, String>, iosStrings: Map<String, String>): LocalizationReport { return LocalizationReport( uniqueAndroidStrings = androidStrings.filterForKeysNotPresentIn(iosStrings), uniqueIosStrings = iosStrings.filterForKeysNotPresentIn(androidStrings), commonAndroidStrings = androidStrings.filterForMatchingKeysIn(iosStrings), commonIosStrings = iosStrings.filterForMatchingKeysIn(androidStrings) ) } } data class LocalizationReport( val uniqueAndroidStrings: Map<String, String>, val uniqueIosStrings: Map<String, String>, val commonAndroidStrings: Map<String, String>, val commonIosStrings: Map<String, String>, ) { //returns the common key to string comparison between ios and android val stringComparisons: Map<String, StringComparison> = commonAndroidStrings.entries.associate { val key = it.key val androidValue: String = it.value val iosValue: String = commonIosStrings[key] ?: "" key to StringComparison( key = key, androidValue = androidValue, iosValue = iosValue ) } val differences: List<StringComparison> = stringComparisons.values.filterNot { it.isExactMatch } val exactMatches: List<StringComparison> = stringComparisons.values.filter { it.isExactMatch } val caseInsensitiveMatches: List<StringComparison> = stringComparisons.values.filter { it.isCaseInsensitiveMatch } val mismatchedPlaceholders: List<StringComparison> = differences.filter { it.hasMismatchedPlaceholders } } data class StringComparison( val key: String, val androidValue: String, val iosValue: String, ) { val isExactMatch: Boolean = androidValue == iosValue val isCaseInsensitiveMatch = !isExactMatch && androidValue.lowercase() == iosValue.lowercase() val iosPlaceholderCount: Int = iosValue.placeholderCount() val androidPlaceholderCount: Int = androidValue.placeholderCount() val hasMismatchedPlaceholders = iosPlaceholderCount != androidPlaceholderCount } //returns the keys within this map that do not belong to the other map fun Map<String, String>.filterForKeysNotPresentIn(other: Map<String, String>): Map<String, String> = this.filterKeys { !other.containsKey(it) } fun Map<String, String>.filterForMatchingKeysIn(other: Map<String, String>): Map<String, String> = this.filterKeys { other.containsKey(it) } //calculates the total number of occurrences of placeholders fun String.placeholderCount(): Int = totalOccurrence(input = this, placeholders = setOf("%@", "%d", "%s", "%f", "\$@", "\$d", "\$s", "\$f")) private fun totalOccurrence(input: String, placeholders: Set<String>): Int { return placeholders.fold(initial = 0) { acc, placeholder -> acc + input.numberOfOccurrence(placeholder) } } private fun String.numberOfOccurrence(substring: String): Int { var count = 0 var index = this.indexOf(substring, startIndex = 0, ignoreCase = true) while (index > -1) { count += 1 index = this.indexOf(substring, startIndex = index + 1, ignoreCase = true) } return count }
[ { "class_path": "mhiew__translation-tool__8261d9e/com/minhiew/translation/Analyzer.class", "javap": "Compiled from \"Analyzer.kt\"\npublic final class com.minhiew.translation.Analyzer {\n public static final com.minhiew.translation.Analyzer INSTANCE;\n\n private com.minhiew.translation.Analyzer();\n Co...
parmeshtoyou__DSAPlaybook__aea9c82/src/main/kotlin/sorting/MergeSort.kt
package sorting //sort the left half //sort the right half //merge both the half fun main() { val input = intArrayOf(23, 47, 81, -1, 95, 7, 14, 39, 55, 63, 74) val temp = IntArray(input.size) { -1 } println("before sorting") for (i in input) { println(i) } mergeSort(input, temp) println("after sorting") for (i in input) { println(i) } } fun mergeSort(input: IntArray, temp: IntArray) { val start = 0 val end = input.size - 1 mergeSortRec(input, temp, start, end) } fun mergeSortRec(input: IntArray, temp: IntArray, lowerBound: Int, upperBound: Int) { if (lowerBound == upperBound) { return } val mid = lowerBound + (upperBound - lowerBound) / 2 mergeSortRec(input, temp, lowerBound, mid) mergeSortRec(input, temp, mid + 1, upperBound) merge(input, temp, lowerBound, mid + 1, upperBound) } fun merge(input: IntArray, temp: IntArray, start: Int, middle: Int, upperBound: Int) { var j = 0 val mid = middle - 1 var highPtr = middle var lowPtr = start val size = upperBound - start + 1 while (lowPtr <= mid && highPtr <= upperBound) { if (input[lowPtr] < input[highPtr]) { temp[j++] = input[lowPtr++] } else { temp[j++] = input[highPtr++] } } while (lowPtr <= mid) { temp[j++] = input[lowPtr++] } while (highPtr <= upperBound) { temp[j++] = input[highPtr++] } for (k in 0 until size) { input[start + k] = temp[k] } }
[ { "class_path": "parmeshtoyou__DSAPlaybook__aea9c82/sorting/MergeSortKt.class", "javap": "Compiled from \"MergeSort.kt\"\npublic final class sorting.MergeSortKt {\n public static final void main();\n Code:\n 0: bipush 11\n 2: newarray int\n 4: astore_1\n 5: aload_1\n...
stangls__krangl__dfa3a6c/src/main/kotlin/krangl/util/Util.kt
package krangl.util // // Functional Helpers (missing in kotlin-stdlib) // // todo should they go into separate artifact? // adopted from https://stackoverflow.com/questions/44429419/what-is-basic-difference-between-fold-and-reduce-in-kotlin-when-to-use-which // desc from https://stackoverflow.com/questions/17408880/reduce-fold-or-scan-left-right /** scanLeft and scanRight cumulate a collection of intermediate cumulative results using a start value. */ fun <T, R> Sequence<T>.scanLeft(initial: R, operation: (R, T) -> R) = fold(listOf(initial), { list, curVal -> list + operation(list.last(), curVal) }) fun <T, R> Sequence<T>.foldWhile(initial: R, operation: (R, T) -> R, predicate: (R) -> Boolean): R = scanLeft(initial, operation).takeWhile { predicate(it) }.last() fun <T, R> Sequence<T>.foldUntil(initial: R, operation: (R, T) -> R, predicate: (R) -> Boolean): R? = scanLeft(initial, operation).dropWhile { predicate(it) }.firstOrNull() fun <T, R> Sequence<T>.reduceUntil(operation: (R?, T) -> R, predicate: (R) -> Boolean): R? = drop(1).scanLeft(operation(null, first()), operation).dropWhile { predicate(it) }.firstOrNull() // Misc helpers internal fun Sequence<*>.joinToMaxLengthString( maxLength: Int = 80, separator: CharSequence = ", ", truncated: CharSequence = "...", transform: ((Any?) -> String) = { it?.toString() ?: "" } ): String = reduceUntil({ a: String?, b -> (a?.let { it + separator } ?: "") + transform(b) }, { it.length < maxLength })?.let { when { it.length < maxLength -> it else -> it.substring(0, maxLength) + truncated } } ?: joinToString(transform = { transform(it) }) //fun main(args: Array<String>) { // // listOf(1,2,3, 4).asSequence().scanLeft(0, { a, b -> a+b}).also{print(it)} // // // listOf("foo", "haus", "baum", "lala").asSequence().scanLeft("", {a,b ->a+b}).also{print(it)} // listOf("foo", "haus", "baum", "lala").asSequence().foldWhile("", { a, b -> a + b }, { // it.length < 30 // }).also { print(it) } //}
[ { "class_path": "stangls__krangl__dfa3a6c/krangl/util/UtilKt.class", "javap": "Compiled from \"Util.kt\"\npublic final class krangl.util.UtilKt {\n public static final <T, R> java.util.List<R> scanLeft(kotlin.sequences.Sequence<? extends T>, R, kotlin.jvm.functions.Function2<? super R, ? super T, ? extends...
RobinGoussey__advent_of_code23__b1421c0/src/main/kotlin/org/rgoussey/aoc2023/day3/Main.kt
package org.rgoussey.aoc2023.day3 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val lines = File({}.javaClass.getResource("/day3/input.txt")!!.toURI()).readLines(); process(lines); } fun process(lines: List<String>) { val characters = mutableListOf<MutableList<Char>>() val symbols = mutableListOf<MutableList<Boolean>>() val numbers = mutableListOf<MutableList<Boolean>>() val closeToSymbol = mutableListOf<MutableList<Boolean>>() for (i in lines.indices) { characters.add(i, mutableListOf()) symbols.add(i, mutableListOf()) numbers.add(i, mutableListOf()) closeToSymbol.add(i, mutableListOf()) for (j in lines[i].indices) { val currentChar = lines[i][j] characters[i].add(j, currentChar) val isSymbol = isSymbol(currentChar) symbols[i].add(j, isSymbol) numbers[i].add(j, isNumber(currentChar)) } } for (i in lines.indices) { for (j in lines[i].indices) { closeToSymbol[i].add(j, adjacentToSymbol(symbols, i, j)) } } printMap(symbols) printMap(numbers) printMap(closeToSymbol) var sum = 0; for (i in characters.indices) { var currentNumber = ""; var lastNumberIndex = 0; var numberIsValid = false; for (j in characters[i].indices) { val isNumber = numbers[i][j] if (isNumber) { numberIsValid = numberIsValid or adjacentToSymbol(symbols, i, j) lastNumberIndex = j currentNumber += characters[i][j] val endOfLine = j == characters[i].size-1 if (endOfLine) { val number = Integer.parseInt(currentNumber) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = "" lastNumberIndex = 0; } } else { val numberEnded = lastNumberIndex + 1 == j if (numberEnded && currentNumber != "") { val number = Integer.parseInt(currentNumber) // println("Number is detected %s".format(number)) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = ""; numberIsValid=false } lastNumberIndex = 0; } } } println("Sum is $sum") } fun printMap(map: MutableList<MutableList<Boolean>>) { for (i in map.indices) { for (j in map[i].indices) { if (map[i][j]) { print('x') } else { print('.') } } print("\n"); } print("\n"); } fun adjacentToSymbol(symbols: MutableList<MutableList<Boolean>>, x: Int, y: Int): Boolean { for (i in max(x - 1, 0)..min(x + 1, symbols.size - 1)) { for (j in max(y - 1, 0)..min(y + 1, symbols[x].size - 1)) { if (symbols[i][j]) { return true } } } return false; } fun isSymbol(char: Char): Boolean { return !isNumber(char) && char != '.'; } fun isNumber(char: Char): Boolean { return char in '0'..'9'; }
[ { "class_path": "RobinGoussey__advent_of_code23__b1421c0/org/rgoussey/aoc2023/day3/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class org.rgoussey.aoc2023.day3.MainKt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n ...
brunogabriel__algorithms__050a709/algorithms-kotlin/src/main/kotlin/io/github/brunogabriel/math/MatrixOperations.kt
package io.github.brunogabriel.math fun matrixMultiplication( matrixA: List<List<Long>>, matrixB: List<List<Long>> ): List<List<Long>> { if (matrixA.first().size != matrixB.size) { return emptyList() } val result = Array(matrixA.size) { Array(matrixB.first().size) { 0L } } for (i in matrixA.indices) { for (j in matrixB[i].indices) { for (k in matrixA[i].indices) { result[i][j] += matrixA[i][k] * matrixB[k][j] } } } return result.map { it.toList() } } fun matrixSummation( matrixA: List<List<Long>>, matrixB: List<List<Long>> ): List<List<Long>> { if (matrixA.size != matrixB.size || matrixA.indices != matrixB.indices) { return emptyList() } matrixA.indices.forEach { if (matrixA[it].size != matrixB[it].size) { return emptyList() } } val result = Array(matrixA.size) { Array(matrixA.first().size) { 0L } } for (i in matrixA.indices) { for (j in matrixA[i].indices) { result[i][j] = matrixA[i][j] + matrixB[i][j] } } return result.map { it.toList() } } operator fun List<List<Long>>.times(other: List<List<Long>>): List<List<Long>> = matrixMultiplication(this, other) operator fun List<List<Long>>.plus(other: List<List<Long>>): List<List<Long>> = matrixSummation(this, other)
[ { "class_path": "brunogabriel__algorithms__050a709/io/github/brunogabriel/math/MatrixOperationsKt.class", "javap": "Compiled from \"MatrixOperations.kt\"\npublic final class io.github.brunogabriel.math.MatrixOperationsKt {\n public static final java.util.List<java.util.List<java.lang.Long>> matrixMultiplic...
vihangpatil__kotlin-tricks__d1f3da3/src/main/kotlin/io/github/vihangpatil/kotlintricks/range/RangeExtensions.kt
package io.github.vihangpatil.kotlintricks.range /** * @param[other] [ClosedRange]<[T]> * @return [Boolean] if this [Comparable]<[T]> overlaps with [other] */ private fun <T : Comparable<T>> ClosedRange<T>.overlapsWith( other: ClosedRange<T> ): Boolean { return (other.start in start..endInclusive || other.endInclusive in start..endInclusive) } /** * @param[other] [ClosedRange]<[T]> * @return [Collection]<[ClosedRange]<[T]>> with [this] and [other] if they do not overlap, or with just one merged * [ClosedRange]<[T]> if they overlap. */ private fun <T : Comparable<T>> ClosedRange<T>.mergeWith( other: ClosedRange<T> ): Collection<ClosedRange<T>> { // if they do not overlap return if (!overlapsWith(other)) { // then return them separately listOf(this, other) } else { // else merge them listOf(minOf(start, other.start)..maxOf(endInclusive, other.endInclusive)) } } /** * @return [Collection]<[ClosedRange]<[T]>> with overlapping [ClosedRange]<[T]> merged. */ fun <T : Comparable<T>> Collection<ClosedRange<T>>.mergeRanges(): Collection<ClosedRange<T>> { // no changes for empty collection or collection with single element if (this.size < 2) { return this } return sortedBy { it.start } // sort by start of range .fold(initial = emptyList()) { list: List<ClosedRange<T>>, element: ClosedRange<T> -> if (list.isEmpty()) { // for first element listOf(element) } else { // Attempt to merge last of the list with the element. // If they are overlapping, [mergeWith] will return collection with single merged element. // Or else, it will return list with two elements. list.last().mergeWith(element) + // drop last element to avoid it to be duplicate list.dropLast(1) } } } /** * @param[asRange] Function to map [E] to [ClosedRange]<[T]>. * @param[asElement] Function to map [ClosedRange]<[T]> to [E]. * @return [Collection]<[E]> with overlapping [ClosedRange]<[T]> merged. */ fun <E, T : Comparable<T>> Collection<E>.mergeBy( asRange: (E) -> ClosedRange<T>, asElement: (ClosedRange<T>) -> E ): Collection<E> { // no changes for empty collection or collection with single element if (this.size < 2) { return this } return sortedBy { element -> // sort by start of range asRange(element).start }.fold(initial = emptyList()) { list: List<E>, element: E -> if (list.isEmpty()) { // for first element listOf(element) } else { // Attempt to merge last of the list with the element. // If they are overlapping, [mergeWith] will return collection with single merged element. // Or else, it will return list with two elements. asRange(list.last()).mergeWith(asRange(element)).map(asElement) + // drop last element to avoid it to be duplicate list.dropLast(1) } } }
[ { "class_path": "vihangpatil__kotlin-tricks__d1f3da3/io/github/vihangpatil/kotlintricks/range/RangeExtensionsKt$mergeBy$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class io.github.vihangpatil.kotlintricks.range.RangeExtensionsKt$mergeBy$$inlined$sortedBy$1<T> impleme...
boti996__lileto_tests__190fbe5/src/test/kotlin/boti996/lileto/tests/helpers/DataHelpers.kt
package boti996.lileto.tests.helpers // Lileto null value internal const val liletoNullValue = "-" /** * Alias for simple testcases. * [Pair]'s first element is a [String] in Lileto language. * [Pair]'s second element is the expected result [String]. */ internal typealias testcase = Pair<String, String> internal typealias testcases = List<testcase> internal fun testcase.getKeyType() = this.first::class internal fun testcase.getValueType() = this.second::class /** * Store the literals of Lileto brackets * @param literals opening and closing characters */ internal enum class BracketType(private val literals: Pair<Char, Char>) { TEXT(Pair('"', '"')), TEMPLATE(Pair('<', '>')), SPECIAL_CHAR(Pair('$', '$')), COMMAND(Pair('!', '!')), CONTAINER(Pair('[', ']')), COMMENT(Pair('.', '.')); fun open() = "{${literals.first}" fun close() = "${literals.second}}" } /** * Store the literals of Lileto special characters * @param values Lileto literal and the resolved values */ internal enum class SpecialCharacter(private val values: Pair<String, Char>) { ENTER (Pair("e", '\n')), TAB (Pair("t", '\t')), SPACE (Pair("s", ' ')), O_R_BRACKET (Pair("orb", '(')), C_R_BBRACKET(Pair("crb", ')')), EQUALS_SIGN (Pair("eq", '=')), PLUS_SIGN (Pair("pl", '+')), O_C_BRACKET (Pair("ocb", '{')), C_C_BRACKET (Pair("ccb", '}')), POINT (Pair("pe", '.')), COMMA (Pair("co", ',')), SEMICOLON (Pair("sc", ';')), COLON (Pair("cl", ':')), VBAR (Pair("pi", '|')), LT_SIGN (Pair("ls", '<')), GT_SIGN (Pair("gt", '>')), QUESTION_M (Pair("qm", '?')), EXCLAM_M (Pair("dm", '!')); fun literal() = values.first fun character() = values.second.toString() } /** * Store bracket with it's content * @param bracket type of bracket */ internal data class BracketWithContent(val bracket: BracketType, val content: Any) { fun open() = bracket.open() fun close() = bracket.close() } /** * Convert an [Array] of [BracketType] and [Any] type of content * into a [List] of [BracketWithContent] * @param brackets data to convert */ internal fun bracketListOf(brackets: List<Pair<BracketType, Any>>) : List<BracketWithContent> = brackets.map { BracketWithContent( bracket = it.first, content = it.second ) } /** * Concatenate a [List] of [Any] type of data into a [String] and return it in [Pair] with the expected [String] * @param input data to concatenate in Lileto language format * @param expected expected output of Lileto in plain text */ internal fun buildTestCaseEntry(input: List<Any>, expected: String) : testcase { return Pair(input.joinToString(separator = ""), expected) }
[ { "class_path": "boti996__lileto_tests__190fbe5/boti996/lileto/tests/helpers/DataHelpersKt.class", "javap": "Compiled from \"DataHelpers.kt\"\npublic final class boti996.lileto.tests.helpers.DataHelpersKt {\n public static final java.lang.String liletoNullValue;\n\n public static final kotlin.reflect.KCla...
nehemiaharchives__cpsd__055a7ba/src/main/kotlin/org/gnit/cpsd/GeoCalculation.kt
package org.gnit.cpsd import kotlin.math.* /** * [Reference](https://stackoverflow.com/questions/3694380/calculating-distance-between-two-points-using-latitude-longitude) * * Calculate distance between two points in latitude and longitude taking * into account height difference. If you are not interested in height * difference pass 0.0. Uses Haversine method as its base. * * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters * el2 End altitude in meters * @returns Distance in Meters */ fun distanceOf( lat1: Double, lat2: Double, lng1: Double, lng2: Double, el1: Double, el2: Double ): Double { val R = 6371 // Radius of the earth val latDistance = Math.toRadians(lat2 - lat1) val lonDistance = Math.toRadians(lng2 - lng1) val a = (sin(latDistance / 2) * sin(latDistance / 2) + (cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(lonDistance / 2) * sin(lonDistance / 2))) val c = 2 * atan2(sqrt(a), sqrt(1 - a)) var distance = R * c * 1000 // convert to meters val height = el1 - el2 distance = distance.pow(2.0) + height.pow(2.0) return sqrt(distance) } /** * [Reference](https://gis.stackexchange.com/questions/15545/calculating-coordinates-of-square-x-miles-from-center-point) * @param lat latitude of center coordinate for square polygon * @param lng longitude of center coordinate for square polygon * @param side length of the side of square in meters * @return array of 5 coordinates to draw square polygon with GeoJson, order of corner is SW->SE->NE->NW->SW */ fun squareOf(lat: Double, lng: Double, side: Double): Array<Array<Double>> { val dLat = side / (111 * 1000) // Latitudinal or north-south distance in degrees val dLng = dLat / cos(Math.toRadians(lat)) // Longitudinal or east-west distance in degrees val nLat = dLat / 2 val nLng = dLng / 2 val lat1 = lat - nLat val lng1 = lng - nLng val lat2 = lat - nLat val lng2 = lng + nLng val lat3 = lat + nLat val lng3 = lng + nLng val lat4 = lat + nLat val lng4 = lng - nLng return arrayOf( arrayOf(lng1, lat1), arrayOf(lng2, lat2), arrayOf(lng3, lat3), arrayOf(lng4, lat4), arrayOf(lng1, lat1) ) } /** * @param latNE latitude of first geo polygon coordinate which is north-east corner * @param lngNE longitude of first geo polygon coordinate which is north-east corner * @param latSW latitude of third geo polygon coordinate which is south-west corner * @param lngSW longitude of third geo polygon coordinate which is south-west corner * @return array of Double representing (latitude, longitude) of center of the square */ fun centerOf(latNE: Double, lngNE: Double, latSW: Double, lngSW: Double): Array<Double> = arrayOf( (latNE + latSW) * 0.5, (lngNE + lngSW) * 0.5 )
[ { "class_path": "nehemiaharchives__cpsd__055a7ba/org/gnit/cpsd/GeoCalculationKt.class", "javap": "Compiled from \"GeoCalculation.kt\"\npublic final class org.gnit.cpsd.GeoCalculationKt {\n public static final double distanceOf(double, double, double, double, double, double);\n Code:\n 0: sipush ...
EduanPrinsloo__RoverKata__5ee857f/src/main/kotlin/com/thedevadventure/roverkata/RoverKata.kt
package com.thedevadventure.roverkata import java.util.* fun main() { val scanner = Scanner(System.`in`) // Get and validate the plateau println("Please enter the dimensions of your plateau starting with the size of X?") val plateauDimensionsX = scanner.nextInt() println("And the size of Y?") val plateauDimensionsY = scanner.nextInt() val marsTerrain = Plateau(plateauDimensionsX, plateauDimensionsY) validatePlateau(marsTerrain) // Get and validate the locations of the rovers println("Please enter the first rovers coordinates, starting with X hitting enter and then Y...") val firstRoverLocation = Location(scanner.nextInt(), scanner.nextInt()) val firstRoverCommands = getRoverCommands(scanner) println("Please enter the second rovers coordinates, starting with X hitting enter and then Y...") val secondRoverLocation = Location(scanner.nextInt(), scanner.nextInt()) val secondRoverCommands = getRoverCommands(scanner) validateTheRoverHasLanded(marsTerrain, firstRoverLocation) validateTheRoverHasLanded(marsTerrain, secondRoverLocation) explore(marsTerrain, firstRoverLocation, firstRoverCommands) explore(marsTerrain, secondRoverLocation, secondRoverCommands) checkIntersections( explore(marsTerrain, firstRoverLocation, firstRoverCommands), explore(marsTerrain, secondRoverLocation, secondRoverCommands) ) } fun validatePlateau(plateauDimensions: Plateau): Boolean { if (plateauDimensions.X > 0 && plateauDimensions.Y > 0) { println("Thank you for passing a valid plateau...") return true } else { throw Exception("Invalid plateau passed both your inputs should be larger than 0!") } } fun validateTheRoverHasLanded(plateau: Plateau, location: Location): Boolean { if ((location.X > plateau.X || location.X < 0) || (location.Y > plateau.Y || location.Y < 0)) { throw Exception("Mission failed... The rover missed the target!") } else { println("Rover has been located on the plateau, good job!") return true } } fun validateRoverCommands(commands: String): Instructions { if (!commands.uppercase().all { it.isLetter().and(it == 'N' || it == 'S' || it == 'W' || it == 'E') }) { throw Exception("Computer says No!") } val roverCommands = Instructions(commands.uppercase()) println("Commands received: ${roverCommands.roverCommands}...") return roverCommands } fun getRoverCommands(scanner: Scanner): Instructions { println("Please enter the command sequence for the first rover... valid inputs are limited to N, E, W, and S! ") val roverCommands = scanner.next() return validateRoverCommands(roverCommands) } fun explore(plateau: Plateau, startingLocation: Location, roverInstructions: Instructions): MutableList<Location> { val instructions = roverInstructions.roverCommands.map { it } val pathPoints = mutableListOf<Location>() var currentLocation = startingLocation pathPoints.add(startingLocation) for (instruction in instructions) { val result = move(instruction, currentLocation) isValidRoverPosition(result, plateau) pathPoints.add(result) currentLocation = result } return pathPoints } fun move(input: Char, location: Location): Location { return when (input.uppercaseChar()) { 'N' -> increaseY(location) 'E' -> increaseX(location) 'S' -> decreaseY(location) 'W' -> decreaseX(location) else -> location } } fun isValidRoverPosition(currentLocation: Location, plateau: Plateau): Boolean { if ((currentLocation.X > plateau.X || currentLocation.X < 0) || (currentLocation.Y > plateau.Y || currentLocation.Y < 0)) { throw Exception("Mission failed... The rover was lost at $currentLocation...") } else return true } fun increaseX(location: Location): Location { return Location(location.X + 1, location.Y) } fun increaseY(location: Location): Location { return Location(location.X, location.Y + 1) } fun decreaseX(location: Location): Location { return Location(location.X - 1, location.Y) } fun decreaseY(location: Location): Location { return Location(location.X, location.Y - 1) } fun checkIntersections(pathPoints1: List<Location>, pathPoints2: List<Location>): MutableList<Location> { val intersections = pathPoints1.intersect(pathPoints2.toSet()).toMutableList() if (intersections.isEmpty()) { throw Exception("No Intersections found...") } else { println("Intersection point are: $intersections") } return intersections } data class Plateau(val X: Int, val Y: Int) data class Location(val X: Int, val Y: Int) data class Instructions(val roverCommands: String)
[ { "class_path": "EduanPrinsloo__RoverKata__5ee857f/com/thedevadventure/roverkata/RoverKataKt.class", "javap": "Compiled from \"RoverKata.kt\"\npublic final class com.thedevadventure.roverkata.RoverKataKt {\n public static final void main();\n Code:\n 0: new #8 // class j...
kodeflap__Algo_Guide__c4a7ddb/app/src/main/java/com/dlight/algoguide/dsa/dynamic_programming/Longest_Common_Subsequence/lcs.kt
package com.dlight.algoguide.dsa.dynamic_programming.Longest_Common_Subsequence import java.util.* object lcs { @JvmStatic fun main(args: Array<String>) { val s1 = "abcde" val s2 = "ace" println("The Length of Longest Common Subsequence is " + longestCommonSubsequence(s1, s2)) } private fun longestCommonSubsequence(s1: String, s2: String): Int { val n = s1.length val m = s2.length val dp = Array(n + 1) { IntArray( m + 1 ) } for (rows in dp) { Arrays.fill(rows, -1) } for (i in 0..n) { dp[i][0] = 0 } for (i in 0..m) { dp[0][i] = 0 } for (ind1 in 0..n) { for (ind2 in 0..m) { if (s1[ind1] == s2[ind2]) { dp[ind1][ind2] = 1 + dp[ind1 - 1][ind2 - 1] } else { dp[ind1][ind2] = Math.max(dp[ind1 - 1][ind2], dp[ind1][ind2 - 1]) } } } return dp[n][m] } }
[ { "class_path": "kodeflap__Algo_Guide__c4a7ddb/com/dlight/algoguide/dsa/dynamic_programming/Longest_Common_Subsequence/lcs.class", "javap": "Compiled from \"lcs.kt\"\npublic final class com.dlight.algoguide.dsa.dynamic_programming.Longest_Common_Subsequence.lcs {\n public static final com.dlight.algoguide....
kodeflap__Algo_Guide__c4a7ddb/app/src/main/java/com/dlight/algoguide/dsa/sorting/quick_sort/QuickSort.kt
package com.dlight.algoguide.dsa.sorting.quick_sort /** * Quick sort * * @constructor Create empty Quick sort */ class QuickSort { suspend fun quickSort( arr: IntArray, left: Int, right: Int) { /*First finding the partioning index using thepartion function */ val index = partition (arr, left, right) if (left < index - 1) /*checking for better position left or right then performing thr sort*/ quickSort(arr, left, index - 1) if (index < right ) quickSort(arr, index, right) } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ private fun partition(arr: IntArray, left: Int, right: Int): Int { var left = left var right = right /* Pivot point */ val pivot = arr[(left + right) / 2] while (left <= right) { while (arr[left] < pivot) left++ while (arr[right] > pivot) right-- if (left <= right) { swap(arr, left, right) left++ right-- } } return left } /*Swap function that helps in swaping the numbers */ private fun swap(arr: IntArray, left: Int, right: Int) { val temp = arr [left] arr[left] = arr[right] arr[right] = temp } }
[ { "class_path": "kodeflap__Algo_Guide__c4a7ddb/com/dlight/algoguide/dsa/sorting/quick_sort/QuickSort$quickSort$1.class", "javap": "Compiled from \"QuickSort.kt\"\nfinal class com.dlight.algoguide.dsa.sorting.quick_sort.QuickSort$quickSort$1 extends kotlin.coroutines.jvm.internal.ContinuationImpl {\n java.l...
abdurakhmonoff__data-structures-and-algorithms-kotlin__cd9746d/src/algorithms/sorting/merge_sort/MergeSort.kt
package algorithms.sorting.merge_sort /** * Implementation of the merge sort algorithm for sorting a list of integers in ascending order. */ class MergeSort { /** * Recursively sorts the given list by dividing it into halves and merging them. * * @param array the list to sort * @return the sorted list */ fun mergeSort(array: List<Int>): List<Int> { // Base case: if array has only one number, it is already sorted if (array.size == 1) { return array } // Divide the array into two halves and recursively sort each half val left = array.subList(0, array.size / 2) val right = array.subList(array.size / 2, array.size) return merge(mergeSort(left), mergeSort(right)) } /** * Merges two sorted lists into a single sorted list. * * @param left the first sorted list * @param right the second sorted list * @return the merged sorted list */ private fun merge(left: List<Int>, right: List<Int>): List<Int> { val result = ArrayList<Int>() var leftIndex = 0 var rightIndex = 0 // Iterate through both lists, comparing the numbers and adding the smaller one to the result list while (leftIndex < left.size && rightIndex < right.size) { if (left[leftIndex] < right[rightIndex]) { result.add(left[leftIndex]) leftIndex++ } else { result.add(right[rightIndex]) rightIndex++ } } // Add any remaining numbers from the left and right lists val leftRemaining = left.subList(leftIndex, left.size) val rightRemaining = right.subList(rightIndex, right.size) result.addAll(leftRemaining) result.addAll(rightRemaining) return result } } fun main() { val mergeSort = MergeSort() val numbers = ArrayList(listOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0)) println(mergeSort.mergeSort(numbers)) }
[ { "class_path": "abdurakhmonoff__data-structures-and-algorithms-kotlin__cd9746d/algorithms/sorting/merge_sort/MergeSortKt.class", "javap": "Compiled from \"MergeSort.kt\"\npublic final class algorithms.sorting.merge_sort.MergeSortKt {\n public static final void main();\n Code:\n 0: new #...