kt_path
stringlengths
35
167
kt_source
stringlengths
626
28.9k
classes
listlengths
1
17
hahaslav__Kotlin-Basics__5ca7234/Cinema.kt
package cinema const val SEATSLIMIT = 60 const val VIPRICE = 10 const val POORPRICE = 8 fun inputRoom(): String { println("Enter the number of rows:") val r = readLine()!! println("Enter the number of seats in each row:") val s = readLine()!! return "$r $s" } fun scheme(cinema: MutableList<MutableList<Char>>) { print("\nCinema:\n ") for (i in 1..cinema[0].size) print(" $i") println() for (i in 0 until cinema.size) println("${i + 1} ${cinema[i].joinToString(" ")}") } fun inputSeat(): String { println("\nEnter a row number:") val r = readLine()!! println("Enter a seat number in that row:") val s = readLine()!! return "$r $s" } fun smallRoom() = VIPRICE fun bigRoom(rows: Int, seatR: Int) = if (seatR <= rows / 2) VIPRICE else POORPRICE fun calculateSeat(cinema: MutableList<MutableList<Char>>, seatR: Int): Int { if (cinema.size * cinema[0].size <= SEATSLIMIT) { return smallRoom() } return bigRoom(cinema.size, seatR) } fun shopping(cinema: MutableList<MutableList<Char>>) { val (seatR, seatS) = inputSeat().split(" ").map { it.toInt() } println() if (seatR < 1 || seatR > cinema.size || seatS < 1 || seatS > cinema[0].size) { println("Wrong input!") shopping(cinema) return } when (cinema[seatR - 1][seatS - 1]) { 'S' -> { cinema[seatR - 1][seatS - 1] = 'B' println("Ticket price: \$${calculateSeat(cinema, seatR)}") } 'B' -> { println("That ticket has already been purchased!") shopping(cinema) } } } fun calculateAll(cinema: MutableList<MutableList<Char>>): Int { var result = 0 for (row in 0 until cinema.size) for (seat in cinema[row]) result += calculateSeat(cinema, row + 1) return result } fun stats(cinema: MutableList<MutableList<Char>>) { var bought = 0 var income = 0 for (row in cinema) for (seat in row) bought += if (seat == 'B') 1 else 0 println("\nNumber of purchased tickets: $bought") var notPrc = bought * 100000 / (cinema.size * cinema[0].size) notPrc = (notPrc + if (notPrc % 10 > 4) 10 else 0) / 10 val prc = (notPrc / 100).toString() + "." + (notPrc % 100 / 10).toString() + (notPrc % 10).toString() println("Percentage: ${prc}%") for (row in 0 until cinema.size) for (seat in cinema[row]) income += if (seat == 'B') calculateSeat(cinema, row + 1) else 0 println("Current income: \$$income") println("Total income: \$${calculateAll(cinema)}") } fun main() { val (rows, seats) = inputRoom().split(" ").map { it.toInt() } val cinema = MutableList(rows) { MutableList(seats) { 'S' } } var choice = -1 while (choice != 0) { println() println(""" 1. Show the seats 2. Buy a ticket 3. Statistics 0. Exit """.trimIndent()) choice = readLine()!!.toInt() when (choice) { 1 -> scheme(cinema) 2 -> shopping(cinema) 3 -> stats(cinema) } } }
[ { "class_path": "hahaslav__Kotlin-Basics__5ca7234/cinema/CinemaKt.class", "javap": "Compiled from \"Cinema.kt\"\npublic final class cinema.CinemaKt {\n public static final int SEATSLIMIT;\n\n public static final int VIPRICE;\n\n public static final int POORPRICE;\n\n public static final java.lang.String...
ahuamana__KotlinCorutinesExpert__931ce88/app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/PalindromicNew.kt
package com.lukaslechner.coroutineusecasesonandroid.playground.challenges //Have the function StringChallenge(str) take the str parameter being passed and determine if it is possible to create a palindromic string of minimum length 3 characters by removing 1 or 2 characters //For example: if str is "abjchba" then you can remove the characters jc to produce "abhba" which is a palindrome. //For this example your program should return the two characters that were removed with no delimiter and in the order they appear in the string, so jc. //If 1 or 2 characters cannot be removed to produce a palindrome, then return the string not possible. //If the input string is already a palindrome, your program should return the string palindrome. //The input will only contain lowercase alphabetic characters. //Your program should always attempt to create the longest palindromic substring by removing 1 or 2 characters // (see second sample test case as an example). //The 2 characters you remove do not have to be adjacent in the string. //Examples //Input: "mmop" //Output: not possible //Input: "kjjjhjjj" //Output: k private fun stringChallenge(str: String): String { if (str == str.reversed()) return "palindrome" //min length 3 characters if (str.length < 3) return "not possible" str.indices.forEachIndexed { index, _ -> //remove 1 character val newStr = str.removeRange(index, index + 1) //min length 3 characters if (newStr.length < 3) return "not possible" if (newStr == newStr.reversed()) return str[index].toString() //remove 2 characters } //remove 2 characters (not adjacent) str.indices.forEachIndexed { index, _ -> val newStr = str.removeRange(index, index + 2) if (newStr.length < 3) return "not possible" if (newStr == newStr.reversed()) return str[index].toString() + str[index + 1].toString() } //If any of the above conditions are not met, return "not possible" return "not possible" } //test StringChallenge fun main () { println(stringChallenge("abh")) println(stringChallenge("abhba")) println(stringChallenge("mmop")) println(stringChallenge("kjjjhjjj")) println(stringChallenge("abjchba")) }
[ { "class_path": "ahuamana__KotlinCorutinesExpert__931ce88/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/PalindromicNewKt.class", "javap": "Compiled from \"PalindromicNew.kt\"\npublic final class com.lukaslechner.coroutineusecasesonandroid.playground.challenges.PalindromicNewKt {\n priva...
ahuamana__KotlinCorutinesExpert__931ce88/app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/SearchingChallenge.kt
package com.lukaslechner.coroutineusecasesonandroid.playground.challenges //find the longest substring that contains k unique characters //The input string str must have at least length 2. //The first character of str must be a digit between 1 and 6 (inclusive), representing the number of unique characters in the longest substring to be found. //The remaining characters of str must be printable ASCII characters (i.e., characters with ASCII codes between 32 and 126, inclusive). //The function should return the longest substring of str that contains exactly k unique characters, where k is the digit extracted from the first character of str. //If there are multiple longest substrings that satisfy the above condition, the function should return the first one. fun SearchingChallenge(str: String): String { //The input string str must have at least length 2. if(str.length < 2) return "not possible" //get the number of unique characters handle exception use elvis operator val k = str[0].toString().toIntOrNull() ?: return "not possible" if(k !in 1..6) return "not possible" //Remove the first character from the string val substring = str.substring(1) //get the longest substring that contains k unique characters val longestSubstring = getLongestSubstring(substring, k) return if(longestSubstring.isEmpty()) "not possible" else longestSubstring } fun getLongestSubstring(substring: String, k: Int): String { //get the list of all substrings val substrings = mutableListOf<String>() for (i in substring.indices) { for (j in i + 1..substring.length) { substrings.add(substring.substring(i, j)) } } //get the list of all substring that contains k unique characters val substringsWithKUniqueChars = mutableListOf<String>() substrings.forEach { if(it.toSet().size == k) substringsWithKUniqueChars.add(it) } //get the longest substring that contains k unique characters avoid use maxByOrNull var longestSubstring = "" substringsWithKUniqueChars.forEach { if(it.length > longestSubstring.length) longestSubstring = it } return longestSubstring } fun main() { println(SearchingChallenge("3aabacbebebe")) //cbebebe println(SearchingChallenge("2aabbcbbbadef")) //bbcbbb println(SearchingChallenge("2aabbacbaa")) //aabba }
[ { "class_path": "ahuamana__KotlinCorutinesExpert__931ce88/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/SearchingChallengeKt.class", "javap": "Compiled from \"SearchingChallenge.kt\"\npublic final class com.lukaslechner.coroutineusecasesonandroid.playground.challenges.SearchingChallengeK...
ahuamana__KotlinCorutinesExpert__931ce88/app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/MathChallenge.kt
package com.lukaslechner.coroutineusecasesonandroid.playground.challenges // Challenge // Have the function MathChallenge(str) take the str parameter, which will be a simple mathematical formula with three numbers, a single operator (+, -, *, or /) and an equal sign (=) and return the digit that completes the equation. In one of the numbers in the equation, there will be an x character, and your program should determine what digit is missing. For example, if str is "3x + 12 = 46" then your program should output 4. The x character can appear in any of the three numbers and all three numbers will be greater than or equal to 0 and less than or equal to 1000000. // Examples // Input: "4 - 2 = x" // Output: 2 // Input: "1x0 * 12 = 1200" // Output: 0 // Input: "3x + 12 = 46" // Output: 4 //Constrainst //1. The x character can appear in any of the three numbers -> has x in it //2. all three numbers will be greater than or equal to 0 and less than or equal to 1000000. //Identify the missing number private fun MathChallenge(str: String): String { //validate constraints 1 -> has x in it if (!str.contains("x")) return "not possible" //validate constraints 2 -> all three numbers will be greater than or equal to 0 and less than or equal to 1000000. val numbersSplit = str.split(" ") //remove operators and equal sign val numbersOnlyValid = numbersSplit.filter { it != "+" && it != "-" && it != "*" && it != "/" && it != "=" } //convert to int val numbersOnlyIntegers = numbersOnlyValid.map { //if it contains x, replace it with 1 if (it.contains("x")) 1 else it.toInt() } //check if all numbers are between 0 and 1000000 numbersOnlyIntegers.forEach { if (it < 0 || it > 1000000) return "not possible" } for(digit in 0..9){ val newStr = str.replace("x", digit.toString()) val numbers = newStr.split(" ") val numbersOnly = numbers.filter { it != "+" && it != "-" && it != "*" && it != "/" && it != "=" } val numbersOnlyInt = numbersOnly.map { //if it contains x, replace it with 1 if (it.contains("x")) 1 else it.toInt() } val firstNumber = numbersOnlyInt[0] val secondNumber = numbersOnlyInt[1] val thirdNumber = numbersOnlyInt[2] val operator = numbers[1] //check if the equation is correct if (operator == "+") { if (firstNumber + secondNumber == thirdNumber) return digit.toString() } if (operator == "-") { if (firstNumber - secondNumber == thirdNumber) return digit.toString() } if (operator == "*") { if (firstNumber * secondNumber == thirdNumber) return digit.toString() } if (operator == "/") { if (firstNumber / secondNumber == thirdNumber) return digit.toString() } } //if no digit is found return "not possible" } fun main () { println(MathChallenge("4 - 2 = x")) println(MathChallenge("1x0 * 12 = 1200")) println(MathChallenge("3x + 12 = 46")) }
[ { "class_path": "ahuamana__KotlinCorutinesExpert__931ce88/com/lukaslechner/coroutineusecasesonandroid/playground/challenges/MathChallengeKt.class", "javap": "Compiled from \"MathChallenge.kt\"\npublic final class com.lukaslechner.coroutineusecasesonandroid.playground.challenges.MathChallengeKt {\n private ...
jksolbakken__aoc_2020__4c5e7a4/src/main/kotlin/day2/Day2.kt
package day2 import java.io.File fun main() { val input = File(object {}.javaClass.getResource("/day2/input.txt").toURI()).readLines() println("char count: ${matchingNrOfChars(input)}") println("char position: ${matchingPosition(input)}") } fun matchingNrOfChars(lines: List<String>) = prepare(lines) .map { (ruleAsString, password) -> Pair(charCountRule(ruleAsString), password) } .count { (rule, password) -> rule(password) } fun matchingPosition(lines: List<String>) = prepare(lines) .map { (ruleAsString, password) -> Pair(charPositionRule(ruleAsString), password) } .count { (rule, password) -> rule(password) } private fun charCountRule(asText: String): (String) -> Boolean = asText.split(" ").let { (charCounts, character) -> val (min, max) = charCounts.split("-").map { it.toInt() } val range = IntRange(min, max) val char = character.first() return { password -> password.filter { it == char }.count() in range } } private fun charPositionRule(asText: String): (String) -> Boolean = asText.split(" ").let { (positions, character) -> val (firstPos, secondPos) = positions.split("-").map { it.toInt() } val char = character.first() return { password -> password.withIndex().count { indexMatches(it.index, firstPos, secondPos) && it.value == char } == 1 } } private fun prepare(input: List<String>) = input.filter { it.isNotEmpty() }.map { it.split(": ") } private fun indexMatches(actualIndex: Int, vararg desiredIndices: Int) = actualIndex + 1 in desiredIndices
[ { "class_path": "jksolbakken__aoc_2020__4c5e7a4/day2/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2Kt {\n public static final void main();\n Code:\n 0: new #8 // class java/io/File\n 3: dup\n 4: new #10 ...
tieren1__LeetCodePractice__427fa28/app/src/test/java/com/terencepeh/leetcodepractice/IntersectionArrays.kt
package com.terencepeh.leetcodepractice fun intersection(nums1: IntArray, nums2: IntArray): IntArray { return nums1.intersect(nums2.toHashSet()).toIntArray() } fun intersection2(nums1: IntArray, nums2: IntArray): IntArray { val set1 = nums1.toHashSet() val set2 = nums2.toHashSet() return if (set1.size > set2.size) { setIntersection(set1, set2) } else { setIntersection(set2, set1) } } fun setIntersection(set1: HashSet<Int>, set2: HashSet<Int>): IntArray { val output = mutableListOf<Int>() set2.forEach { s -> if (set1.contains(s)) { output.add(s) } } return output.toIntArray() } fun main() { val nums1 = intArrayOf(4, 9, 5, 1) val nums2 = intArrayOf(9, 4, 9, 8, 4) println("intersection: ${intersection(nums1, nums2).contentToString()}") println("intersection: ${intersection2(nums1, nums2).contentToString()}") }
[ { "class_path": "tieren1__LeetCodePractice__427fa28/com/terencepeh/leetcodepractice/IntersectionArraysKt.class", "javap": "Compiled from \"IntersectionArrays.kt\"\npublic final class com.terencepeh.leetcodepractice.IntersectionArraysKt {\n public static final int[] intersection(int[], int[]);\n Code:\n ...
tieren1__LeetCodePractice__427fa28/app/src/test/java/com/terencepeh/leetcodepractice/LowestCommonAncestorBST.kt
package com.terencepeh.leetcodepractice /** * Created by <NAME> on 26/10/22. */ /** * Definition for a binary tree node. * class TreeNode(var `val`: Int = 0) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class TreeNode(var `val`: Int = 0) { var left: TreeNode? = null var right: TreeNode? = null } fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null) { return null } val current = root.`val` val pVal = p!!.`val` val qVal = q!!.`val` if (pVal > current && qVal > current) { return lowestCommonAncestor(root.right, p, q) } if (pVal < current && qVal < current) { return lowestCommonAncestor(root.left, p, q) } return root } fun lowestCommonAncestor2(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { if (root == null) { return null } var node = root val pVal = p!!.`val` val qVal = q!!.`val` while (node != null) { node = if (pVal > node.`val` && qVal > node.`val`) { node.right } else if (pVal < node.`val` && qVal < node.`val`) { node.left } else { break } } return node } fun main() { val input = TreeNode(6).apply { left = TreeNode(2).apply { left = TreeNode(0) right = TreeNode(4).apply { left = TreeNode(3) right = TreeNode(5) } } right = TreeNode(8).apply { left = TreeNode(7) right = TreeNode(9) } } print(input) var p = TreeNode(2) var q = TreeNode(8) println(lowestCommonAncestor(input, p, q)?.`val`) p = TreeNode(2) q = TreeNode(4) println(lowestCommonAncestor2(input, p, q)?.`val`) p = TreeNode(2) q = TreeNode(1) println(lowestCommonAncestor(input, p, q)?.`val`) }
[ { "class_path": "tieren1__LeetCodePractice__427fa28/com/terencepeh/leetcodepractice/LowestCommonAncestorBSTKt.class", "javap": "Compiled from \"LowestCommonAncestorBST.kt\"\npublic final class com.terencepeh.leetcodepractice.LowestCommonAncestorBSTKt {\n public static final com.terencepeh.leetcodepractice....
tieren1__LeetCodePractice__427fa28/app/src/test/java/com/terencepeh/leetcodepractice/RecursiveSum.kt
package com.terencepeh.leetcodepractice fun sum(arr: IntArray): Int { println("Size = ${arr.size}") return when { arr.isEmpty() -> 0 else -> arr[0] + sum(arr.copyOfRange(1, arr.size)) } } fun count(list: List<Any>): Int { return when { list.isEmpty() -> 0 else -> 1 + count(list.subList(1, list.size)) } } private fun max(list: IntArray): Int = when { list.size == 2 -> if (list[0] > list[1]) list[0] else list[1] else -> { val subMax = max(list.copyOfRange(1, list.size)) if (list[0] > subMax) list[0] else subMax } } fun main() { println(sum(intArrayOf(1, 2, 3, 4, 5))) println(count(listOf(1, 2, 3, 4, 5))) println(max(intArrayOf(1, 5, 10, 25, 16, 1))) // 25 }
[ { "class_path": "tieren1__LeetCodePractice__427fa28/com/terencepeh/leetcodepractice/RecursiveSumKt.class", "javap": "Compiled from \"RecursiveSum.kt\"\npublic final class com.terencepeh.leetcodepractice.RecursiveSumKt {\n public static final int sum(int[]);\n Code:\n 0: aload_0\n 1: ldc ...
tieren1__LeetCodePractice__427fa28/app/src/test/java/com/terencepeh/leetcodepractice/GroupAnagrams.kt
package com.terencepeh.leetcodepractice // O(NKlogK) // O(NK) fun groupAnagrams(strs: Array<String>): List<List<String>> { if (strs.isEmpty()) { return emptyList() } val hashMap = hashMapOf<String, MutableList<String>>() for (s in strs) { val ca = s.toCharArray() ca.sort() val key = String(ca) if (!hashMap.containsKey(key)) { hashMap[key] = arrayListOf() } hashMap[key]!!.add(s) } return ArrayList(hashMap.values) } fun matchAnagrams(strs: Array<String>, originalWord: String): List<String> { if (originalWord.isBlank()) { return emptyList() } val input = originalWord.toCharArray() input.sort() val inputKey = String(input) val hashMap = hashMapOf<String, MutableList<String>>() for (s in strs) { val ca = s.toCharArray() ca.sort() val key = String(ca) if (!hashMap.containsKey(key)) { hashMap[key] = arrayListOf() } hashMap[key]!!.add(s) } return hashMap[inputKey] ?: emptyList() } fun main() { val strs = arrayOf("eat", "tea", "tan", "ate", "nat", "bat") println("groupAnagrams result: ${groupAnagrams(strs)}") println("matchAnagrams result: ${matchAnagrams(strs, "ant")}") }
[ { "class_path": "tieren1__LeetCodePractice__427fa28/com/terencepeh/leetcodepractice/GroupAnagramsKt.class", "javap": "Compiled from \"GroupAnagrams.kt\"\npublic final class com.terencepeh.leetcodepractice.GroupAnagramsKt {\n public static final java.util.List<java.util.List<java.lang.String>> groupAnagrams...
tieren1__LeetCodePractice__427fa28/app/src/test/java/com/terencepeh/leetcodepractice/BestTimeToBuyAndSellStock.kt
package com.terencepeh.leetcodepractice /** * Created by <NAME> on 7/9/22. */ // o(n2) fun maxProfitBruteForce(prices: IntArray): Int { var maxProfit = 0 for (i in 0 until prices.size - 1) { for (j in i until prices.size) { val profit = prices[j] - prices[i] if (profit > maxProfit) { maxProfit = profit } } } return maxProfit } // O(n) fun maxProfitTwoPointer(prices: IntArray): Int { var left = 0 var right = 1 var maxProfit = 0 while (right < prices.size) { if (prices[left] < prices[right]) { val profit = prices[right] - prices[left] maxProfit = kotlin.math.max(maxProfit, profit) } else { left = right } right += 1 } return maxProfit } fun maxProfit(prices: IntArray): Int { var minPrice = Integer.MAX_VALUE var maxProfit = 0 for (i in prices.indices) { if (prices[i] < minPrice) { minPrice = prices[i] } else { val profit = prices[i] - minPrice maxProfit = kotlin.math.max(maxProfit, profit) } } return maxProfit } fun main() { val input1 = intArrayOf(7, 1, 5, 3, 6, 4) val input2 = intArrayOf(7, 6, 4, 3, 1) println("Prices input1 = ${maxProfitBruteForce(input1)}") println("Prices input2 = ${maxProfitBruteForce(input2)}") println("Prices input1 = ${maxProfitTwoPointer(input1)}") println("Prices input2 = ${maxProfitTwoPointer(input2)}") println("Prices input1 = ${maxProfit(input1)}") println("Prices input2 = ${maxProfit(input2)}") }
[ { "class_path": "tieren1__LeetCodePractice__427fa28/com/terencepeh/leetcodepractice/BestTimeToBuyAndSellStockKt.class", "javap": "Compiled from \"BestTimeToBuyAndSellStock.kt\"\npublic final class com.terencepeh.leetcodepractice.BestTimeToBuyAndSellStockKt {\n public static final int maxProfitBruteForce(in...
dokerplp__abit-vt-bot__b3c530a/src/main/kotlin/dokerplp/bot/utli/StrignSimilarity.kt
package dokerplp.bot.utli import java.util.* /* Code was taken from https://stackoverflow.com/questions/955110/similarity-string-comparison-in-java */ /** * Calculates the similarity (a number within 0 and 1) between two strings. */ fun stringSimilarity(s1: String, s2: String): Double { var longer = s1 var shorter = s2 if (s1.length < s2.length) { // longer should always have greater length longer = s2 shorter = s1 } val longerLength = longer.length return if (longerLength == 0) { 1.0 /* both strings are zero length */ } else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble() /* // If you have Apache Commons Text, you can use it to calculate the edit distance: LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); return (longerLength - levenshteinDistance.apply(longer, shorter)) / (double) longerLength; */ } // Example implementation of the Levenshtein Edit Distance // See http://rosettacode.org/wiki/Levenshtein_distance#Java private fun editDistance(s1: String, s2: String): Int { var s1 = s1 var s2 = s2 s1 = s1.lowercase(Locale.getDefault()) s2 = s2.lowercase(Locale.getDefault()) val costs = IntArray(s2.length + 1) for (i in 0..s1.length) { var lastValue = i for (j in 0..s2.length) { if (i == 0) costs[j] = j else { if (j > 0) { var newValue = costs[j - 1] if (s1[i - 1] != s2[j - 1]) newValue = Math.min( Math.min(newValue, lastValue), costs[j] ) + 1 costs[j - 1] = lastValue lastValue = newValue } } } if (i > 0) costs[s2.length] = lastValue } return costs[s2.length] }
[ { "class_path": "dokerplp__abit-vt-bot__b3c530a/dokerplp/bot/utli/StrignSimilarityKt.class", "javap": "Compiled from \"StrignSimilarity.kt\"\npublic final class dokerplp.bot.utli.StrignSimilarityKt {\n public static final double stringSimilarity(java.lang.String, java.lang.String);\n Code:\n 0: al...
willowtreeapps__assertk__5ff8a09/assertk/src/commonMain/kotlin/assertk/assertions/support/ListDiffer.kt
package assertk.assertions.support /** * List diffing using the Myers diff algorithm. */ internal object ListDiffer { fun diff(a: List<*>, b: List<*>): List<Edit> { val diff = mutableListOf<Edit>() backtrack(a, b) { prevX, prevY, x, y -> diff.add( 0, when { x == prevX -> Edit.Ins(prevY, b[prevY]) y == prevY -> Edit.Del(prevX, a[prevX]) else -> Edit.Eq(prevX, a[prevX], prevY, b[prevY]) } ) } return diff } sealed class Edit { sealed class Mod : Edit() data class Ins(val newIndex: Int, val newValue: Any?) : Mod() data class Del(val oldIndex: Int, val oldValue: Any?) : Mod() data class Eq(val oldIndex: Int, val oldValue: Any?, val newIndex: Int, val newValue: Any?) : Edit() } private fun shortestEdit(a: List<*>, b: List<*>): List<IntArray> { val n = a.size val m = b.size val max = n + m if (max == 0) { return emptyList() } val v = IntArray(2 * max + 1) val trace = mutableListOf<IntArray>() for (d in 0..max) { trace += v.copyOf() for (k in -d..d step 2) { var x = if (k == -d || (k != d && v.ringIndex(k - 1) < v.ringIndex(k + 1))) { v.ringIndex(k + 1) } else { v.ringIndex(k - 1) + 1 } var y = x - k while (x < n && y < m && a[x] == b[y]) { x += 1 y += 1 } v.ringIndexAssign(k, x) if (x >= n && y >= m) { return trace } } } return trace } private fun IntArray.ringIndex(index: Int): Int = this[if (index < 0) size + index else index] private fun IntArray.ringIndexAssign(index: Int, value: Int) { this[if (index < 0) size + index else index] = value } private fun backtrack(a: List<*>, b: List<*>, yield: (Int, Int, Int, Int) -> Unit) { var x = a.size var y = b.size val shortestEdit = shortestEdit(a, b) for (d in shortestEdit.size - 1 downTo 0) { val v = shortestEdit[d] val k = x - y val prevK = if (k == -d || (k != d && v.ringIndex(k - 1) < v.ringIndex(k + 1))) { k + 1 } else { k - 1 } val prevX = v.ringIndex(prevK) val prevY = prevX - prevK while (x > prevX && y > prevY) { yield(x - 1, y - 1, x, y) x -= 1 y -= 1 } if (d > 0) { yield(prevX, prevY, x, y) } x = prevX y = prevY } } }
[ { "class_path": "willowtreeapps__assertk__5ff8a09/assertk/assertions/support/ListDiffer.class", "javap": "Compiled from \"ListDiffer.kt\"\npublic final class assertk.assertions.support.ListDiffer {\n public static final assertk.assertions.support.ListDiffer INSTANCE;\n\n private assertk.assertions.support...
tiksem__KotlinSpirit__8c2001f/src/main/java/com/kotlinspirit/ext/RangeExtensions.kt
package com.kotlinspirit.ext import java.util.StringJoiner internal operator fun CharRange.minus(range: CharRange): List<CharRange> { if (range.first <= this.first && range.last >= this.last) { return emptyList() } return if (range.first > this.first && range.last < this.last) { listOf( first until range.first, (range.last + 1)..last ) } else if (range.first <= this.first && range.last >= this.first) { listOf( (range.last + 1)..this.last ) } else if (range.first > this.first && range.last >= this.last && range.first <= this.last) { listOf( this.first until range.first ) } else { listOf(this) } } internal operator fun CharRange.plus(range: CharRange): List<CharRange> { return when { range.first <= this.first && range.last >= this.last -> { listOf(range) } this.first <= range.first && this.last >= range.last -> { listOf(this) } range.first <= this.first && range.last <= this.last && range.last >= this.first - 1 -> { listOf(range.first..this.last) } range.first > this.first && range.last >= this.last && range.first <= this.last + 1 -> { listOf(this.first..range.last) } else -> { return listOf(this, range) } } } // List should be sorted by first private fun List<CharRange>.optimizeRanges(): List<CharRange> { if (size <= 1) { return this } val result = arrayListOf(this[0]) var i = 1 val size = this.size while (i < size) { result.addAll(result.removeLast() + this[i]) i++ } return result } internal fun List<CharRange>.includeRanges(ranges: List<CharRange>): List<CharRange> { return (this + ranges).sortedBy { it.first }.optimizeRanges() } internal fun List<CharRange>.excludeRange(range: CharRange): List<CharRange> { val result = ArrayList<CharRange>() for (thisRange in this) { result.addAll(thisRange - range) } return result } internal fun List<CharRange>.excludeRanges(ranges: List<CharRange>): List<CharRange> { if (ranges.isEmpty()) { return this } var list = this for (range in ranges) { list = list.excludeRange(range) } return list.sortedBy { it.first }.optimizeRanges() } internal val IntRange.debugString: String get() { if (this.last == Int.MAX_VALUE) { return "$first,max" } else { return "$first,$last" } }
[ { "class_path": "tiksem__KotlinSpirit__8c2001f/com/kotlinspirit/ext/RangeExtensionsKt.class", "javap": "Compiled from \"RangeExtensions.kt\"\npublic final class com.kotlinspirit.ext.RangeExtensionsKt {\n public static final java.util.List<kotlin.ranges.CharRange> minus(kotlin.ranges.CharRange, kotlin.range...
JonasKellerer__motivsearch__7d57ab6/src/main/kotlin/org/motivesearch/csma/MotiveGenerator.kt
package org.motivesearch.csma data class MotiveUnit(val name: String) data class MotivePosition(val position: Int, val length: Int) data class Motive(val positions: List<MotivePosition>, val frequency: Int, val sequence: List<MotiveUnit>) { companion object { fun fromPositions(positions: List<MotivePosition>, sequence: List<MotiveUnit>) = Motive(positions, positions.size, sequence) } } class MotiveGenerator { fun generateMotives( sequence: List<MotiveUnit>, minFrequency: Int, maxGap: Int, minLength: Int, maxLength: Int ): List<Motive> { val basicMotives = getBasicMotives(sequence, minFrequency) var motivesOfIteration = basicMotives var motivesOfAllIterations = emptyList<Motive>() while (motivesOfIteration.isNotEmpty()) { motivesOfIteration = motiveOfIteration(motivesOfIteration, basicMotives, minFrequency, maxLength, maxGap) motivesOfAllIterations = motivesOfAllIterations + motivesOfIteration.filter { it.sequence.size >= minLength} } return motivesOfAllIterations } private fun motiveOfIteration( motivesOfLastIteration: List<Motive>, baseMotives: List<Motive>, minFrequency: Int, maxLength: Int, maxGap: Int ): List<Motive> { val motivesOfNextIteration = motivesOfLastIteration.map { motiveOfIteration -> val frequentPosition = getFrequentPosition(motiveOfIteration, minFrequency) val candidateExtensions = generateCandidateExtension(baseMotives, frequentPosition) candidateExtensions.map { candidateExtension -> mergeMotives(motiveOfIteration, candidateExtension, maxGap, maxLength) } }.flatten() return filterMotives(motivesOfNextIteration, minFrequency, maxLength) } fun getBasicMotives(sequence: List<MotiveUnit>, minFrequency: Int): List<Motive> { val basicMotiveUnits = sequence.toSet() val basicMotives = basicMotiveUnits.map { it to Motive(emptyList(), 0, listOf(it)) } .toMap().toMutableMap() sequence.forEachIndexed { index, motiveUnit -> val motive = basicMotives[motiveUnit]!! val newPositions = motive.positions.toMutableList() newPositions.add(MotivePosition(index, 1)) basicMotives[motiveUnit] = motive.copy(positions = newPositions, frequency = motive.frequency + 1) } val basicMotivesAboveMinFrequency = basicMotives.filter { it.value.frequency >= minFrequency } return basicMotivesAboveMinFrequency.values.toList() } fun getMotiveUnits(sequence: String): List<MotiveUnit> { val uniqueValues = sequence.split(",") return uniqueValues.map { MotiveUnit(it) } } fun getFrequentPosition(motive: Motive, minFrequency: Int): Int { if (motive.frequency < minFrequency) throw IllegalArgumentException("Motiv frequency is less than minFrequency") val position = motive.positions[minFrequency - 1] return position.position + position.length } fun generateCandidateExtension(baseMotives: List<Motive>, frequentPosition: Int): List<Motive> { return baseMotives.filter { baseMotive -> baseMotive.positions.any { position -> position.position >= frequentPosition - 1 } } } fun mergeMotives(motive: Motive, candidateExtension: Motive, maxGap: Int, maxLength: Int): Motive { val newSequence = motive.sequence + candidateExtension.sequence val newPositions = motive.positions.map { position -> val nextCandidatePosition = candidateExtension.positions.filter { candidatePosition -> val notToLargeGap = candidatePosition.position - (position.position + position.length) <= maxGap val afterPosition = candidatePosition.position >= (position.position + position.length) val notToLong = candidatePosition.position + candidatePosition.length - position.position <= maxLength notToLargeGap && afterPosition && notToLong }.firstOrNull() if (nextCandidatePosition != null) { MotivePosition(position.position, position.length + nextCandidatePosition.length) } else { null } }.filterNotNull() return motive.copy(positions = newPositions, frequency = newPositions.size, sequence = newSequence) } private fun filterMotives(motives: List<Motive>, minFrequency: Int, maxLength: Int): List<Motive> { return motives.filter { it.frequency >= minFrequency && it.sequence.size <= maxLength } } }
[ { "class_path": "JonasKellerer__motivsearch__7d57ab6/org/motivesearch/csma/MotiveGenerator.class", "javap": "Compiled from \"MotiveGenerator.kt\"\npublic final class org.motivesearch.csma.MotiveGenerator {\n public org.motivesearch.csma.MotiveGenerator();\n Code:\n 0: aload_0\n 1: invokespec...
WeiLianYang__AlgorithmAnalysis__0b2defc/src/com/weiliange/algorithm/AddTwoNumbers.kt
package com.weiliange.algorithm import kotlin.math.pow /** * @author : WilliamYang * @date : 2022/3/8 11:36 * @description : <a href="https://leetcode-cn.com/problems/add-two-numbers">两数相加</a> * * 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。 * 请你将两个数相加,并以相同形式返回一个表示和的链表。 * 你可以假设除了数字 0 之外,这两个数都不会以 0 开头。 * * 示例 1: * 输入:l1 = [2,4,3], l2 = [5,6,4] * 输出:[7,0,8] * 解释:342 + 465 = 807. * * 示例 2: * 输入:l1 = [0], l2 = [0] * 输出:[0] * * 示例 3: * 输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] * 输出:[8,9,9,9,0,0,0,1] * * 提示: * 每个链表中的节点数在范围 [1, 100] 内 * 0 <= Node.val <= 9 * 题目数据保证列表表示的数字不含前导零 * */ data class ListNode( var value: Int = 0, var next: ListNode? = null ) /** * 第一种:没有考虑链表长度,存在溢出情况 * @param l1 链表1 * @param l2 链表2 */ fun addTwoNumbers1(l1: ListNode?, l2: ListNode?): ListNode { println(l1) println(l2) println("---------> start <---------") val list1 = arrayListOf<Int>() val list2 = arrayListOf<Int>() flatNodeValue(l1, list1) flatNodeValue(l2, list2) println(list1) println(list2) val sum1 = sumNodeValue(list1) val sum2 = sumNodeValue(list2) val sum = sum1 + sum2 println("sum1: $sum1, sum2: $sum2, sum: $sum") return numberToNode(sum) } /** * 链表中的节点值展开为集合 * @param node 链表 * @param list 集合 */ fun flatNodeValue(node: ListNode?, list: ArrayList<Int>): ArrayList<Int> { if (node == null) { return list } list.add(node.value) return flatNodeValue(node.next, list) } /** * 对链表中的数求和 * @param list */ fun sumNodeValue(list: ArrayList<Int>): Int { var sum = 0 list.forEachIndexed { index, value -> val r = 10f.pow(index.toFloat()) * value sum += r.toInt() } return sum } /** * 将数字转为链表 */ fun numberToNode(number: Int): ListNode { val source = number.toString().reversed() println("source: $source") var firstNode: ListNode? = null var node: ListNode? = null source.forEachIndexed { _, char -> if (node == null) { node = ListNode(char.digitToInt()) firstNode = node } else { val nextNode = ListNode(char.digitToInt()) node?.next = nextNode node = nextNode } } println(firstNode) return firstNode!! } /** * 第二种:解决第一种中的溢出情况,其实就是解决大数相加问题: * * 1. 将对应位的数字逆序相加,然后存到数组中 * 2. 检查数组中的各项如果 >=10,就将该项 /10=十位上的数,再累加到后一项。将该项对 %10=个位,重新赋值给当前项 * 3. 最后再逆序组装获得链表 */ fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode { println(l1) println(l2) println("---------> start <---------") val list1 = arrayListOf<Int>() val list2 = arrayListOf<Int>() flatNodeValue(l1, list1) flatNodeValue(l2, list2) println(list1) println(list2) return ListNode() } fun main() { val node11 = ListNode(1) val node12 = ListNode(2, node11) val node13 = ListNode(3, node12) // [2, 1] + [3, 2, 1] = [5, 3, 1] // 12 + 123 = 135 // ListNode(value=5, next=ListNode(value=3, next=ListNode(value=1, next=null))) addTwoNumbers1(node12, node13) }
[ { "class_path": "WeiLianYang__AlgorithmAnalysis__0b2defc/com/weiliange/algorithm/AddTwoNumbersKt.class", "javap": "Compiled from \"AddTwoNumbers.kt\"\npublic final class com.weiliange.algorithm.AddTwoNumbersKt {\n public static final com.weiliange.algorithm.ListNode addTwoNumbers1(com.weiliange.algorithm.L...
jihedamine__kotlin_coursera__61e7156/src/rationals/Rational.kt
package rationals import java.lang.IllegalArgumentException import java.lang.NumberFormatException import java.math.BigInteger class Rational { private val numerator: BigInteger private val denominator: BigInteger constructor(numerator: BigInteger) : this(numerator, BigInteger.ONE) constructor(numerator: Number): this(numerator, 1) constructor(numerator: Number, denominator: Number) : this(BigInteger.valueOf(numerator.toLong()), BigInteger.valueOf(denominator.toLong())) constructor(numerator: BigInteger, denominator: BigInteger) { if (denominator == BigInteger.ZERO) throw IllegalArgumentException("Denominator cannot be zero") val sign = denominator.signum().toBigInteger() val signedNumerator = sign * numerator val signedDenominator = sign * denominator val gcd = signedNumerator.gcd(signedDenominator) this.numerator = signedNumerator.divide(gcd) this.denominator = signedDenominator.divide(gcd) } operator fun plus(that: Rational) = Rational( (this.numerator * that.denominator) + (that.numerator * this.denominator), this.denominator * that.denominator) operator fun minus(that: Rational) = plus(-that) operator fun times(that: Rational) = Rational(this.numerator * that.numerator, this.denominator * that.denominator) operator fun div(that: Rational) = Rational(this.numerator * that.denominator, this.denominator * that.numerator) operator fun unaryMinus() = Rational(-numerator, denominator) operator fun compareTo(that: Rational) : Int { return ((this.numerator * that.denominator) - (that.numerator * this.denominator)).signum() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Rational) return false return this.numerator == other.numerator && this.denominator == other.denominator } override fun toString() = if (denominator == BigInteger.ONE) "$numerator" else "$numerator/$denominator" operator fun rangeTo(that: Rational): RationalRange { return RationalRange(this, that) } override fun hashCode(): Int { var result = numerator.hashCode() result = 31 * result + denominator.hashCode() return result } class RationalRange(val startRational: Rational, val endRational: Rational) { operator fun contains(rational: Rational) = rational >= startRational && rational <= endRational } } infix fun <T : Number> T.divBy(denominator: T) = Rational(this, denominator) fun String.toRational() : Rational { fun String.toBigIntegerOrFail() = toBigIntegerOrNull() ?: throw IllegalArgumentException("${this@toRational} cannot be converted to a Rational") if (!contains("/")) return Rational(toBigIntegerOrFail()) val (elem1, elem2) = split("/") return Rational(elem1.toBigIntegerOrFail(), elem2.toBigIntegerOrFail()) } fun Int.toRational() = Rational(this) fun main() { "a/f".toRational() val half = 1 divBy 2 val third = 1 divBy 3 val sum: Rational = half + third println(5 divBy 6 == sum) val difference: Rational = half - third println(1 divBy 6 == difference) val product: Rational = half * third println(1 divBy 6 == product) val quotient: Rational = half / third println(3 divBy 2 == quotient) val negation: Rational = -half println(-1 divBy 2 == negation) println((2 divBy 1).toString() == "2") println((-2 divBy 4).toString() == "-1/2") println("117/1098".toRational().toString() == "13/122") val twoThirds = 2 divBy 3 println(half < twoThirds) println(half in third..twoThirds) println(3.toRational().toString() == "3") println(2000000000L divBy 4000000000L == 1 divBy 2) println("912016490186296920119201192141970416029".toBigInteger() divBy "1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2) }
[ { "class_path": "jihedamine__kotlin_coursera__61e7156/rationals/Rational$RationalRange.class", "javap": "Compiled from \"Rational.kt\"\npublic final class rationals.Rational$RationalRange {\n private final rationals.Rational startRational;\n\n private final rationals.Rational endRational;\n\n public rati...
E3FxGaming__ExtendedCYK-Algorithm__292026d/src/main/kotlin/org/example/e3fxgaming/wortproblem/ExtendedCYKAlgorithm.kt
package org.example.e3fxgaming.wortproblem fun main() { val fileContent = InputReader::class.java.getResource("/inputChomskyNF.txt")?.readText() ?: throw Exception("No rules found") val inputReader = InputReader(fileContent) val firstTestWord = "abaaba" val secondTestWord = "abbbba" val thirdTestWord = "bbabbbaabbaabbbabb" val falseWord = "aaabbbb" val solver = Solver(inputReader) println("$firstTestWord: ${solver.solve(firstTestWord)}") println("$secondTestWord: ${solver.solve(secondTestWord)}") println("$thirdTestWord: ${solver.solve(thirdTestWord)}") println("$falseWord: ${solver.solve(falseWord)}") println(inputReader) } /** * Class for reading the Chomsky NF input. Also holds the cache. */ class InputReader(fileContent: String) { //Maps second part of rule to all possible first parts private val rules = fileContent.split(System.getProperty("line.separator")) .map { it.split("->") } .map { Rule(it[0], it[1]) } val reversedRules = rules.groupBy { it.productionOutput } //caching rule wrappers to speed up subsequent same-word-evaluations val cache: MutableMap<String, DerivationWrapper> = mutableMapOf() override fun toString(): String { return "Read ${rules.size } rules. Current cache size: ${cache.size} entries." } } /** * An element of the production system, that can transform a [variable] into a [productionOutput] */ data class Rule(val variable: String, val productionOutput: String) { override fun toString(): String { return "$variable->$productionOutput" } } /** * Since the same [word] may be derived in multiple ways, this DerivationWrapper bundles the possible [derivations]. * Also stores information about its direct [left] and [right] DerivationWrapper descendants. * */ data class DerivationWrapper(val word: String, val derivations: List<DerivationOperation>, val left: DerivationWrapper?, val right: DerivationWrapper?) { fun getChild(childSelector: (DerivationWrapper) -> DerivationWrapper?, collectionList: MutableList<DerivationWrapper>): List<DerivationWrapper> { collectionList.add(this) childSelector(this)?.getChild(childSelector, collectionList) return collectionList } override fun toString(): String { return derivations.joinToString("\n") } } /** * Represents a single derivation A -> A B with [rule], where A ends at [firstSegmentEndsAtIndex]. */ data class DerivationOperation(val rule: Rule, val firstSegmentEndsAtIndex: Int) { override fun toString(): String { return "$rule ($firstSegmentEndsAtIndex)" } } /** * Wrapper class for solving word problems. * [inputReader] provides the grammar information. */ class Solver(private val inputReader: InputReader) { /** * Tests whether a [word] string belongs to the language of the provided grammar. */ fun solve(word: String): Boolean { val solutionPyramid: MutableList<List<DerivationWrapper>> = mutableListOf() //create foundation row of solutionPyramid word.map { wordChar -> val substring = wordChar.toString() inputReader.cache[substring]?.let { return@map it } val derivations = inputReader.reversedRules[substring]?.map { rule -> DerivationOperation(rule, 0) }.orEmpty() DerivationWrapper(substring, derivations, null, null).also { inputReader.cache[it.word] = it } }.let { firstRow -> solutionPyramid.add(firstRow) } //create top rows of solutionPyramid do { val lastRow = solutionPyramid.last() val combinationPairs = (0 until lastRow.lastIndex).map { indexFirstElement -> val leftDerivationWrapper = lastRow[indexFirstElement] val rightDerivationWrapper = lastRow[indexFirstElement + 1] val substring = word.substring(indexFirstElement, indexFirstElement + solutionPyramid.size + 1) combinePairs(leftDerivationWrapper, rightDerivationWrapper, substring) } solutionPyramid.add(combinationPairs) } while (solutionPyramid.last().size != 1) return solutionPyramid.last().first().derivations.any { it.rule.variable == "S" } } /** * Combines a [leftDerivationWrapper] and [rightDerivationWrapper] into a superior [DerivationWrapper] for a given [word] */ private fun combinePairs(leftDerivationWrapper: DerivationWrapper, rightDerivationWrapper: DerivationWrapper, word: String): DerivationWrapper { inputReader.cache[word]?.let { return it } val leftDerivationWrappers = leftDerivationWrapper.getChild({it.left}, mutableListOf()) val rightDerivationWrappers = rightDerivationWrapper.getChild({it.right}, mutableListOf()) if(leftDerivationWrappers.size != rightDerivationWrappers.size) throw Exception("DerivationWrapper not balanced") val pairs = leftDerivationWrappers.zip(rightDerivationWrappers.reversed()).filterNot { it.first.derivations.isEmpty() || it.second.derivations.isEmpty() } val derivationOperations = pairs.map { derivationWrappers -> val firstProductionInputs = derivationWrappers.first.derivations.map { it.rule.variable } val secondProductionInputs = derivationWrappers.second.derivations.map { it.rule.variable } val productionPairs = firstProductionInputs.toPairList(secondProductionInputs).map { it.joinToString(" ") } val applicableRules = productionPairs.mapNotNull { productionPair -> inputReader.reversedRules[productionPair] }.flatten() applicableRules.map { DerivationOperation(it, derivationWrappers.first.word.length) } }.flatten() return DerivationWrapper(word, derivationOperations, leftDerivationWrapper, rightDerivationWrapper).also { inputReader.cache[it.word] = it } } } /** * Creates the Cartesian product of the elements of this List and a different [otherList] List. */ private fun List<String>.toPairList(otherList: List<String>) = flatMap { aItem -> otherList.map { bItem -> listOf(aItem, bItem) } }
[ { "class_path": "E3FxGaming__ExtendedCYK-Algorithm__292026d/org/example/e3fxgaming/wortproblem/ExtendedCYKAlgorithmKt.class", "javap": "Compiled from \"ExtendedCYKAlgorithm.kt\"\npublic final class org.example.e3fxgaming.wortproblem.ExtendedCYKAlgorithmKt {\n public static final void main();\n Code:\n ...
HeerKirov__Hedge-v2__8140cd6/server/src/main/kotlin/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxTable.kt
package com.heerkirov.hedge.server.library.compiler.grammar.definintion import kotlin.math.max //语法分析表的定义,作用是和syntax-table.txt中的定义对应。 class SyntaxTable(internal val actionTable: Array<Array<Action?>>, internal val gotoTable: Array<Array<Int?>>, private val actionMap: Map<String, Int>, private val gotoMap: Map<String, Int>) { private val reflectActionMap by lazy { actionMap.asSequence().map { (k, v) -> v to k }.toMap() } val statusCount: Int get() = actionTable.size val actionNotations: Set<String> get() = actionMap.keys val gotoNotations: Set<String> get() = gotoMap.keys fun getAction(status: Int, terminalNotation: String): Action? { val i = actionMap[terminalNotation] ?: throw RuntimeException("Action $terminalNotation is not exist.") return actionTable[status][i] } fun getGoto(status: Int, nonTerminalNotation: String): Int? { val i = gotoMap[nonTerminalNotation] ?: throw RuntimeException("Goto $nonTerminalNotation is not exist.") return gotoTable[status][i] } fun getExpected(status: Int): List<String> { return actionTable[status].asSequence() .mapIndexed { i, action -> i to action } .filter { (_, action) -> action != null } .map { (i, _) -> reflectActionMap[i]!! } .toList() } } /** * ACTION的指令。 */ sealed class Action data class Shift(val status: Int) : Action() { override fun toString() = "Shift($status)" } data class Reduce(val syntaxExpressionIndex: Int) : Action() { override fun toString() = "Reduce($syntaxExpressionIndex)" } object Accept : Action() { override fun toString() = "Accept" } /** * 读取并生成语法分析表的定义。 */ fun readSyntaxTable(text: String): SyntaxTable { val lines = text.split("\n") .filter { it.isNotBlank() } .apply { if(isEmpty()) throw RuntimeException("Text of syntax table is empty.") } .map { it.split(Regex("\\s+")).filter { i -> i.isNotBlank() } } val head = lines.first().apply { if(isEmpty()) throw RuntimeException("Table head is empty.") } val terminalNum = head.first().toInt() val actionMap = head.subList(1, terminalNum + 1).asSequence().mapIndexed { i, s -> s to i }.toMap() val gotoMap = head.subList(terminalNum + 1, head.size).asSequence().mapIndexed { i, s -> s to i }.toMap() val (action, goto) = lines.subList(1, lines.size).asSequence().map { row -> val action = row.subList(1, terminalNum + 1).map { when { it == "_" -> null it == "acc" -> Accept it.startsWith("s") -> Shift(it.substring(1).toInt()) it.startsWith("r") -> Reduce(it.substring(1).toInt()) else -> throw RuntimeException("Unknown action '$it'.") } }.toTypedArray() val goto = row.subList(terminalNum + 1, row.size).map { if(it == "_") null else it.toInt() }.toTypedArray() Pair(action, goto) }.unzip() val actionTable = action.toTypedArray() val gotoTable = goto.toTypedArray() return SyntaxTable(actionTable, gotoTable, actionMap, gotoMap) } /** * 将语法分析表打印为文本定义。 */ fun printSyntaxTable(table: SyntaxTable): String { //将action和goto表to string val actionTable = table.actionTable.map { row -> row.map { action -> if(action == null) "_" else when (action) { is Shift -> "s${action.status}" is Reduce -> "r${action.syntaxExpressionIndex}" is Accept -> "acc" } } } val gotoTable = table.gotoTable.map { row -> row.map { goto -> goto?.toString() ?: "_" } } //取得首列、action列、goto列的宽度 val statusColWidth = max(table.statusCount.toString().length, table.actionNotations.size.toString().length) val actionColWidth = max(table.actionNotations.maxOf { it.length }, actionTable.flatten().maxOf { it.length }) val gotoColWidth = max(table.gotoNotations.maxOf { it.length }, gotoTable.flatten().maxOf { it.length }) val head = String.format("%-${statusColWidth}s %s %s", table.actionNotations.size, table.actionNotations.joinToString(" ") { String.format("%-${actionColWidth}s", it) }, table.gotoNotations.joinToString(" ") { String.format("%-${gotoColWidth}s", it) } ) val body = actionTable.zip(gotoTable).mapIndexed { i, (actionRow, gotoRow) -> String.format("%-${statusColWidth}s %s %s", i, actionRow.joinToString(" ") { String.format("%-${actionColWidth}s", it) }, gotoRow.joinToString(" ") { String.format("%-${gotoColWidth}s", it) } ) }.joinToString("\n") return "$head\n$body" }
[ { "class_path": "HeerKirov__Hedge-v2__8140cd6/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxTableKt.class", "javap": "Compiled from \"SyntaxTable.kt\"\npublic final class com.heerkirov.hedge.server.library.compiler.grammar.definintion.SyntaxTableKt {\n public static final com.heerki...
HeerKirov__Hedge-v2__8140cd6/server/src/main/kotlin/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxExpression.kt
package com.heerkirov.hedge.server.library.compiler.grammar.definintion //文法产生式的定义,作用是和syntax.txt中的定义对应。 /** * 被定义的文法产生式。 */ data class SyntaxExpression(val index: Int, val key: KeyNotation, val sequence: List<Notation>) /** * 文法产生式中的文法符号。 */ interface Notation /** * 终结符。 */ interface TerminalNotation : Notation /** * 用户定义的非终结符。 */ class KeyNotation private constructor(val key: String) : Notation { companion object { private val cache = HashMap<String, KeyNotation>() fun of(key: String): KeyNotation { return cache.computeIfAbsent(key) { KeyNotation(it) } } } override fun equals(other: Any?) = other === this || (other is KeyNotation && other.key == key) override fun hashCode() = key.hashCode() override fun toString() = key } /** * 用户定义的终结符。 */ class SyntaxNotation private constructor(val symbol: String) : TerminalNotation { companion object { private val cache = HashMap<String, SyntaxNotation>() fun of(symbol: String): SyntaxNotation { return cache.computeIfAbsent(symbol) { SyntaxNotation(it) } } } override fun equals(other: Any?) = other === this || (other is SyntaxNotation && other.symbol == symbol) override fun hashCode() = symbol.hashCode() override fun toString() = symbol } /** * 读取并生成原始的文法产生式定义。 * 原始文法定义没有序号,自动添加序号,从1开始。 */ fun readSyntaxExpression(text: String): List<SyntaxExpression> { val lines = text.split("\n") .asSequence().filter { it.isNotBlank() }.map { it.split(Regex("\\s+")) } .map { if(it.size < 2 || it[1] != "->") throw RuntimeException("Expression [${it.joinToString(" ")}] is incorrect.") it[0] to it.subList(2, it.size) }.toList() val nonTerminals = lines.asSequence().map { (left, _) -> left }.toSet() return lines.mapIndexed { i, (left, right) -> SyntaxExpression(i + 1, KeyNotation.of(left), right.map { if(it in nonTerminals) KeyNotation.of(it) else SyntaxNotation.of(it) }) } }
[ { "class_path": "HeerKirov__Hedge-v2__8140cd6/com/heerkirov/hedge/server/library/compiler/grammar/definintion/SyntaxExpression.class", "javap": "Compiled from \"SyntaxExpression.kt\"\npublic final class com.heerkirov.hedge.server.library.compiler.grammar.definintion.SyntaxExpression {\n private final int i...
nickaigi__kotlin-in-action__bc2a547/src/ch02/iterations.kt
package ch02 import java.util.* /* fizzbuzz: * - if any number is divisible by 3 = Fizz * - if any number is divisible by 5 = Buzz * - if number is divisible by both 3 and 5 = FizzBuzz */ fun fizzBuzz(i: Int) = when { i % 15 == 0 -> "FizzBuzz " i % 3 == 0 -> "Fizz " i % 5 == 0 -> "Buzz " else -> "$i " } fun exampleOne() { /* kotlin doesn't bring anything new to the 'while' and 'do while' loops * Kotlin has the 'for-each' loop */ var count = 1 while (count < 10) { println("count $count") count += 1 } do { println("count $count") count -= 1 } while (count > 0) } fun exampleTwo() { /* to define a range in kotlin, use the .. operator * start..stop * * stop is always part of the range * */ for (i in 1..100) { print(fizzBuzz(i)) } } fun exampleThree() { /* for loop with a step */ for (i in 100 downTo 1 step 2) { print(fizzBuzz(i)) } } fun exampleFour() { /* you can use 'until' * for (x in number until size) * * Key difference between 1..10 and 1 until 10 is that * * - 1..10 includes the stop number * - 1 until 10 does not include the stop number * * */ for (i in 1 until 30) { print(fizzBuzz(i)) } } fun exampleFive() { /* iterating over maps */ val binaryReps = TreeMap<Char, String>() /* the .. syntax for creating ranges works not only for numbers by for * characters as well */ for (c in 'A'..'F') { val binary = Integer.toBinaryString(c.toInt()) binaryReps[c] = binary } for ((letter, binary) in binaryReps) { println("$letter = $binary") } } fun exampleSix(){ val list = arrayListOf("10", "11", "1001") for ((index, element) in list.withIndex()) { println("$index: $element") } } fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z' fun isNotDigt(c: Char) = c !in '0'..'9' fun exampleSeven() { println(isLetter('q')) println(isNotDigt('x')) } fun recognize(c: Char): String { var s = when (c) { in '0'..'9' -> "It's a digit!" in 'a'..'z' -> "It's a lowercase letter!" in 'A'..'Z' -> "It's a uppercase letter!" else -> "I don't know ..." } return s } fun main(args: Array<String>) { println(recognize('Z')) }
[ { "class_path": "nickaigi__kotlin-in-action__bc2a547/ch02/IterationsKt.class", "javap": "Compiled from \"iterations.kt\"\npublic final class ch02.IterationsKt {\n public static final java.lang.String fizzBuzz(int);\n Code:\n 0: nop\n 1: iload_0\n 2: bipush 15\n 4: irem\n ...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/RpsSim.kt
package com.github.brpeterman.advent2022 class RpsSim { fun simulateAndScore(plays: List<Pair<String, String>>): Int { return plays.fold(0, { total, play -> total + scorePlay(play.first, toPlay(play.second)) }) } fun strategizeAndScore(plays: List<Pair<String, String>>): Int { return plays.fold(0, {total, play -> total + scorePlay(play.first, choosePlay(play.first, play.second)) }) } fun toPlay(play: String): String { return when (play) { ME_ROCK -> ROCK ME_PAPER -> PAPER ME_SCISSORS -> SCISSORS else -> throw IllegalStateException("Unexpected play: ${play}") } } fun choosePlay(opponent: String, outcome: String): String { if (outcome == WIN) { return when (opponent) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK else -> throw IllegalStateException("Unexpected move: ${opponent}") } } if (outcome == LOSE) { return when (opponent) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER else -> throw IllegalStateException("Unexpected move: ${opponent}") } } return opponent } fun scorePlay(opponent: String, me: String): Int { var score = SCORES[me]!! if (opponent == me) { score += 3 } else if ((opponent == ROCK && me == PAPER) || (opponent == PAPER && me == SCISSORS) || (opponent == SCISSORS && me == ROCK)) { score += 6 } return score } companion object { // I had these in nice typesafe enums and then part 2 showed up 😐 val ROCK = "A" val PAPER = "B" val SCISSORS = "C" val ME_ROCK = "X" val ME_PAPER = "Y" val ME_SCISSORS = "Z" val LOSE = "X" val WIN = "Z" val SCORES = mapOf( Pair(ROCK, 1), Pair(PAPER, 2), Pair(SCISSORS, 3)) fun parseInput(input: String): List<Pair<String, String>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val (left, right) = line.split(" ") Pair(left, right) } } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/RpsSim.class", "javap": "Compiled from \"RpsSim.kt\"\npublic final class com.github.brpeterman.advent2022.RpsSim {\n public static final com.github.brpeterman.advent2022.RpsSim$Companion Companion;\n\n private static final j...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/ForestSurvey.kt
package com.github.brpeterman.advent2022 class ForestSurvey(input: String) { data class Coords(val row: Int, val column: Int) data class TreeMap(val width: Int, val height: Int, val trees: Map<Coords, Int>) enum class Offset(val rowOffset: Int, val colOffset: Int) { NORTH(-1, 0), SOUTH(1, 0), WEST(0, -1), EAST(0, 1) } var map: TreeMap init { map = parseInput(input) } fun countVisible(): Int { return map.trees.keys .filter { isVisible(it) } .count() } fun findBestTree(): Int { return map.trees.keys .filter { it.row != 0 && it.row != map.height-1 && it.column != 0 && it.column != map.width-1 } .maxOf { scenicScore(it) } } fun isVisible(coords: Coords): Boolean { val height = map.trees[coords]!! return ((0..coords.row-1).all { map.trees[Coords(it, coords.column)]!! < height }) || (coords.row+1..map.height-1).all { map.trees[Coords(it, coords.column)]!! < height } || (0..coords.column-1).all { map.trees[Coords(coords.row, it)]!! < height } || (coords.column+1..map.width-1).all { map.trees[Coords(coords.row, it)]!! < height } } fun scenicScore(coords: Coords): Int { val height = map.trees[coords]!! val score = Offset.values() .map { offset -> var current = Coords(coords.row + offset.rowOffset, coords.column + offset.colOffset) var count = 1 while (map.trees[current] != null && map.trees[current]!! < height) { current = Coords(current.row + offset.rowOffset, current.column + offset.colOffset) if (map.trees[current] != null) { count++ } } count } .reduce { product, i -> product * i } return score } companion object { fun parseInput(input: String): TreeMap { val lines = input.split("\n") .filter { it.isNotBlank() } val height = lines.size val width = lines[0].length val trees = lines.withIndex() .fold(mutableMapOf<Coords, Int>()) { map, (lineIndex, line) -> line.toCharArray() .withIndex() .forEach { (charIndex, char) -> map[Coords(lineIndex, charIndex)] = char.toString().toInt() } map } return TreeMap(width, height, trees) } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/ForestSurvey$Offset.class", "javap": "Compiled from \"ForestSurvey.kt\"\npublic final class com.github.brpeterman.advent2022.ForestSurvey$Offset extends java.lang.Enum<com.github.brpeterman.advent2022.ForestSurvey$Offset> {\n ...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/KeepAway.kt
package com.github.brpeterman.advent2022 import java.util.LinkedList import java.util.SortedMap typealias ArithmeticOperation = (Long, Long) -> Long typealias MonkeyRule = (Long) -> KeepAway.ItemPass class KeepAway(input: String, worryDecay: Int) { data class Monkey(val holding: LinkedList<Long>, val rule: MonkeyRule, val divisor: Int, var inspectionCount: Int = 0) data class ItemPass(val to: Int, val worryLevel: Long) enum class Operation(val function: ArithmeticOperation) { ADD({ a, b -> a + b }), MULTIPLY({ a, b -> a * b }) } val monkeys = parseInput(input, worryDecay) val commonMultiple = calculateCommonMultiple(monkeys.values) fun calculateMonkeyBusiness(): Long { return monkeys.values.map { it.inspectionCount.toLong() } .sorted() .reversed() .subList(0, 2) .reduce { product, count -> product * count } } fun simulate(rounds: Int) { (0 until rounds).forEach { monkeys.values .forEach { monkey -> takeTurn(monkey) } } } fun takeTurn(monkey: Monkey) { while (monkey.holding.isNotEmpty()) { val item = monkey.holding.pop() val result = monkey.rule.invoke(item) monkeys[result.to]!!.holding.add(result.worryLevel) monkey.inspectionCount++ } } fun parseInput(input: String, worryDecay: Int): SortedMap<Int, Monkey> { return input.split("\n\n") .withIndex() .map { (index, monkeyDef) -> val lines = monkeyDef.split("\n") val startingItems = parseStartingItems(lines[1]) val (divisorStr) = """divisible by (\d+)""".toRegex() .find(lines[3])!! .destructured val divisor = divisorStr.toInt() val rule = parseRule(divisor, lines[2], lines[4], lines[5], worryDecay) index to Monkey(startingItems, rule, divisor) } .toMap() .toSortedMap() } fun parseStartingItems(line: String): LinkedList<Long> { return LinkedList(""" (\d+),?""".toRegex().findAll(line) .map { val (num) = it.destructured num.toLong() } .toList()) } fun calculateCommonMultiple(monkeys: Collection<Monkey>): Long { return monkeys.fold(1, { product, m -> product * m.divisor.toLong() }) } fun parseRule(divisor: Int, operationLine: String, trueLine: String, falseLine: String, worryDecay: Int): MonkeyRule { val (operator, operandStr) = """new = old ([+*]) (\d+|old)""".toRegex() .find(operationLine)!! .destructured val operatorFunction = when (operator) { "+" -> Operation.ADD "*" -> Operation.MULTIPLY else -> throw IllegalStateException("Unexpected operator: ${operator}") } val (trueMonkeyStr) = """monkey (\d+)""".toRegex() .find(trueLine)!! .destructured val (falseMonkeyStr) = """monkey (\d+)""".toRegex() .find(falseLine)!! .destructured val trueMonkey = trueMonkeyStr.toInt() val falseMonkey = falseMonkeyStr.toInt() return constructRuleFunction(operatorFunction, operandStr, divisor, trueMonkey, falseMonkey, worryDecay) } fun constructRuleFunction(operatorFunction: Operation, operandStr: String, divisor: Int, trueMonkey: Int, falseMonkey: Int, worryDecay: Int): MonkeyRule { return { old -> val operand = if (operandStr == "old") { old } else { operandStr.toLong() } var new = operatorFunction.function.invoke(old, operand) new = if (worryDecay > 1) { new / worryDecay } else { new % commonMultiple } if (new % divisor == 0L) { ItemPass(trueMonkey, new) } else { ItemPass(falseMonkey, new) } } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/KeepAway$Operation.class", "javap": "Compiled from \"KeepAway.kt\"\npublic final class com.github.brpeterman.advent2022.KeepAway$Operation extends java.lang.Enum<com.github.brpeterman.advent2022.KeepAway$Operation> {\n privat...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/CrateCrane.kt
package com.github.brpeterman.advent2022 import java.util.* class CrateCrane { data class CrateState(val stacks: MutableMap<Int, LinkedList<Char>>, val moves: List<CrateMove>) data class CrateMove(val count: Int, val from: Int, val to: Int) fun reportStacks(stacks: List<LinkedList<Char>>): String { return stacks.fold("") { output, stack -> output + stack.peek().toString() } } enum class CraneMode { DEFAULT, HOLD_MULTIPLE } fun simulate(state: CrateState, mode: CraneMode = CraneMode.DEFAULT): List<LinkedList<Char>> { val stacks = state.stacks val moves = state.moves moves.forEach { move -> val from = stacks[move.from]!! val to = stacks[move.to]!! val holding = mutableListOf<Char>() (1..move.count).forEach { holding.add(from.pop()) } if (mode == CraneMode.HOLD_MULTIPLE) { holding.reverse() } holding.forEach { crate -> to.push(crate) } } return stacks.entries .sortedBy { it.key } .map { it.value } } companion object { fun parseInput(input: String): CrateState { val (stateInput, movesInput) = input.split("\n\n") val stacks = stateInput.split("\n") .filter { it.matches(""" *\[.*""".toRegex()) } .fold(mutableMapOf<Int, LinkedList<Char>>().withDefault { LinkedList() }) { stacks, line -> line.chunked(4) .withIndex() .forEach { (index, crate) -> val matches = """\[([A-Z])] ?""".toRegex().matchEntire(crate) if (matches != null) { val stack = stacks.getValue(index + 1) val (crateName) = matches.destructured stack.add(crateName[0]) stacks[index + 1] = stack } } stacks } val moves = movesInput.split("\n") .filter { it.isNotBlank() } .map { line -> val matches = """move (\d+) from (\d+) to (\d+)""".toRegex().matchEntire(line) val (count, from, to) = matches!!.destructured CrateMove(count.toInt(), from.toInt(), to.toInt()) } return CrateState(stacks, moves) } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/CrateCrane$CraneMode.class", "javap": "Compiled from \"CrateCrane.kt\"\npublic final class com.github.brpeterman.advent2022.CrateCrane$CraneMode extends java.lang.Enum<com.github.brpeterman.advent2022.CrateCrane$CraneMode> {\n...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/HillClimber.kt
package com.github.brpeterman.advent2022 import java.util.LinkedList class HillClimber(input: String) { data class HeightMap(val startPos: Coords, val endPos: Coords, val elevations: Map<Coords, Int>) data class Coords(val row: Int, val col: Int) { operator fun plus(other: Coords): Coords { return Coords(row + other.row, col + other.col) } } val map = parseInput(input) fun climb(): Int { return climbFrom(map.startPos)!! } fun findBestTrail(): Int { return map.elevations.filter { it.value == 1 } .map { climbFrom(it.key) } .filter { it != null } .map { it!! } .min() } fun climbFrom(start: Coords): Int? { var current = start val toVisit = LinkedList(getNeighbors(current)) val bestPathLength = mutableMapOf(current to 0) toVisit.forEach { bestPathLength[it] = 1 } while (toVisit.isNotEmpty()) { current = toVisit.pop() val pathLength = bestPathLength[current]!! val neighbors = getNeighbors(current) neighbors.forEach { neighbor -> if (bestPathLength[neighbor] == null || bestPathLength[neighbor]!! > pathLength + 1) { bestPathLength[neighbor] = pathLength + 1 toVisit.add(neighbor) } } } return bestPathLength[map.endPos] } fun getNeighbors(location: Coords): List<Coords> { return listOf( Coords(location.row - 1, location.col), Coords(location.row + 1, location.col), Coords(location.row, location.col - 1), Coords(location.row, location.col + 1)) .filter { neighbor -> map.elevations[neighbor] != null && (map.elevations[neighbor]!! - map.elevations[location]!! <= 1) } } companion object { fun parseInput(input: String): HeightMap { val map = HashMap<Coords, Int>() var startPos = Coords(0, 0) var endPos = Coords(0, 0) input.split("\n") .filter { it.isNotBlank() } .withIndex() .forEach { (row, line) -> line.toCharArray() .withIndex() .forEach { (column, char) -> val elevation = when (char) { 'S' -> { startPos = Coords(row, column) 1 } 'E' -> { endPos = Coords(row, column) 26 } else -> char.code - 96 } map[Coords(row, column)] = elevation } } return HeightMap(startPos, endPos, map) } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/HillClimber$Companion.class", "javap": "Compiled from \"HillClimber.kt\"\npublic final class com.github.brpeterman.advent2022.HillClimber$Companion {\n private com.github.brpeterman.advent2022.HillClimber$Companion();\n Co...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/RopeSnake.kt
package com.github.brpeterman.advent2022 class RopeSnake { data class Coords(val row: Int, val column: Int) { operator fun plus(other: Coords): Coords { return Coords(row + other.row, column + other.column) } } enum class Direction(val offset: Coords) { UP(Coords(-1, 0)), DOWN(Coords(1, 0)), LEFT(Coords(0, -1)), RIGHT(Coords(0, 1)) } fun simulateAndCount(steps: List<Pair<Direction, Int>>, tailCount: Int = 1): Int { val visited = mutableSetOf(Coords(0, 0)) var head = Coords(0, 0) val tails = (1..tailCount).fold(ArrayList<Coords>()) { list, _ -> list.add(Coords(0, 0)) list } steps.forEach { (direction, count) -> (1..count).forEach { head = head + direction.offset tails.withIndex().forEach { (index, tail) -> val leader = if (index == 0) { head } else { tails[index - 1] } if (!isAdjacent(tail, leader)) { val newTail = moveTo(tail, leader) tails[index] = newTail if (index == tailCount - 1) { visited.add(newTail) } } } } } return visited.size } fun isAdjacent(tail: Coords, head: Coords): Boolean { return listOf(Coords(0, 0), Direction.UP.offset, Direction.DOWN.offset, Direction.LEFT.offset, Direction.RIGHT.offset, Direction.UP.offset + Direction.LEFT.offset, Direction.UP.offset + Direction.RIGHT.offset, Direction.DOWN.offset + Direction.LEFT.offset, Direction.DOWN.offset + Direction.RIGHT.offset) .any { head + it == tail } } fun moveTo(tail: Coords, head: Coords): Coords { val rowOffset = if (tail.row == head.row) { 0 } else { (head.row - tail.row) / Math.abs(head.row - tail.row) } val colOffset = if (tail.column == head.column) { 0 } else { (head.column - tail.column) / Math.abs(head.column - tail.column) } return Coords(tail.row + rowOffset, tail.column + colOffset) } companion object { fun parseInput(input: String): List<Pair<Direction, Int>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val (dir, count) = line.split(" ") val direction = when (dir) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> throw IllegalStateException("Unexpected direction: ${dir}") } Pair(direction, count.toInt()) } } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/RopeSnake$Coords.class", "javap": "Compiled from \"RopeSnake.kt\"\npublic final class com.github.brpeterman.advent2022.RopeSnake$Coords {\n private final int row;\n\n private final int column;\n\n public com.github.brpeterm...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/DirTree.kt
package com.github.brpeterman.advent2022 class DirTree(input: String, val root: Folder = Folder("")) { init { constructTree(parseInput(input)) } data class Folder(val name: String, val parent: Folder? = null, val children: MutableMap<String, Folder> = mutableMapOf(), val files: MutableMap<String, Int> = mutableMapOf()) fun sumSmallDirs(threshold: Int = 100000): Int { val index = mutableMapOf<String, Int>() dirSize(root, index) return index.values .filter { it <= threshold } .sum() } fun findThresholdDir(totalSpace: Int = 70000000, requiredSpace: Int = 30000000): Int { val index = mutableMapOf<String, Int>() dirSize(root, index) val usedSpace = index[""]!! return index.values.sorted() .first { totalSpace - usedSpace + it >= requiredSpace } } fun dirSize(dir: Folder, index: MutableMap<String, Int> = mutableMapOf()): Int { val count = dir.files.values.sum() + dir.children.values.map { dirSize(it, index) }.sum() index[dir.name] = count return count } fun constructTree(lines: List<String>) { var workingDir = root var index = 0 while (index < lines.size - 1) { val line = lines[index] val tokens = line.split(" ") val cmd = tokens[1] when (cmd) { "cd" -> { val dir = tokens[2] workingDir = when (dir) { "/" -> root ".." -> workingDir.parent!! else -> workingDir.children[dir]!! } index++ } "ls" -> { var outputIndex = index + 1 while (lines[outputIndex].isNotBlank() && !lines[outputIndex].startsWith('$')) { val outputLine = lines[outputIndex] val outputTokens = outputLine.split(" ") when (outputTokens[0]) { "dir" -> workingDir.children.put(outputTokens[1], Folder("${workingDir.name}/${outputTokens[1]}", workingDir)) else -> workingDir.files.put(outputTokens[1], outputTokens[0].toInt()) } outputIndex++ } index = outputIndex } } } } companion object { fun parseInput(input: String): List<String> { return input.split("\n") } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/DirTree.class", "javap": "Compiled from \"DirTree.kt\"\npublic final class com.github.brpeterman.advent2022.DirTree {\n public static final com.github.brpeterman.advent2022.DirTree$Companion Companion;\n\n private final com....
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/CampSections.kt
package com.github.brpeterman.advent2022 class CampSections { fun countOverlaps(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.fold(0, { total, assignment -> if ((assignment.second.contains(assignment.first.first)) || (assignment.second.contains(assignment.first.endInclusive))) { total + 1 } else { total } }) } fun countRedundancies(assignments: List<Pair<IntRange, IntRange>>): Int { return assignments.fold(0, { total, assignment -> if ((assignment.second.contains(assignment.first.start)) && (assignment.second.contains(assignment.first.endInclusive))) { total + 1 } else { total } }) } companion object { fun parseInput(input: String): List<Pair<IntRange, IntRange>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val ranges = line.split(",") .map { section -> val (start, end) = section.split("-") start.toInt()..end.toInt() } .sortedBy { it.endInclusive - it.start } Pair(ranges[0], ranges[1]) } } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/CampSections.class", "javap": "Compiled from \"CampSections.kt\"\npublic final class com.github.brpeterman.advent2022.CampSections {\n public static final com.github.brpeterman.advent2022.CampSections$Companion Companion;\n\n...
brpeterman__advent2022__1407ca8/src/main/kotlin/com/github/brpeterman/advent2022/Rucksacks.kt
package com.github.brpeterman.advent2022 class Rucksacks { fun scoreMisfits(rucksacks: List<Pair<Set<String>, Set<String>>>): Int { return rucksacks.fold(0) { total, sack -> val misfit = sack.first.intersect(sack.second).first() total + score(misfit) } } fun scoreBadges(rucksacks: List<Pair<Set<String>, Set<String>>>): Int { return rucksacks.chunked(3) .fold(0) { total, group -> val badge = unify(group[0]) .intersect(unify(group[1])) .intersect(unify(group[2])) .first() total + score(badge) } } fun unify(rucksack: Pair<Set<String>, Set<String>>): Set<String> { return rucksack.first + rucksack.second } fun score(item: String): Int { if (item.matches("[a-z]".toRegex())) { return item[0].code - 96 } else if (item.matches("[A-Z]".toRegex())) { return item[0].code - 38 } return 0 } companion object { fun parseInput(input: String): List<Pair<Set<String>, Set<String>>> { return input.split("\n") .filter { it.isNotBlank() } .map { line -> val left = line.substring(0, (line.length/2)) val right = line.substring(line.length/2) Pair( left.split("").filter {it.isNotBlank()}.toSet(), right.split("").filter {it.isNotBlank()}.toSet()) } } } }
[ { "class_path": "brpeterman__advent2022__1407ca8/com/github/brpeterman/advent2022/Rucksacks$Companion.class", "javap": "Compiled from \"Rucksacks.kt\"\npublic final class com.github.brpeterman.advent2022.Rucksacks$Companion {\n private com.github.brpeterman.advent2022.Rucksacks$Companion();\n Code:\n ...
Lazalatin__advent-of-code-2020__816e0e0/src/main/kotlin/de/bitfroest/aoc2020/Day01.kt
package de.bitfroest.aoc2020 object Day01 { private fun Pair<Int, Int>.sum() = first + second private fun Pair<Int, Int>.product() = first * second private fun List<Int>.toPairs(): Sequence<Pair<Int, Int>> { return this.asSequence().flatMapIndexed { i, first -> this.drop(i).map { second -> Pair(first, second) } } } fun solve(inputs: List<String>): Int { val numericInputs = inputs.map(String::toInt) return numericInputs.toPairs() .filter { it.sum() == 2020 } .first().product() } // --- Second Task private fun Triple<Int, Int, Int>.sum() = first + second + third private fun Triple<Int, Int, Int>.product() = first * second * third private fun List<Int>.toTriples(): Sequence<Triple<Int, Int, Int>> { return this.asSequence().flatMapIndexed() { i, first -> this.drop(i).flatMapIndexed { j, second -> this.drop(j).map { third -> Triple(first, second, third) } } } } fun solve2(inputs: List<String>): Int { val numericInputs = inputs.map(String::toInt) return numericInputs.toTriples() .filter { it.sum() == 2020 } .first().product() } }
[ { "class_path": "Lazalatin__advent-of-code-2020__816e0e0/de/bitfroest/aoc2020/Day01.class", "javap": "Compiled from \"Day01.kt\"\npublic final class de.bitfroest.aoc2020.Day01 {\n public static final de.bitfroest.aoc2020.Day01 INSTANCE;\n\n private de.bitfroest.aoc2020.Day01();\n Code:\n 0: aload...
dremme__coding-kotlin__1bdd663/src/main/algorithms/Quicksort.kt
package algorithms /** * Sorts the array using quicksort. Elements must be greater than zero. */ fun IntArray.quicksort() { require(all { it > 0 }) quicksort(0, size - 1) } /** * Quicksort algorithm picking the highest element as pivot, * so elements are only shifted to the right if they are */ private fun IntArray.quicksort(from: Int, to: Int) { if (from < to) { val pivot = this[to] var index = from (from..to).forEach { if (this[it] < pivot) swap(index++, it) } swap(index, to) quicksort(from, index - 1) quicksort(index + 1, to) } } private fun IntArray.swap(a: Int, b: Int) { val temp = this[a] this[a] = this[b] this[b] = temp }
[ { "class_path": "dremme__coding-kotlin__1bdd663/algorithms/QuicksortKt.class", "javap": "Compiled from \"Quicksort.kt\"\npublic final class algorithms.QuicksortKt {\n public static final void quicksort(int[]);\n Code:\n 0: aload_0\n 1: ldc #9 // String <this>\n ...
dremme__coding-kotlin__1bdd663/src/main/arrays/SpecialNumbers.kt
package arrays /** * Finds the minimum and maximum values. Elements can be any integer. * * @return a tuple of `(min, max)` or `null` if the array is empty. */ fun IntArray.findMinMaxNumbers(): Pair<Int, Int>? { if (isEmpty()) return null var min = Int.MAX_VALUE var max = Int.MIN_VALUE forEach { min = if (min > it) it else min max = if (max < it) it else max } return min to max } /** * Finds all prime numbers. Elements are greater than zero. * * @return an array of prime numbers. */ fun IntArray.findPrimeNumbers(): IntArray { require(all { it > 0 }) var primeArray = intArrayOf() forEach { if (it.isPrime()) primeArray += it } return primeArray } /** * Almost any halfway efficient prime algorithm is acceptable here, but the steps required should not exceed the square * root of the number. */ private fun Int.isPrime(): Boolean { if (this == 1) return false (2..sqrt()).forEach { if (this % it == 0) return false } return true } /** * Square root rounded to the nearest lower integer. */ private fun Int.sqrt() = Math.sqrt(toDouble()).toInt() /** * Determines the deepness of an array of arrays. A flat array (even if empty) has a deepness of `1`. */ fun Array<*>.deepness(): Int { return map { if (it is Array<*>) 1 + it.deepness() else 1 }.max() ?: 1 }
[ { "class_path": "dremme__coding-kotlin__1bdd663/arrays/SpecialNumbersKt.class", "javap": "Compiled from \"SpecialNumbers.kt\"\npublic final class arrays.SpecialNumbersKt {\n public static final kotlin.Pair<java.lang.Integer, java.lang.Integer> findMinMaxNumbers(int[]);\n Code:\n 0: aload_0\n ...
alexiscrack3__algorithms-kotlin__a201986/src/main/kotlin/search/BinarySearch.kt
package search class BinarySearch { fun binarySearch(arr: IntArray, l: Int, r: Int, key: Int): Int { if (r < l) return -1 val mid = (l + r) / 2 if (key == arr[mid]) { return mid } return if (key > arr[mid]) { binarySearch(arr, mid + 1, r, key) } else { binarySearch(arr, l, mid - 1, key) } } fun pivotedBinarySearch(array: IntArray, n: Int, value: Int): Int { val pivot = findPivot(array, 0, n - 1) // If we didn't find a pivot, then // array is not rotated at all if (pivot == -1) { return binarySearch(array, 0, n - 1, value) } // If we found a pivot, then first // compare with pivot and then // search in two subarrays around pivot if (array[pivot] == value) { return pivot } return if (array[0] <= value) { binarySearch(array, 0, pivot - 1, value) } else { binarySearch(array, pivot + 1, n - 1, value) } } /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */ fun findPivot(arr: IntArray, l: Int, r: Int): Int { // base cases if (r < l) { return -1 } if (r == l) { return l } /* low + (high - low)/2; */ val mid = (l + r) / 2 if (mid < r && arr[mid] > arr[mid + 1]) { return mid } if (mid > l && arr[mid] < arr[mid - 1]) { return mid - 1 } return if (arr[l] >= arr[mid]) { findPivot(arr, l, mid - 1) } else { findPivot(arr, mid + 1, r) } } }
[ { "class_path": "alexiscrack3__algorithms-kotlin__a201986/search/BinarySearch.class", "javap": "Compiled from \"BinarySearch.kt\"\npublic final class search.BinarySearch {\n public search.BinarySearch();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\...
techstay__kotlin-study__822a02c/kotlin-samples/src/yitian/study/skilled/collections.kt
package yitian.study.skilled fun main(args: Array<String>) { //获取订单数最多的顾客 val customerOfMaxOrder = orders().groupBy { it.customer } .maxBy { it.value.size } ?.key println("获取订单数最多的顾客:$customerOfMaxOrder") //获取订单金额最多的顾客 val customerOfMaxOrderPrice = orders().groupBy { it.customer } .maxBy { it.value.sumByDouble { it.products.sumByDouble { it.price } } } ?.key println("获取订单金额最多的顾客:$customerOfMaxOrderPrice") //价格最贵的商品 val mostExpensiveProduct = products().maxBy { it.price } println("价格最贵的商品:$mostExpensiveProduct") //计算机类的所有商品 val productsOfComputer = products().filter { it.category == Category.Computer } println("计算机类的所有商品:$productsOfComputer") //最便宜的三件商品 val productsOfCheapestThree = products().sortedBy { it.price } .filterIndexed({ index, _ -> index < 3 }) println("最便宜的三件商品:$productsOfCheapestThree") //每个顾客购买的商品列表 val productsOfCustomers = orders().groupBy { it.customer } .map { it.value.map { it.products }.flatten() } //每位顾客都购买了的商品 val productsOfEveryCustomer = productsOfCustomers.fold(products(), { result, products -> result.intersect(products).toList() }) println("每位顾客都购买了的商品:$productsOfEveryCustomer") } data class Product(val name: String, val price: Double, val category: Category) data class City(val name: String) data class Customer(val name: String, val city: City) { override fun toString(): String { return "Customer(name=$name, city=$city)" } } data class Order(val products: List<Product>, val customer: Customer) enum class Category { Computer, Education, Game } fun cities(): List<City> { return listOf(City("呼和浩特") , City("北京") , City("上海") , City("天津") , City("武汉")) } fun products(): List<Product> { return listOf(Product("Intel Core i7-7700k", 2799.00, Category.Computer), Product("AMD Ryzen 7 1700", 2499.0, Category.Computer), Product("Counter Strike", 10.0, Category.Game), Product("Batman", 79.0, Category.Game), Product("Thinking in Java", 59.0, Category.Education), Product("C# Programming", 99.0, Category.Education) ) } fun customers(): List<Customer> { return listOf(Customer("易天", cities()[0]) , Customer("张三", cities()[1]) , Customer("李四", cities()[2]) , Customer("沪生", cities()[3]) , Customer("王五", cities()[4])) } fun orders(): List<Order> { return listOf(Order(products().subList(0, 3), customers()[0]) , Order(products().subList(3, products().size), customers()[0]) , Order(products().subList(1, 3), customers()[1]) , Order(products().subList(2, 4), customers()[2]) , Order(products().subList(0, 4), customers()[3]) , Order(products().subList(1, 5), customers()[4]) ) }
[ { "class_path": "techstay__kotlin-study__822a02c/yitian/study/skilled/CollectionsKt$main$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class yitian.study.skilled.CollectionsKt$main$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public yitian.study.skilled....
ariannysOronoz__tutorialKotlin__a779f54/CombinacionesPalabras/src/main/java/Main.kt
package com.includehelp.basic import java.util.* /* fun main(args: Array<String>) { val num = 10 var i = 1 var factorial: Long = 1 while (i <= num) { factorial *= i.toLong() i++ } println(" El Factorial de $num = $factorial") }*/ // Kotlin program for // Print all permutations of a string class Permutation { // Swapping two string elements by index fun swap( info: String, size: Int, a: Int, b: Int ): String { var text = info; // Check valid location of swap element if ((a >= 0 && a < size) && (b >= 0 && b < size)) { // Get first character val first: Char = text.get(a); // Get second character val second: Char = text.get(b); // Put character text = text.substring(0, b) + first.toString() + text.substring(b + 1); text = text.substring(0, a) + second.toString() + text.substring(a + 1); } return text; } // Method which is print all permutations of given string fun findPermutation(info: String, n: Int, size: Int): Unit { if (n > size) { return; } if (n == size) { println(info); return; } var text = info; var i: Int = n; while (i < size) { // Swap the element text = this.swap(text, size, i, n); this.findPermutation(text, n + 1, size); // Swap the element text = this.swap(text, size, i, n); i += 1; } } } fun main(args: Array < String > ): Unit { val task: Permutation = Permutation(); var text: String = "CARACOL"; var size: Int = text.length; task.findPermutation(text, 0, size); println(""); text = "caracol"; size = text.length; task.findPermutation(text, 0, size); }
[ { "class_path": "ariannysOronoz__tutorialKotlin__a779f54/com/includehelp/basic/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class com.includehelp.basic.MainKt {\n public static final void main(java.lang.String[]);\n Code:\n 0: aload_0\n 1: ldc #9 ...
zebalu__advent2020__ca54c64/day_07/src/main/kotlin/io/github/zebalu/advent2020/BagRuleReader.kt
package io.github.zebalu.advent2020 typealias Rules = Map<String, Set<Pair<Int, String>>> object BagRuleReader { fun readRules(lines: List<String>): Rules { val result = mutableMapOf<String, MutableSet<Pair<Int, String>>>() lines.forEach { line -> val parts = line.split(" bags contain ") val type = parts[0] parts[1].split(", ").map { s -> s.split(" bag")[0] }.forEach { bag -> val split = bag.split(" ") if (split.size != 2 && split.size != 3) { throw IllegalStateException("split is not 2 or 3 long: " + split) } val count = if ("no".equals(split[0])) 0 else split[0].toInt() val bagName = if (count == 0) "no other" else split[1] + " " + split[2] result.computeIfAbsent(type, { _ -> mutableSetOf<Pair<Int, String>>() }).add(Pair(count, bagName)) } } return result } fun countWaysToShinyGold(rules: Map<String, Set<Pair<Int, String>>>) = rules.keys.count { name -> (!("shiny gold".equals(name))) && isThereWayToShinyGold( name, rules, setOf(name) ) } fun countContentInShinyGold(rules: Rules) = countContent("shiny gold", rules) private fun countContent(name: String, rules: Rules): Int { return rules.get(name)?.map { pair -> pair.first + pair.first * countContent(pair.second, rules) }?.sum() ?: 0 } private fun isThereWayToShinyGold(name: String, rules: Rules, visited: Set<String>): Boolean { if ("shiny gold".equals(name)) { return true } val col = rules.get(name)?.map { pair -> if (pair.first == 0) false else if ("shiny gold".equals(pair.second)) true else if (visited.contains(pair.second)) false else isThereWayToShinyGold( pair.second, rules, visited + pair.second ) } return if (col == null || col.isEmpty()) false else col.reduce { acc, next -> acc || next } } }
[ { "class_path": "zebalu__advent2020__ca54c64/io/github/zebalu/advent2020/BagRuleReader.class", "javap": "Compiled from \"BagRuleReader.kt\"\npublic final class io.github.zebalu.advent2020.BagRuleReader {\n public static final io.github.zebalu.advent2020.BagRuleReader INSTANCE;\n\n private io.github.zebalu...
zebalu__advent2020__ca54c64/day_13/src/main/kotlin/io/github/zebalu/advent2020/IdealTimeFinder.kt
package io.github.zebalu.advent2020 import java.math.BigInteger object IdealTimeFinder { fun findTime2(buses: List<Pair<Int, Int>>): Long = longBuses(buses) .fold(Pair(0L, 1L)) { acc, next -> applyBus(acc.first, acc.second, next.first, next.second) }.first private fun applyBus(sum: Long, interval: Long, bus: Long, timeDif: Long) = Pair(findTimeWithRightDiff(sum, interval, timeDif, bus), interval * bus) private tailrec fun findTimeWithRightDiff(start: Long, interval: Long, expected: Long, bus: Long): Long = if ((start + expected) % bus == 0L) start else findTimeWithRightDiff(start + interval, interval, expected, bus) private fun longBuses(buses: List<Pair<Int, Int>>) = buses.map { Pair(it.first.toLong(), it.second.toLong()) } fun findTime(buses: List<Pair<Long, Long>>): Long { return chineseRemainder(buses) } /* returns x where (a * x) % b == 1 */ fun multInv(a: Long, b: Long): Long { if (b == 1L) return 1L var aa = a var bb = b var x0 = 0L var x1 = 1L while (aa > 1) { x0 = (x1 - (aa / bb) * x0).also { x1 = x0 } bb = (aa % bb).also { aa = bb } } if (x1 < 0) x1 += b return x1 } fun chineseRemainder(buses: List<Pair<Long, Long>>): Long { val prod = buses.map { it.first }.fold(1L) { acc, i -> acc * i } var sum = 0L for (i in buses.indices) { val p = prod / buses[i].first sum += buses[i].second * multInv(p, buses[i].first) * p } return sum % prod } }
[ { "class_path": "zebalu__advent2020__ca54c64/io/github/zebalu/advent2020/IdealTimeFinder.class", "javap": "Compiled from \"IdealTimeFinder.kt\"\npublic final class io.github.zebalu.advent2020.IdealTimeFinder {\n public static final io.github.zebalu.advent2020.IdealTimeFinder INSTANCE;\n\n private io.githu...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/oct_challenge2021/Trie.kt
package oct_challenge2021 fun main() { val trie = Trie() trie.insert("apple") val res1 = trie.search("apple") assert(res1) val res2 = trie.search("app") assert(!res2) val res3 = trie.startsWith("app") assert(res3) trie.insert("app") val res4 = trie.search("app") assert(res4) } class Trie { private val root: TrieNode? = TrieNode() fun insert(word: String) { var node = root for (currChar in word) { if (!node!!.containsKey(currChar)) { node.put(currChar, TrieNode()) } node = node.get(currChar) } node!!.isEnd = true } fun search(word: String): Boolean { val node = searchPrefix(word) return node != null && node.isEnd } fun startsWith(prefix: String): Boolean { val node = searchPrefix(prefix) return node != null } private fun searchPrefix(word: String): TrieNode? { var node = root for (currChar in word) { if (node!!.containsKey(currChar)) { node = node.get(currChar) } else { return null } } return node } } private class TrieNode { private val numberOfAlphabet = 26 private var links: Array<TrieNode?> = arrayOfNulls(numberOfAlphabet) var isEnd = false fun containsKey(char: Char): Boolean { return links[char - 'a'] != null } fun get(char: Char): TrieNode? { return links[char - 'a'] } fun put(char: Char, node: TrieNode) { links[char - 'a'] = node } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/oct_challenge2021/Trie.class", "javap": "Compiled from \"Trie.kt\"\npublic final class oct_challenge2021.Trie {\n private final oct_challenge2021.TrieNode root;\n\n public oct_challenge2021.Trie();\n Code:\n 0: aload_0\n 1: invokespecial ...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/oct_challenge2021/LongestCommonSubsequence.kt
package oct_challenge2021 fun main() { assert(longestCommonSubsequence("abcde", "ace") == 3) assert(longestCommonSubsequence("abc", "def") == 0) assert(longestCommonSubsequence("abc", "abc") == 2) val res = longestCommonSubsequence("abc", "abc") println(res) } fun longestCommonSubsequence(text1: String, text2: String): Int { val memo: Array<Array<Int>> = Array(text1.length) {Array(text2.length) {-1} } return getMax(text1, text2, 0, 0, memo) } private fun getMax(text1: String, text2: String, index1: Int, index2: Int, memo: Array<Array<Int>>): Int { if (index1 == text1.length || index2 == text2.length) return 0 if (memo[index1][index2] != -1) return memo[index1][index2] val char1: Char = text1[index1] val char2: Char = text2[index2] val result = when (char1) { char2 -> { getMax(text1, text2, index1 + 1, index2 + 1, memo) + 1 } else -> { val res1 = getMax(text1, text2, index1, index2 + 1, memo) val res2 = getMax(text1, text2, index1 + 1, index2, memo) maxOf(res1, res2) } } memo[index1][index2] = result return result }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/oct_challenge2021/LongestCommonSubsequenceKt.class", "javap": "Compiled from \"LongestCommonSubsequence.kt\"\npublic final class oct_challenge2021.LongestCommonSubsequenceKt {\n public static final void main();\n Code:\n 0: ldc #8 ...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/oct_challenge2021/IslandPerimeter.kt
package oct_challenge2021 fun main() { val grid = arrayOf( intArrayOf(0, 1, 0, 0), intArrayOf(1, 1, 1, 0), intArrayOf(0, 1, 0, 0), intArrayOf(1, 1, 0, 0), ) val result = Solution().islandPerimeter(grid) assert(result == 16) println(result) } class Solution { private lateinit var grid: Array<IntArray> private lateinit var visited: Array<IntArray> private val dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) private var result: Int = 0 fun islandPerimeter(grid: Array<IntArray>): Int { this.grid = grid this.visited = Array(grid.size) { IntArray(grid[0].size) { 0 } } for (i in grid.indices) { for (j in grid[0].indices) { if (grid[i][j] == 1 && visited[i][j] == 0) { traverse(i, j) return result } } } return result } private fun traverse(i: Int, j: Int) { val m = grid.size val n = grid[0].size visited[i][j] = 1 for (dir in dirs) { val newI = i + dir[0] val newJ = j + dir[1] val canTraverse = newI in 0 until m && newJ in 0 until n && grid[newI][newJ] == 1 when { canTraverse -> { if (visited[newI][newJ] == 0) traverse(newI, newJ) } else -> { result++ } } } } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/oct_challenge2021/IslandPerimeterKt.class", "javap": "Compiled from \"IslandPerimeter.kt\"\npublic final class oct_challenge2021.IslandPerimeterKt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: anewarray #8 ...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/bk70/Problem3.kt
package bk70 import java.util.* // [[0,2,0]] // [2,2] // [0,1] // 1 fun main() { val res = Problem3().highestRankedKItems( arrayOf( intArrayOf(0, 2, 0), ), intArrayOf(2, 2), intArrayOf(0, 1), 1 ) println(res) } class Problem3 { private lateinit var grid: Array<IntArray> private lateinit var pricing: IntArray private var visitedPoints = mutableListOf<Point>() fun highestRankedKItems(grid: Array<IntArray>, pricing: IntArray, start: IntArray, k: Int): List<List<Int>> { this.grid = grid this.pricing = pricing bfs(start[0], start[1]) return visitedPoints .filter { it.`val` != 1 && it.`val` >= pricing[0] && it.`val` <= pricing[1] } .sortedWith( compareBy<Point> { it.dist } .thenBy { it.`val` } .thenBy { it.x } .thenBy { it.y } ) .map { listOf(it.x, it.y) } .take(k) } private fun bfs(i: Int, j: Int) { val queue: Queue<Point> = LinkedList<Point>() val visited = Array(grid.size) { BooleanArray( grid[0].size ) } val directions = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) val first = Point(i, j, 0, grid[i][j]) queue.add(first) visitedPoints.add(first) visited[first.x][first.y] = true var distance = 0 while (!queue.isEmpty()) { distance++ val size = queue.size for (i in 0 until size) { val curr: Point = queue.poll() for (direction in directions) { val newPoint = Point( curr.x + direction[0], curr.y + direction[1], distance, 0 ) if (newPoint.x >= 0 && newPoint.x < grid.size && newPoint.y >= 0 && newPoint.y < grid[0].size && !visited[newPoint.x][newPoint.y] && grid[newPoint.x][newPoint.y] != 0 ) { newPoint.`val` = grid[newPoint.x][newPoint.y] visited[newPoint.x][newPoint.y] = true queue.add(newPoint) visitedPoints.add(newPoint) } } } } } internal class Point(var x: Int, var y: Int, var dist: Int, var `val`: Int) }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/bk70/Problem3$highestRankedKItems$$inlined$thenBy$3.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class bk70.Problem3$highestRankedKItems$$inlined$thenBy$3<T> implements java.util.Comparator {\n final java.util.Comparator $this_thenBy;...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/wk271/Problem3.kt
package wk271 fun main() { // val res = Problem3().minimumRefill(intArrayOf(2,2,3,3), 5 ,5) // val res = Problem3().minimumRefill(intArrayOf(2,2,3,3), 3 ,4) val res = Problem3().minimumRefill(intArrayOf(2, 2, 5, 2, 2), 5, 5) println(res) } class Problem3 { fun minimumRefill(plants: IntArray, capacityA: Int, capacityB: Int): Int { var aliceCur = 0 var bobCur = plants.size - 1 var aliceCurCapacity = capacityA var bobCurCapacity = capacityB var result = 0 while (aliceCur <= bobCur) { if (aliceCur == bobCur) { if (bobCurCapacity > aliceCurCapacity) { if (plants[bobCur] <= bobCurCapacity) { bobCurCapacity -= plants[bobCur] } else { result++ } } else { if (plants[aliceCur] <= aliceCurCapacity) { aliceCurCapacity -= plants[aliceCur] } else { result++ } } return result } if (plants[aliceCur] <= aliceCurCapacity) { aliceCurCapacity -= plants[aliceCur] } else { result++ aliceCurCapacity = capacityA aliceCurCapacity -= plants[aliceCur] } if (plants[bobCur] <= bobCurCapacity) { bobCurCapacity -= plants[bobCur] } else { result++ bobCurCapacity = capacityB bobCurCapacity -= plants[bobCur] } aliceCur++ bobCur-- } return result } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/wk271/Problem3Kt.class", "javap": "Compiled from \"Problem3.kt\"\npublic final class wk271.Problem3Kt {\n public static final void main();\n Code:\n 0: new #8 // class wk271/Problem3\n 3: dup\n 4: invokespe...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/bk65/Problem1.kt
package bk65 import kotlin.math.abs fun main() { // "aaaa" // "bccb" val resul = Problem1().checkAlmostEquivalent("aaaa", "bccb") println(resul) } class Problem1 { fun checkAlmostEquivalent(word1: String, word2: String): Boolean { val map1 = word1.toCharArray().toList().groupingBy { it }.eachCount() val map2 = word2.toCharArray().toList().groupingBy { it }.eachCount() val bigger = if (map1.size > map2.size) map1 else map2 val smaller = if (map1.size <= map2.size) map1 else map2 for (entry: Map.Entry<Char, Int> in bigger) { val char1 = entry.key val char1Count = entry.value val char2Count = smaller[char1] ?: 0 if (abs(char1Count - char2Count) > 3) return false } for (entry: Map.Entry<Char, Int> in smaller) { val char1 = entry.key val char1Count = entry.value val char2Count = bigger[char1] ?: 0 if (abs(char1Count - char2Count) > 3) return false } return true } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/bk65/Problem1$checkAlmostEquivalent$$inlined$groupingBy$2.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class bk65.Problem1$checkAlmostEquivalent$$inlined$groupingBy$2 implements kotlin.collections.Grouping<java.lang.Character, java.la...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/sep_challenge2021/ShortestPathGridWithObstacles.kt
package sep_challenge2021 import java.util.* fun main() { val grid = arrayOf( intArrayOf(0, 0, 0), intArrayOf(1, 1, 0), intArrayOf(0, 0, 0), intArrayOf(0, 1, 1), intArrayOf(0, 0, 0), ) val result = shortestPath(grid, 1) assert(result == 6) println(result) } val directions = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) fun shortestPath(grid: Array<IntArray>, k: Int): Int { val m = grid.size val n = grid[0].size val visited = Array(grid.size) { Array(grid[0].size) { IntArray(grid[0].size * grid.size + 1) } } val queue: Queue<IntArray> = LinkedList() queue.add(intArrayOf(0, 0, k, 0)) while (!queue.isEmpty()) { val current = queue.poll() val i = current[0] val j = current[1] val currentRemain = current[2] val currentDist = current[3] if (visited[i][j][currentRemain] == 1) continue visited[i][j][currentRemain] = 1 if (i == m - 1 && j == n - 1) return currentDist for (direction in directions) { val newI = i + direction[0] val newJ = j + direction[1] if (newI in 0 until m && newJ in 0 until n) { if (grid[newI][newJ] == 1 && currentRemain > 0) { queue.add(intArrayOf(newI, newJ, currentRemain - 1, currentDist + 1)) } else if (grid[newI][newJ] == 0) { queue.add(intArrayOf(newI, newJ, currentRemain, currentDist + 1)) } } } } return -1 }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/sep_challenge2021/ShortestPathGridWithObstaclesKt.class", "javap": "Compiled from \"ShortestPathGridWithObstacles.kt\"\npublic final class sep_challenge2021.ShortestPathGridWithObstaclesKt {\n private static final int[][] directions;\n\n public static f...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/wk269/Problem2.kt
package wk269 // fun main() { val result = Problem2().getAverages(intArrayOf(7, 4, 3, 9, 1, 8, 5, 2, 6), 3) // val result = Problem2().getAverages(intArr, 10) println(result) } class Problem2 { fun getAverages(nums: IntArray, k: Int): IntArray { if (k * 2 > nums.size - 1) return IntArray(nums.size) { -1 } var initSum: Long = 0 val result = IntArray(nums.size) for (index in 0..k * 2) { initSum += nums[index] } result[k] = (initSum / (k * 2 + 1)).toInt() for (index in nums.indices) { val prevIndex = index - 1 - k val nextIndex = index + k if (index == k) continue if (prevIndex < 0 || nextIndex >= nums.size) { result[index] = -1 continue } val prev = nums[prevIndex] val next = nums[nextIndex] initSum = initSum - prev + next result[index] = (initSum / (k * 2 + 1)).toInt() } return result } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/wk269/Problem2.class", "javap": "Compiled from \"Problem2.kt\"\npublic final class wk269.Problem2 {\n public wk269.Problem2();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4:...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/wk269/Problem3.kt
package wk269 import kotlin.math.min fun main() { val result = Problem3().minimumDeletions(intArrayOf(1, 2)) println(result) } class Problem3 { fun minimumDeletions(nums: IntArray): Int { // Find indices of min and max elements var minIndex = 0 var maxIndex = 0 for ((index, num) in nums.withIndex()) { if (num > nums[maxIndex]) maxIndex = index if (num < nums[minIndex]) minIndex = index } // Find in what order min and max elements appear in the array val first = if (minIndex < maxIndex) minIndex else maxIndex val second = if (minIndex > maxIndex) minIndex else maxIndex // There are 3 cases when we can remove 2 elements: // 1. Remove all elements from the first appeared element to the right. // It will include both elements in any case: // _ _ // 2,1,3,6,5 // |_______ val removeLessToTheLeft = first + 1 // 2. Remove all elements from the second appeared element to the left. // It will include both elements in any case: // _ _ // 2,1,3,6,5 // _______| val removeLessToTheRight = nums.size - first // 3. Remove all elements from the first to the left // and from the second to the right // _ _ // 2,1,3,6,5 // ___| |___ val removeBiggerToTheLeft = second + 1 val removeBiggerToTheRight = nums.size - second // Then just find the minimum between all 3 cases: return min( removeLessToTheLeft + removeBiggerToTheRight, min(removeLessToTheRight, removeBiggerToTheLeft) ) } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/wk269/Problem3Kt.class", "javap": "Compiled from \"Problem3.kt\"\npublic final class wk269.Problem3Kt {\n public static final void main();\n Code:\n 0: new #8 // class wk269/Problem3\n 3: dup\n 4: invokespe...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/feb_challenge2023/ShortestPathWithAltColors.kt
package feb_challenge2023 import java.util.* fun main() { val result = ShortestPathWithAltColors() .shortestAlternatingPaths( 5, arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(3, 4)), arrayOf(intArrayOf(1, 2), intArrayOf(2, 3), intArrayOf(3, 1)) ) // val result = // ShortestPathWithAltColors() // .shortestAlternatingPaths( // 3, // arrayOf(intArrayOf(0, 1), intArrayOf(0, 2)), // arrayOf(intArrayOf(1,0)) // ) println(result) } class ShortestPathWithAltColors { private val graph = mutableMapOf<Int, MutableList<Point>>() private var graphSize = 0 private var result = intArrayOf() fun shortestAlternatingPaths(n: Int, redEdges: Array<IntArray>, blueEdges: Array<IntArray>): IntArray { graphSize = n result = IntArray(n) { -1 } buildGraph(redEdges, blueEdges) bfs() return result } private fun bfs() { val visited = mutableSetOf<String>() val queue: Queue<Point> = LinkedList() queue.add(Point(0, -1)) visited.add("c-1v0") result[0] = 0 var distance = -1 while (!queue.isEmpty()) { distance++ val size = queue.size for (i in 0 until size) { val curr = queue.poll() if (result[curr.value] == -1) result[curr.value] = distance val children = graph.getOrDefault(curr.value, mutableListOf()) for (child in children) { val visitedKey = "c${child.color}v${child.value}" if (!visited.contains(visitedKey) and (curr.color != child.color)) { queue.add(child) visited.add(visitedKey) } } } } } private fun buildGraph(redEdges: Array<IntArray>, blueEdges: Array<IntArray>) { for (redEdge: IntArray in redEdges) processEdge(0, redEdge) for (blueEdge: IntArray in blueEdges) processEdge(1, blueEdge) } private fun processEdge(color: Int, edge: IntArray) { val from = edge[0] val to = edge[1] val existingEdges = graph.getOrDefault(from, mutableListOf()) existingEdges.add(Point(to, color)) graph[from] = existingEdges } internal data class Point(val value: Int = -1, val color: Int = -1) }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/feb_challenge2023/ShortestPathWithAltColors$Point.class", "javap": "Compiled from \"ShortestPathWithAltColors.kt\"\npublic final class feb_challenge2023.ShortestPathWithAltColors$Point {\n private final int value;\n\n private final int color;\n\n publi...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/bk69/Problem3.kt
package bk69 // ["dd","aa","bb","dd","aa","dd","bb","dd","aa","cc","bb","cc","dd","cc"] fun main() { val res = Problem3().longestPalindrome( arrayOf( "xx", "zz" ) ) println(res) } class Problem3 { fun longestPalindrome(words: Array<String>): Int { val countMap = words.toList().groupingBy { it }.eachCount() as MutableMap<String, Int> var sameMax = 0 var res = 0 for (entry in countMap) { val str = entry.key val reversed = str.reversed() val num = entry.value val reversedCount = countMap.getOrDefault(str.reversed(), 0) if (str == reversed && num == 1) sameMax = 1 if (num >= 1 && reversedCount >= 1) { var minNum = minOf(num, reversedCount) if (minNum > 1 && minNum % 2 == 1) minNum-- res += minNum * if (str == reversed) 2 else 4 countMap[str] = num - minNum if (countMap.containsKey(reversed)) { countMap[reversed] = reversedCount - minNum } } } for (entry in countMap) { if (entry.key == entry.key.reversed()) sameMax = maxOf(entry.value, sameMax) } return res + sameMax * 2 } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/bk69/Problem3$longestPalindrome$$inlined$groupingBy$1.class", "javap": "Compiled from \"_Collections.kt\"\npublic final class bk69.Problem3$longestPalindrome$$inlined$groupingBy$1 implements kotlin.collections.Grouping<java.lang.String, java.lang.String> ...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/bk66/Problem3.kt
package bk66 fun main() { val result = Problem3().minCost(intArrayOf(0, 3), intArrayOf(2, 3), intArrayOf(5, 4, 3), intArrayOf(8, 2, 6, 7)) println(result) } class Problem3 { fun minCost(startPos: IntArray, homePos: IntArray, rowCosts: IntArray, colCosts: IntArray): Int { val startI = startPos[0] val startJ = startPos[1] val homeI = homePos[0] val homeJ = homePos[1] if (startI == homeI && startJ == homeJ) return 0 var result = 0 if (startJ < homeJ) { for (i in startJ + 1..homeJ) result += colCosts[i] } else { for (i in startJ - 1 downTo homeJ) result += colCosts[i] } if (startI < homeI) { for (i in startI + 1..homeI) result += rowCosts[i] } else { for (i in startI - 1 downTo homeI) result += rowCosts[i] } return result } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/bk66/Problem3Kt.class", "javap": "Compiled from \"Problem3.kt\"\npublic final class bk66.Problem3Kt {\n public static final void main();\n Code:\n 0: new #8 // class bk66/Problem3\n 3: dup\n 4: invokespecia...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/nov_challenge2021/UniquePathsIII.kt
package nov_challenge2021 fun main() { val grid1 = arrayOf( intArrayOf(1, 0, 0, 0), intArrayOf(0, 0, 0, 0), intArrayOf(0, 0, 2, -1), ) val res1 = UniquePathsIII().uniquePathsIII(grid1) assert(res1 == 2) val grid2 = arrayOf( intArrayOf(0, 1), intArrayOf(2, 0), ) val res2 = UniquePathsIII().uniquePathsIII(grid2) assert(res2 == 0) } class UniquePathsIII { private var result = 0 private lateinit var visited: Array<IntArray> private lateinit var grid: Array<IntArray> private var obstaclesCount = 0 private val dirs = arrayOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0)) fun uniquePathsIII(grid: Array<IntArray>): Int { var startI = 0 var startJ = 0 this.grid = grid visited = Array(grid.size) { IntArray(grid[0].size) } for (i in grid.indices) { for (j in grid[i].indices) { if (grid[i][j] == 1) { startI = i startJ = j } if (grid[i][j] == -1) { obstaclesCount++ } } } count(startI, startJ, 0) return result } private fun count(i: Int, j: Int, counter: Int) { if (grid[i][j] == 2 && counter == grid.size * grid[0].size - 1 - obstaclesCount) { result++ return } visited[i][j] = 1 for (dir in dirs) { val newI = i + dir.first val newJ = j + dir.second if ( newI >= 0 && newI < grid.size && newJ >= 0 && newJ < grid[0].size && visited[newI][newJ] == 0 && grid[newI][newJ] != -1 ) { count(newI, newJ, counter + 1) } } visited[i][j] = 0 } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/nov_challenge2021/UniquePathsIII.class", "javap": "Compiled from \"UniquePathsIII.kt\"\npublic final class nov_challenge2021.UniquePathsIII {\n private int result;\n\n private int[][] visited;\n\n private int[][] grid;\n\n private int obstaclesCount;\...
yvelianyk__leetcode-kotlin__780d659/src/main/kotlin/oct_challenge2021/wordSearchII/WordSearchII.kt
package oct_challenge2021.wordSearchII fun main() { val matrix = arrayOf( charArrayOf('o', 'a', 'a', 'n'), charArrayOf('e', 't', 'a', 'e'), charArrayOf('i', 'h', 'k', 'r'), charArrayOf('i', 'f', 'l', 'v'), ) val words = arrayOf("oath", "pea", "eat", "rain") val result = WordSearchII().findWords(matrix, words) println(result) // expected "oath", "eat" } class WordSearchII { private val hashResult = hashSetOf<String>() private lateinit var board: Array<CharArray> private val trie = Trie() fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { this.board = board for (word in words) trie.insert(word) for (i in board.indices) { for (j in board[0].indices) { traverse(i, j, "") } } return hashResult.toList() } private fun traverse(i: Int, j: Int, prev: String) { if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] == '#') return val current = prev + board[i][j] if (!trie.startsWith(current)) return if (trie.search(current)) hashResult.add(current) val temp = board[i][j] board[i][j] = '#' traverse(i + 1, j, current) traverse(i, j + 1, current) traverse(i - 1, j, current) traverse(i, j - 1, current) board[i][j] = temp } } private class Trie { private val root: TrieNode? = TrieNode() fun insert(word: String) { var node = root for (currChar in word) { if (!node!!.containsKey(currChar)) { node.put(currChar, TrieNode()) } node = node.get(currChar) } node!!.isEnd = true } fun search(word: String): Boolean { val node = searchPrefix(word) return node != null && node.isEnd } fun startsWith(prefix: String): Boolean { val node = searchPrefix(prefix) return node != null } private fun searchPrefix(word: String): TrieNode? { var node = root for (currChar in word) { if (node!!.containsKey(currChar)) { node = node.get(currChar) } else { return null } } return node } } private class TrieNode { private val numberOfAlphabet = 26 private var links: Array<TrieNode?> = arrayOfNulls(numberOfAlphabet) var isEnd = false fun containsKey(char: Char): Boolean { return links[char - 'a'] != null } fun get(char: Char): TrieNode? { return links[char - 'a'] } fun put(char: Char, node: TrieNode) { links[char - 'a'] = node } }
[ { "class_path": "yvelianyk__leetcode-kotlin__780d659/oct_challenge2021/wordSearchII/WordSearchIIKt.class", "javap": "Compiled from \"WordSearchII.kt\"\npublic final class oct_challenge2021.wordSearchII.WordSearchIIKt {\n public static final void main();\n Code:\n 0: iconst_4\n 1: anewarray ...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day07/day07.kt
package day07 import java.io.File data class Bid(val hand: String, val bet: Int) fun main() { run(encode1, ::part1) run(encode2, ::part2) } fun run(encode: Map<Char, Char>, rank: (String) -> Char) { val result = File("input.data").readLines().map { parseHand(it, encode, rank) }.sortedBy { it.hand }.withIndex() .sumOf { (idx, card) -> (idx + 1) * card.bet } println(result) } fun parseHand(line: String, encode: Map<Char, Char>, type: (String) -> Char): Bid { val (handStr, bet) = line.split(" ") val hand = handStr.map { encode[it] }.joinToString(separator = "") return Bid(hand = type(handStr) + hand, bet = bet.toInt()) } fun part1(hand: String): Char { val sizes = hand.map { it }.groupBy { it }.map { it.value.size }.sortedBy { -it } return type(sizes) } fun part2(hand: String): Char { val g = hand.map { it }.groupBy { it }.map { it.value }.toList().sortedBy { -it.size }.toList() var bestRank = g[0][0] if (bestRank == 'J' && g.size > 1) { bestRank = g[1][0] } val sizes = hand.replace('J', bestRank).map { it }.groupBy { it }.map { it.value.size }.sortedBy { -it } .toList() return type(sizes) } fun type(sizes: List<Int>): Char = when (sizes[0]) { 1 -> 'a' // high card 2 -> when (sizes[1]) { 1 -> 'b' // pair else -> 'c' // two pair } 3 -> when (sizes[1]) { 1 -> 'd' // three of a kind else -> 'e' // full house } 4 -> 'f' // four of a kind 5 -> 'g' // 5 aces? else -> 'x' } // encode rank to sortable code val encode1 = mapOf( '2' to 'b', '3' to 'c', '4' to 'd', '5' to 'e', '6' to 'f', '7' to 'g', '8' to 'h', '9' to 'i', 'T' to 'j', 'J' to 'k', 'Q' to 'l', 'K' to 'm', 'A' to 'n', ) // encode rank to sortable code val encode2 = mapOf( 'J' to 'a', '2' to 'b', '3' to 'c', '4' to 'd', '5' to 'e', '6' to 'f', '7' to 'g', '8' to 'h', '9' to 'i', 'T' to 'j', 'Q' to 'l', 'K' to 'm', 'A' to 'n', ) //251927063 //255632664
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day07/Day07Kt$part1$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class day07.Day07Kt$part1$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public day07.Day07Kt$part1$$inlined$sortedBy$1();\n Code:\n ...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day08/day08.kt
package day08 import java.io.File data class Targets(val left: String, val right: String) fun main() { run(start = { it == "AAA" }, end = { it == "ZZZ" }) run(start = { it.endsWith('A') }, end = { it.endsWith('Z') }) } fun run(start: (String) -> Boolean, end: (String) -> Boolean) { val lines = File("input.data").readLines() val turns = turnSequence(lines[0]) val instructions = parseInstructions(lines.drop(2)) var totalSteps = 1L for (startPlace in instructions.keys.filter(start)) { var place = startPlace var steps = 0L for (turn in turns) { steps++ val targets = instructions[place]!! place = if (turn == 'L') targets.left else targets.right if (end(place)) break } totalSteps = lcm(totalSteps, steps) } println(totalSteps) } fun parseInstructions(lines: List<String>): Map<String, Targets> { val result = mutableMapOf<String, Targets>() for (line in lines) { val parts = line.split(" = (", ", ", ")") result[parts[0]] = Targets(left = parts[1], right = parts[2]) } return result } fun turnSequence(turns: String) = sequence { while (true) { for (char in turns) { yield(char) } } } fun lcm(first: Long, second: Long): Long = first / gcd(first, second) * second fun gcd(first: Long, second: Long): Long { var a = first var b = second while (b > 0) { val t = b b = a % b a = t } return a } // 11911 // 10151663816849
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day08/Day08Kt$turnSequence$1.class", "javap": "Compiled from \"day08.kt\"\nfinal class day08.Day08Kt$turnSequence$1 extends kotlin.coroutines.jvm.internal.RestrictedSuspendLambda implements kotlin.jvm.functions.Function2<kotlin.sequences.SequenceScope<? supe...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day06/day06.kt
package day06 import java.io.File import kotlin.math.ceil import kotlin.math.sqrt data class Race(val time: Long, val distance: Long) fun main() { run(::part1, ::solve) run(::part1, ::altSolve) run(::part2, ::solve) run(::part2, ::altSolve) } fun run(part: (String) -> List<Long>, solution: (Race) -> Long) { val lines = File("input.data").readLines() val result = part(lines[0]).zip(part(lines[1])) .map { (time, distance) -> Race(time = time, distance = distance) } .map { solution(it) } .reduce { acc, n -> acc * n } println(result) } fun part1(line: String): List<Long> = line.split(Regex(" +")).drop(1).map { it.toLong() } fun part2(line: String): List<Long> = listOf(line.split(Regex(" +")).drop(1).joinToString(separator = "").toLong()) fun solve(race: Race): Long { var min = 0L var max = race.time / 2 while (true) { val mid = (min + max + 1) / 2 val prod = mid * (race.time - mid) if (prod <= race.distance) { min = mid } else { max = mid } if (max - min == 1L) { return race.time + 1L - 2L * max } } } fun altSolve(race: Race): Long { val discriminant = (race.time*race.time - 4*race.distance).toDouble() val solution = (race.time - sqrt(discriminant)) / 2 val roundedUp = ceil(solution).toLong() return race.time + 1L - 2L * roundedUp } // 2449062 // 33149631
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day06/Day06Kt$main$8.class", "javap": "Compiled from \"day06.kt\"\nfinal class day06.Day06Kt$main$8 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function1<day06.Race, java.lang.Long> {\n public static final day06.Day06Kt...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day04/day04.kt
package day04 import java.io.File fun main() { Part1("input.data").run() Part2("input.data").run() } data class Card(val matchingNumbers: Int, var copies: Int = 1) abstract class Day04(val fileName: String) { val cards = parseInput() fun run() { var result = 0 for ((idx, card) in cards.withIndex()) { for (idx2 in idx + 1..idx + card.matchingNumbers) { cards[idx2].copies += card.copies } result += score(card) } println(result) } abstract fun score(card: Card): Int private fun parseInput(): List<Card> { val cards = mutableListOf<Card>() for (line in File(fileName).readLines()) { val parts = line.split(": ", " | ") cards += Card(matchingNumbers = parseNumbers(parts[1]).intersect(parseNumbers(parts[2])).size) } return cards } private fun parseNumbers(numbers: String) = numbers.trim().split(Regex(" +")).toSet() } class Part1(fileName: String) : Day04(fileName) { override fun score(card: Card): Int { if (card.matchingNumbers == 0) return 0 var result = 1 repeat(card.matchingNumbers - 1) { result *= 2 } return result } } class Part2(fileName: String) : Day04(fileName) { override fun score(card: Card): Int = card.copies } // Part1: 25004 // Part2: 14427616
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day04/Day04Kt.class", "javap": "Compiled from \"day04.kt\"\npublic final class day04.Day04Kt {\n public static final void main();\n Code:\n 0: new #8 // class day04/Part1\n 3: dup\n 4: ldc #10 ...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day03/day03.kt
package day03 import java.io.File fun main() { run(::part1) run(::part2) } data class Number(val value: Int, val row: Int, val colStart: Int, var colEnd: Int) fun run(part: (numbers: List<Number>, char: Char, row: Int, col: Int) -> Int) { val lines = File("input.data").readLines() val numbers = parseEngine(lines) var result = 0 for ((row, line) in lines.withIndex()) { for ((col, char) in line.withIndex()) { result += part(numbers, char, row, col) } } println(result) } fun part1(numbers: List<Number>, char: Char, row: Int, col: Int): Int { var result = 0 if (char != '.' && !char.isDigit()) { for (number in numbers) { if (adjacent(number, row, col)) { result += number.value } } } return result } fun part2(numbers: List<Number>, char: Char, row: Int, col: Int): Int { var result = 0 if (char == '*') { val adjacentNumbers = mutableListOf<Number>() for (number in numbers) { if (adjacent(number, row, col)) adjacentNumbers += number } if (adjacentNumbers.size == 2) { result += adjacentNumbers[0].value * adjacentNumbers[1].value } } return result } fun parseEngine(lines: List<String>): List<Number> { val numbers = mutableListOf<Number>() for ((row, line) in lines.withIndex()) { var firstDigit = -1 for ((col, char) in line.withIndex()) { if (char.isDigit()) { if (firstDigit == -1) { firstDigit = col } } else { if (firstDigit != -1) { val value = line.substring(firstDigit, col).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = col) firstDigit = -1 } } } if (firstDigit != -1) { val value = line.substring(firstDigit, line.length).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = line.length) } } return numbers } fun adjacent(number: Number, row: Int, col: Int): Boolean = row in number.row - 1..number.row + 1 && col in number.colStart - 1..number.colEnd // Part1: 527144 // Part2: 81463996
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day03/Day03Kt.class", "javap": "Compiled from \"day03.kt\"\npublic final class day03.Day03Kt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field day03/Day03Kt$main$1.INSTANCE:Lday03/Day03Kt$main$1;\n 3...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day03_oop/day03_oop.kt
package day03_oop import java.io.File fun main() { Part1("input.data").run() Part2("input.data").run() } data class Number(val value: Int, val row: Int, val colStart: Int, var colEnd: Int) abstract class Day03(fileName: String) { private val lines = File(fileName).readLines() val numbers = parseEngine() abstract fun score(char: Char, row: Int, col: Int): Int fun run() { var result = 0 for ((row, line) in lines.withIndex()) { for ((col, char) in line.withIndex()) { result += score(char, row, col) } } println(result) } private fun parseEngine(): List<Number> { val numbers = mutableListOf<Number>() for ((row, line) in lines.withIndex()) { var firstDigit = -1 for ((col, char) in line.withIndex()) { if (char.isDigit()) { if (firstDigit == -1) { firstDigit = col } } else { if (firstDigit != -1) { val value = line.substring(firstDigit, col).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = col) firstDigit = -1 } } } if (firstDigit != -1) { val value = line.substring(firstDigit, line.length).toInt() numbers += Number(value = value, row = row, colStart = firstDigit, colEnd = line.length) } } return numbers } fun adjacent(number: Number, row: Int, col: Int): Boolean = row in number.row - 1..number.row + 1 && col in number.colStart - 1..number.colEnd } class Part1(fileName: String) : Day03(fileName) { override fun score(char: Char, row: Int, col: Int): Int { var result = 0 if (char != '.' && !char.isDigit()) { for (number in numbers) { if (adjacent(number, row, col)) { result += number.value } } } return result } } class Part2(fileName: String) : Day03(fileName) { override fun score(char: Char, row: Int, col: Int): Int { var result = 0 if (char == '*') { val adjacentNumbers = mutableListOf<Number>() for (number in numbers) { if (adjacent(number, row, col)) adjacentNumbers += number } if (adjacentNumbers.size == 2) { result += adjacentNumbers[0].value * adjacentNumbers[1].value } } return result } }
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day03_oop/Day03_oopKt.class", "javap": "Compiled from \"day03_oop.kt\"\npublic final class day03_oop.Day03_oopKt {\n public static final void main();\n Code:\n 0: new #8 // class day03_oop/Part1\n 3: dup\n 4: ...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day02/day02.kt
package day02 import java.io.File import kotlin.math.max data class Game(val id: Int, val colors: Colors) data class Colors(val red: Int, val green: Int, val blue: Int) fun main() { println(run(::part1)) println(run(::part2)) } fun run(score: (Game) -> Int): Int = File("input.data").readLines().sumOf { score(parseGame(it)) } fun parseGame(line: String): Game { val (gameIdStr, gameDataStr) = line.split(": ") val gameId = gameIdStr.split(" ")[1].toInt() return Game(id = gameId, colors = parseColors(gameDataStr)) } fun parseColors(gameDataStr: String): Colors { var red = 0 var green = 0 var blue = 0 for (setStr in gameDataStr.split("; ")) { val colorsStr = setStr.split(", ") for (colorStr in colorsStr) { val (cubesStr, color) = colorStr.split(" ") val cubes = cubesStr.toInt() when (color) { "red" -> red = max(red, cubes) "green" -> green = max(green, cubes) "blue" -> blue = max(blue, cubes) } } } return Colors(red = red, green = green, blue = blue) } fun part1(game: Game): Int { val colors = game.colors if (colors.red <= 12 && colors.green <= 13 && colors.blue <= 14) return game.id return 0 } fun part2(game: Game): Int { return game.colors.red * game.colors.green * game.colors.blue }
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day02/Day02Kt.class", "javap": "Compiled from \"day02.kt\"\npublic final class day02.Day02Kt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field day02/Day02Kt$main$1.INSTANCE:Lday02/Day02Kt$main$1;\n 3...
andrew-suprun__AoC-2023__dd5f53e/src/main/kotlin/day05/day05.kt
package day05 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { run(::part1) run(::part2) } data class Map(val range: LongRange, val inc: Long) data class Model(val seeds: List<LongRange>, val allMaps: List<List<Map>>) fun run(part: (String) -> List<LongRange>) { val model = parseInput(part) var mapped = model.seeds for (maps in model.allMaps) { mapped = mapLongRanges(mapped, maps) } println(mapped.minOfOrNull { it.first }) } fun mapLongRanges(ranges: List<LongRange>, maps: List<Map>): List<LongRange> { val result = mutableListOf<LongRange>() var unprocessed = mutableListOf<LongRange>() var toProcess = MutableList(ranges.size) { ranges[it] } for (map in maps) { for (range in toProcess) { if (range.first >= map.range.last || range.last <= map.range.first) { unprocessed += range } else { val start = max(range.first, map.range.first) val end = min(range.last, map.range.last) result += start + map.inc..<end + map.inc if (range.first < start) { unprocessed += range.first..<start } if (range.last > end) { unprocessed += end..<range.last } } } toProcess = unprocessed unprocessed = mutableListOf() } result += toProcess return result } fun parseInput(seeds: (String) -> List<LongRange>): Model { val lines = File("input.data").readLines() val ranges = seeds(lines[0]) val allMaps = mutableListOf<List<Map>>() var curMaps = mutableListOf<Map>() for (line in lines.drop(3)) { when { line == "" -> continue line.endsWith(" map:") -> { allMaps += curMaps curMaps = mutableListOf() } else -> { val numbers = line.split(" ").map { it.toLong() } curMaps += Map(range = numbers[1]..< numbers[1] + numbers[2], inc = numbers[0] - numbers[1]) } } } allMaps += curMaps return Model(seeds = ranges, allMaps = allMaps) } fun part1(line: String): List<LongRange> = line.split(" ").drop(1).map { val start = it.toLong() start..<start+1 } fun part2(line: String): List<LongRange> { val seedNumbers = line.split(" ").drop(1).map { it.toLong() } return seedNumbers.chunked(2).map { (start, len) -> start..<start + len } } // 993500720 // 4917124
[ { "class_path": "andrew-suprun__AoC-2023__dd5f53e/day05/Day05Kt.class", "javap": "Compiled from \"day05.kt\"\npublic final class day05.Day05Kt {\n public static final void main();\n Code:\n 0: getstatic #12 // Field day05/Day05Kt$main$1.INSTANCE:Lday05/Day05Kt$main$1;\n 3...
RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/easy/TwoNumberSum.kt
package com.ztoais.dailycoding.algoexpert.easy /* Two Number Sum Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return then in an array. in any order. if no two numbers sum up the target sum, the function should return an empty array. Note that the target sum has to be obtained by summing two different integers in the array: you can't add a single integer to itself in order to obtain the target sum. You can assume that there will be at most one pair of numbers summing up to the target sum. */ //Sample input /* { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 10 } //Sample output [-1,11] */ fun twoNumberSum(array: MutableList<Int>,targetSum:Int):List<Int>{ val initialValue = array[0] val newArray = mutableListOf<Int>() array.drop(1).forEach{nextValue -> if(initialValue+nextValue == targetSum){ return listOf(initialValue,nextValue) }else{ newArray.add(nextValue) } } if(newArray.size >1){ return twoNumberSum(newArray,targetSum) } return listOf() } /* //Test cases Test Case 1 { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 10 } Test Case 2 { "array": [4, 6], "targetSum": 10 } Test Case 3 { "array": [4, 6, 1], "targetSum": 5 } Test Case 4 { "array": [4, 6, 1, -3], "targetSum": 3 } Test Case 5 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "targetSum": 17 } Test Case 6 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 18 } Test Case 7 { "array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "targetSum": -5 } Test Case 8 { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 163 } Test Case 9 { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 164 } Test Case 10 { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 15 } Test Case 11 { "array": [14], "targetSum": 15 } Test Case 12 { "array": [15], "targetSum": 15 } */
[ { "class_path": "RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/easy/TwoNumberSumKt.class", "javap": "Compiled from \"TwoNumberSum.kt\"\npublic final class com.ztoais.dailycoding.algoexpert.easy.TwoNumberSumKt {\n public static final java.util.List<java.lang.Integer> twoNumberSum(j...
RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/hard/FourNumberSum.kt
package com.ztoais.dailycoding.algoexpert.hard /* Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all quadruplets in the array that sum up to the target sum and return a tow-dimensional array of all these quadruplets in no particular order. If no four numbers sum up to the target sum, the function should return an empty array Sample input array = [7,6,4,-1,1,2] targetSum = 16 Sample output [[7,6,4,-1],[7,6,1,2]] */ /* */ fun fourNumberSum(array: MutableList<Int>, targetSum:Int):List<List<Int>>{ val result = mutableListOf<List<Int>>() val appPairSums = mutableMapOf<Int,List<Pair<Int,Int>>>() for (i in 1 until array.size-1) { for(j in i+1 until array.size){ val currentSum:Int = array[i]+array[j] val difference = targetSum - currentSum if(appPairSums.containsKey(difference)){ val pairValues = appPairSums[difference] pairValues?.let { for(pair in it){ val quadruplets = listOf(pair.first,pair.second, array[i], array[j]) result.add(quadruplets) } } } } for(k in 0 until i){ val currentSum = array[i]+array[k] if(!appPairSums.containsKey(currentSum)){ appPairSums[currentSum] = listOf(Pair(array[k],array[i])) }else{ val pairList = appPairSums[currentSum]?.toMutableList() pairList?.add(Pair(array[k],array[i])) if (pairList != null) { appPairSums[currentSum] = pairList.toList() } } } } return result } /* Tests Quick Test Sandbox Test Case 1 { "array": [7, 6, 4, -1, 1, 2], "targetSum": 16 } Test Case 2 { "array": [1, 2, 3, 4, 5, 6, 7], "targetSum": 10 } Test Case 3 { "array": [5, -5, -2, 2, 3, -3], "targetSum": 0 } Test Case 4 { "array": [-2, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9], "targetSum": 4 } Test Case 5 { "array": [-1, 22, 18, 4, 7, 11, 2, -5, -3], "targetSum": 30 } Test Case 6 { "array": [-10, -3, -5, 2, 15, -7, 28, -6, 12, 8, 11, 5], "targetSum": 20 } Test Case 7 { "array": [1, 2, 3, 4, 5], "targetSum": 100 } Test Case 8 { "array": [1, 2, 3, 4, 5, -5, 6, -6], "targetSum": 5 } */
[ { "class_path": "RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/hard/FourNumberSumKt.class", "javap": "Compiled from \"FourNumberSum.kt\"\npublic final class com.ztoais.dailycoding.algoexpert.hard.FourNumberSumKt {\n public static final java.util.List<java.util.List<java.lang.Integ...
RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/medium/ThreeNumberSum.kt
package com.ztoais.dailycoding.algoexpert.medium import kotlin.io.path.createTempDirectory /* Three Number Sum Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should find all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold. If no three numbers sum up to the target sum, the function should return an empty array. Sample Input: array = [12,3,1,2,-6,5,-8,6] targetSum = 0 Sample Output: [[-8,2,6],[-8,3,5],[-6,1,5]] */ fun threeNumberSum(array: MutableList<Int>, targetSum: Int):List<List<Int>>{ //1. Sort the array //2. Current number firs //3. User Right and left pointer movement one at time. //4. Left pointer movement increase the current sum //5. Right pointer movement decrease the current sum //6. If the target sum equal then move the left and right same time //7. Time : O(N2) Space: O(N) array.sort() val result = mutableListOf<List<Int>>() for(i in 0..array.size-2){ var left = i+1 var right = array.size-1 while(left < right){ val currentSum = array[i]+array[left]+array[right] if(currentSum == targetSum){ result.add(listOf(array[i],array[left],array[right])) left+=1 right-=1 }else if(currentSum < targetSum){ left+=1 }else if(currentSum > targetSum){ right-=1 } } } return result } /* Tests Test Case 1 { "array": [12, 3, 1, 2, -6, 5, -8, 6], "targetSum": 0 } Test Case 2 { "array": [1, 2, 3], "targetSum": 6 } Test Case 3 { "array": [1, 2, 3], "targetSum": 7 } Test Case 4 { "array": [8, 10, -2, 49, 14], "targetSum": 57 } Test Case 5 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1], "targetSum": 0 } Test Case 6 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1, 6], "targetSum": 0 } Test Case 7 { "array": [12, 3, 1, 2, -6, 5, 0, -8, -1, 6, -5], "targetSum": 0 } Test Case 8 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 18 } Test Case 9 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 32 } Test Case 10 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 33 } Test Case 11 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 5 } */
[ { "class_path": "RanjithRagavan__daily-coding__a5f29dd/com/ztoais/dailycoding/algoexpert/medium/ThreeNumberSumKt.class", "javap": "Compiled from \"ThreeNumberSum.kt\"\npublic final class com.ztoais.dailycoding.algoexpert.medium.ThreeNumberSumKt {\n public static final java.util.List<java.util.List<java.lan...
DPNT-Sourcecode__CHK-gply01__cb056a9/src/main/kotlin/solutions/CHK/CheckoutSolution.kt
package solutions.CHK //+------+-------+------------------------+ //| Item | Price | Special offers | //+------+-------+------------------------+ //| H | 10 | 5H for 45, 10H for 80 | //| K | 80 | 2K for 150 | //| N | 40 | 3N get one M free | //| P | 50 | 5P for 200 | //| Q | 30 | 3Q for 80 | //| R | 50 | 3R get one Q free | //| U | 40 | 3U get one U free | //| V | 50 | 2V for 90, 3V for 130 | //+------+-------+------------------------+ object CheckoutSolution { private val valid = listOf('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') fun checkout(skus: String): Int { if (skus.count { it !in valid } != 0) return -1 return Skus(totalSoFar = 0, skus = skus.toMutableList()) // SKUs without a deal involved .consumeSimpleItems() .consumeE() .consumeA() .consumeB() .consumeF() .totalSoFar } } data class Skus(var totalSoFar: Int, val skus: MutableList<Char>) { val simpleSkusToPrice = mapOf( 'C' to 20, 'D' to 15, 'G' to 20, 'I' to 35, 'J' to 60, 'L' to 90, 'M' to 15, 'O' to 10, 'S' to 30, 'T' to 20, 'W' to 20, 'X' to 90, 'Y' to 10, 'Z' to 50 ) fun consumeA(): Skus { val aCount = countSku('A') val firstDealCount = aCount / 5 val secondDealCount = (aCount - (firstDealCount * 5)) / 3 val leftOver = (aCount - (firstDealCount * 5) - secondDealCount * 3) skus.removeIf { it == 'A' } totalSoFar += (firstDealCount * 200) + (secondDealCount * 130) + (leftOver * 50) return this } fun consumeB(): Skus { val value = specialDeal(2, 45, 30, countSku('B')) skus.removeIf { it == 'B' } totalSoFar += value return this } fun consumeE(): Skus { val eCost = countSku('E') * 40 totalSoFar += eCost val freeBs = countSku('E') / 2 skus.removeIf { it == 'E' } for (i in 0 until freeBs ) { skus.remove('B') } return this } fun consumeF(): Skus { totalSoFar += freeSelfDeal('F', 3, 10) skus.removeIf { it == 'F' } return this } fun consumeSimpleItems(): Skus { simpleSkusToPrice.forEach { (sku, price) -> val count = skus.count { it == sku } totalSoFar += count * price skus.removeIf { it == sku } } return this } private fun countSku(char: Char) = this.skus.count { it == char } private fun freeSelfDeal(sku: Char, countForFree: Int, usualPrice: Int): Int { val count = countSku(sku) val free = count / countForFree return (count - free) * usualPrice } private fun specialDeal(dealCount: Int, forMoney: Int, usualPrice: Int, itemCount: Int): Int { var total = 0 var items = itemCount while (items >= dealCount) { total += forMoney items -= dealCount } total += items * usualPrice return total } }
[ { "class_path": "DPNT-Sourcecode__CHK-gply01__cb056a9/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 static final java.util.List<java.lang...
DPNT-Sourcecode__CHK-ojzb01__035af07/src/main/kotlin/solutions/CHK/CheckoutSolution.kt
package solutions.CHK data class Product(val price: Int, val offers: List<Offer> = listOf()) data class Offer( val requiredCount: Int, val price: Int, val freeItem: Char? = null, val freeItemCount: Int = 1, val groupItems: List<Char>? = null ) object CheckoutSolution { private var productMap = mutableMapOf<Char, Product>( 'A' to Product(50, listOf(Offer(5,200), Offer(3, 130))), 'B' to Product(30, listOf(Offer(2, 45))), 'C' to Product(20), 'D' to Product(15), 'E' to Product(40, listOf(Offer(2, 80, 'B'))), 'F' to Product(10, listOf(Offer(3, 20))), 'G' to Product(20), 'H' to Product(10, listOf(Offer(10, 80), Offer(5, 45))), 'I' to Product(35), 'J' to Product(60), 'K' to Product(70, listOf(Offer(2, 120))), 'L' to Product(90), 'M' to Product(15), 'N' to Product(40, listOf(Offer(3, 120, 'M'))), 'O' to Product(10), 'P' to Product(50, listOf(Offer(5, 200))), 'Q' to Product(30, listOf(Offer(3, 80))), 'R' to Product(50, listOf(Offer(3, 150, 'Q'))), 'S' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))), 'T' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))), 'U' to Product(40, listOf(Offer(4,120))), 'V' to Product(50, listOf(Offer(3, 130), Offer(2, 90))), 'W' to Product(20), 'X' to Product(17, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))), 'Y' to Product(20, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))), 'Z' to Product(21, listOf(Offer(3, 45, groupItems = listOf('S', 'T', 'X', 'Y', 'Z')))), ) fun checkout(skus: String): Int { val itemCounts = skus.groupingBy { it }.eachCount().toMutableMap() if (itemCounts.keys.any { it !in productMap }) return -1 var total = 0 total += processFreeItems(itemCounts) total += processGroupDiscounts(itemCounts) total += processRegularDiscountsAndRemainingItems(itemCounts) return total } private fun processRegularDiscountsAndRemainingItems(itemCounts: MutableMap<Char, Int>): Int { var total = 0 itemCounts.forEach { p -> val productChar = p.key var count = p.value val product = productMap[productChar]!! product.offers .filter { it.groupItems == null && it.freeItem == null } .sortedByDescending { o -> o.requiredCount } .forEach { offer -> while(count >= offer.requiredCount) { total += offer.price count -= offer.requiredCount } } total += count * product.price } return total } private fun processGroupDiscounts(itemCounts: MutableMap<Char, Int>): Int { var total = 0 productMap.values.forEach { product -> val groupOffers = product.offers.filter { it.groupItems != null } groupOffers.forEach { offer -> val eligibleGroupItems = offer.groupItems!!.associateWith { itemCounts.getOrDefault(it, 0) }.toMutableMap() while (eligibleGroupItems.values.sum() >= offer.requiredCount) { total += offer.price var itemsNeededForDiscount = offer.requiredCount for ((item, availabeCount) in eligibleGroupItems.entries.sortedByDescending { productMap[it.key]!!.price }) { val itemsToUseForDiscount = minOf(availabeCount, itemsNeededForDiscount) eligibleGroupItems[item] = availabeCount - itemsToUseForDiscount itemCounts[item] = itemCounts.getOrDefault(item, 0) - itemsToUseForDiscount itemsNeededForDiscount -= itemsToUseForDiscount } } } } return total } private fun processFreeItems(itemCounts: MutableMap<Char, Int>): Int { var total = 0 productMap.forEach { (productChar, product) -> var count = itemCounts.getOrDefault(productChar, 0) product.offers.filter { it.freeItem != null }.sortedByDescending { it.requiredCount }.forEach { offer -> while (count >= offer.requiredCount && (itemCounts[offer.freeItem] ?: 0) >= offer.freeItemCount) { total += offer.price count -= offer.requiredCount itemCounts[offer.freeItem!!] = maxOf(0, itemCounts[offer.freeItem]!! - offer.freeItemCount) } } itemCounts[productChar] = count } return total } }
[ { "class_path": "DPNT-Sourcecode__CHK-ojzb01__035af07/solutions/CHK/CheckoutSolution$processGroupDiscounts$lambda$10$lambda$9$$inlined$sortedByDescending$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class solutions.CHK.CheckoutSolution$processGroupDiscounts$lambda$10$lambda$9$$inlined$...
gabriaraujo__scrabble__9623ecc/app/src/main/java/com/exemple/scrabble/Trie.kt
package com.exemple.scrabble import java.lang.StringBuilder import java.util.ArrayList /** * Title: Trie * * Author: <NAME> * * Brief: * This object represents the implementation of a Trie tree for a 26 letter * alphabet. * * Descrição: * A Trie tree, or prefix tree, is an ordered tree that can be used to store an * array where the keys are usually strings. All descendants of any node have a * common prefix with the chain associated with that node, and the root is * associated with the empty chain. Normally, values ​​are not associated with * all nodes, only with the leaves and some internal nodes that correspond to * keys of interest. */ object Trie { const val alphabet = 26 private var root: TrieNode = TrieNode() class TrieNode { var child = arrayOfNulls<TrieNode>(alphabet) var leaf = false } /** * Brief: * Function responsible for inserting the dictionary words in the [Trie] * tree. * * Description: * This function inserts all the words in a dictionary into a tree [Trie]. * For the sake of simplicity, the dictionary is created in a 'hardcoded' * way, that is, its data is directly in the code. Each word in this * dictionary is added individually to the tree, the length of the string * is measured to find the index of each of its letters. The insertion * begins at the root of the tree, checking its descendants, if there is * already a node for that letter, then the root becomes that node, * otherwise a new node is created and defined as the root. Thus, with each * letter entered, a level is lowered in the tree. After the word has been * completely inserted, the last node is marked as a leaf node, indicating * the end of the word. This process is repeated for all words in the * dictionary. */ fun insert() { // dictionary containing all available words val dict = arrayOf( "pineapple", "herd", "order", "door", "table", "die", "mangoes", "go", "things", "radiography", "math", "drugs", "buildings", "implementation", "computer", "balloon", "cup", "boredom", "banner", "book", "leave", "superior", "profession", "meeting", "buildings", "mountain", "botany", "bathroom", "boxes", "cursing", "infestation", "termite", "winning", "breaded", "rats", "noise", "antecedent", "company", "emissary", "slack", "break", "guava", "free", "hydraulic", "man", "dinner", "games", "assembly", "manual", "cloud", "snow", "operation", "yesterday", "duck", "foot", "trip", "cheese", "room", "backyard", "loose", "route", "jungle", "tattoo", "tiger", "grape", "last", "reproach", "voltage", "angry", "mockery", "pain" ) // performs the individual insertion of each word in the tree for (key in dict) { // saves the word size and the root node val length = key.length var crawl = root // inserts each letter of the word in the tree for (i in 0 until length) { val index = key[i] - 'a' if (crawl.child[index] == null) crawl.child[index] = TrieNode() crawl = crawl.child[index]!! } // marks the current node as a leaf node crawl.leaf = true } } /** * Brief: * Function responsible for calculating the word score. * * Description: * Calculates the value of each valid word obtained from the input * characters. For each string, its characters are traversed and the value * assigned to them is added to an array of points, initialized with zeros, * in the index corresponding to the word in question. The set of words and * points are combined to form a set of pairs of (word, points). This set * is ordered by the size of the words, from smallest to largest, and then * the word with the highest score is selected; if there is a tie, the first * occurrence of that value is returned, that is, the smallest word. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (Pair<String, Int>?): Pair composed of the word with the highest * score and its value. */ fun highestScore(arr: CharArray): Pair<String, Int>? { // auxiliary variables for calculating the value of each letter val one = arrayOf('e', 'a', 'i', 'o', 'n', 'r', 't', 'l', 's', 'u') val two = arrayOf('w', 'd', 'g') val tree = arrayOf('b', 'c', 'm', 'p') val four = arrayOf('f', 'h', 'v') val eight = arrayOf('j', 'x') val ten = arrayOf('q', 'z') // searches for all words that can be formed from the entry val words = searchAllWords(arr) // filters the words to respect the frequency of characters wordFilter(arr, words) // calculates the value of each word and saves it in an array of points val points = IntArray(words.size) for (i in words.indices) for (letter in words[i]) when (letter) { in one -> points[i] += 1 in two -> points[i] += 2 in tree -> points[i] += 3 in four -> points[i] += 4 in eight -> points[i] += 8 in ten -> points[i] += 10 } // associates each word with its respective score var pair = words zip points.toTypedArray() // sorts pairs of (word, dots) by the length of each word pair = pair.sortedBy { it.first.length } // returns the first occurrence of the pair with the highest score return pair.maxBy { it.second } } /** * Brief: * Function responsible for finding the characters that were not used for * the composition of the final word. * * Description: * This function finds and saves all the characters that were not used for * the formation of the word with the highest score. From the input * characters and the chosen word, each letter of the word is traversed and * removes its first occurrence from the input set, so at the end of this * execution, there is a set with only the letters that were not used. * * Params: * * word (String): Highest scored word. * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (String): Set with all unused characters. */ fun getRest(word: String, arr: CharArray) : String { // auxiliary variable to store the input characters val rest = arr.toMutableList() // removes each character in the word from the input characters for (letter in word) rest.remove(letter) // returns all unused characters return String(rest.toCharArray()) } /** * Brief: * Function responsible for searching all words in the dictionary that can * be formed with the input characters. * * Description: * Searches for all words contained in the trees that can be formed with * the characters provided. Initially an array is created where the words * found will be saved and also an array of Booleans for each letter of the * alphabet. For each character received in the entry, it is marked as * 'true' in the array of Booleans in the index corresponding to that letter * in the alphabet. In sequence, this array is traversed and if any position * is marked as 'true' and there is a descendant in the tree for that * letter, then that letter is added to a string, which is initially empty, * so that a deep search can be performed for the descendants of that * letter. After all letters that have been received have been searched, the * words that were found are returned. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * Returns: * * (ArrayList<String>): Set with all the words found by the search. */ private fun searchAllWords(arr: CharArray): ArrayList<String> { // initially empty word set and boolean array val words = arrayListOf("") val hash = BooleanArray(alphabet) // marks each letter of the entry as 'true' in the Boolean array for (element in arr) hash[element - 'a'] = true var str = StringBuilder() // scrolls through the alphabet to search each letter in the entry for (i in 0 until alphabet) if (hash[i] && root.child[i] != null) { // saves the letter that has descendants and is in the entry str.append((i + 'a'.toInt()).toChar()) // performs in-depth search for each letter searchWord(root.child[i], words, hash, str.toString()) str = StringBuilder() } // returns all words found in the tree return words } /** * Brief: * Recursive function responsible for searching in depth for each letter of * the entry. * * Description: * Searches each node for the existence of descendants and adds the * characters found to the string passed by parameter, which initially has * only the first letter of the word. If the node in question is a leaf * node, it means that a complete word has been found, then that word is * added to the set. The search continues until you scroll through all the * letters available at the entrance. * * Params: * * root (TrieNode?): Node through which the search will start. * * words (ArrayList<String>): Set with all the words found by the * search. * * hash (BooleanArray): Set of Booleans that indicate which letters of * the alphabets are present at the entrance. * * str (String): Word that will be constructed during the execution of * the search. */ private fun searchWord( root: TrieNode?, words: ArrayList<String>, hash: BooleanArray, str: String ) { // if the node in question is a leaf the word is saved in the set if (root!!.leaf) words.add(str) // performs the in-depth search for each valid descendant for (i in 0 until alphabet) if (hash[i] && root.child[i] != null) { val c = (i + 'a'.toInt()).toChar() searchWord(root.child[i], words, hash, str + c) } } /** * Brief: * Function responsible for filtering words that disregard the character * frequency of the entry. * * Description: * This function removes from the set of words those that violate the * acceptance criteria, in this case the frequency of each character. * Initially an array of integers saves how many occurrences there were of * each character in the entry, where the index corresponds to its position * in the alphabet. This array is then traversed and for each letter whose * frequency is not zero, it is verified how many occurrences of it exist * in each of the words in the set. If any word has more characters of that * type than are available, that word is removed from the set. * * Params: * * arr (CharArray): Array of characters received as input for word * formation. * * words (ArrayList<String>): Set with all the words found by the * search. */ private fun wordFilter(arr: CharArray, words: ArrayList<String>) { // array that stores the frequency of each letter in the alphabet val frequency = IntArray(alphabet) // auxiliary variable to store the words that must be removed val aux = arrayListOf<String>() // the frequency of each letter is calculated and the search begins for (element in arr) frequency[element - 'a']++ for (i in 0 until alphabet) if (frequency[i] > 0) for (word in words) { // the occurrences of the letter in question are counted in the word val n = word.count { c -> c == (i + 'a'.toInt()).toChar() } // save the word that must be removed from the set if (n > frequency[i]) aux.add(word) } // remove the invalid words from the solution set for (element in aux) words.remove(element) } }
[ { "class_path": "gabriaraujo__scrabble__9623ecc/com/exemple/scrabble/Trie.class", "javap": "Compiled from \"Trie.kt\"\npublic final class com.exemple.scrabble.Trie {\n public static final com.exemple.scrabble.Trie INSTANCE;\n\n public static final int alphabet;\n\n private static com.exemple.scrabble.Tri...
StarWishsama__Comet-Bot__19ed20e/comet-utils/src/main/kotlin/ren/natsuyuk1/comet/utils/string/FuzzyMatch.kt
package ren.natsuyuk1.comet.utils.string import java.math.BigDecimal import java.math.RoundingMode import kotlin.math.max /** * The Levenshtein distance between two words is the minimum number of * single-character edits (insertions, deletions or substitutions) required to * change one string into the other. * * @author <NAME> * @see https://github.com/tdebatty/java-string-similarity#levenshtein */ fun levenshteinDistance(s1: String, s2: String, limit: Int = Int.MAX_VALUE): Double { if (s1 == s2) { return 0.0 } if (s1.isBlank()) { return s2.length.toDouble() } if (s2.isBlank()) { return s1.length.toDouble() } // create two work vectors of integer distances var v0 = IntArray(s2.length + 1) var v1 = IntArray(s2.length + 1) var vtemp: IntArray // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t // initialize v0 (the previous row of distances) // this row is A[0][i]: edit distance for an empty s // the distance is just the number of characters to delete from t for (i in v0.indices) { v0[i] = i } for (i in s1.indices) { // calculate v1 (current row distances) from the previous row v0 // first element of v1 is A[i+1][0] // edit distance is delete (i+1) chars from s to match empty t v1[0] = i + 1 var minv1 = v1[0] // use formula to fill in the rest of the row for (j in s2.indices) { var cost = 1 if (s1.toCharArray()[i] == s2.toCharArray()[j]) { cost = 0 } v1[j + 1] = // Cost of insertion // Cost of remove (v1[j] + 1).coerceAtMost((v0[j + 1] + 1).coerceAtMost(v0[j] + cost)) // Cost of substitution minv1 = minv1.coerceAtMost(v1[j + 1]) } if (minv1 >= limit) { return limit.toDouble() } // copy v1 (current row) to v0 (previous row) for next iteration // System.arraycopy(v1, 0, v0, 0, v0.length); // Flip references to current and previous row vtemp = v0 v0 = v1 v1 = vtemp } return v0[s2.length].toDouble() } fun ldSimilarity(s1: String, s2: String): BigDecimal { val ld = levenshteinDistance(s1, s2) return BigDecimal.ONE.minus( BigDecimal.valueOf(ld).divide(BigDecimal.valueOf(max(s1.length, s2.length).toLong()), 2, RoundingMode.HALF_UP), ) }
[ { "class_path": "StarWishsama__Comet-Bot__19ed20e/ren/natsuyuk1/comet/utils/string/FuzzyMatchKt.class", "javap": "Compiled from \"FuzzyMatch.kt\"\npublic final class ren.natsuyuk1.comet.utils.string.FuzzyMatchKt {\n public static final double levenshteinDistance(java.lang.String, java.lang.String, int);\n ...
NextTurnGames__Wordle__5e0f21a/src/main/kotlin/Main.kt
package games.nextturn import java.io.File import java.lang.RuntimeException var allWords = setOf<String>() var commonWords = setOf<String>() fun main() { loadWords() println("Available choices:") println("[1] Input grades (use as aide)") println("[2] Test against random word") println("[3] Test against input word") println("[4] Find best first guess") println("[5] Build cheat sheet") println("[6] Test all words") print("Enter choice > ") val highSelection = 6 var menuChoice = 0 while (menuChoice < 1 || menuChoice > highSelection) { try { menuChoice = readLine()?.toInt() ?: 0 } catch (ex: Exception) { println("Please make a selection between 1 and $highSelection") } } when (menuChoice) { 1 -> runAide() 2 -> runTest(null) 3 -> testAnswer() 4 -> bestFirstGuess() 5 -> buildCheatSheet() 6 -> testAllWords() } } fun runAide() { val remaining = allWords.toMutableSet() var tries = 0 var guess = "lares" var grade = 1 while (grade != 0 && remaining.size > 0) { println("There are still ${remaining.size} possible words left") tries++ var gradeIn = "" println("Guessing $guess") while (gradeIn.length != 5 && gradeIn.filter { listOf('.', 'c', 'W').contains(it) }.length != 5) { print(" Grade? > ") gradeIn = readLine() ?: "" if (gradeIn == "p") { for (w in remaining) { println(w) } } if (gradeIn.length != 5 && gradeIn.filter { listOf('.', 'c', 'W').contains(it) }.length != 5) { println("Grade must be 5 characters. Use '.' for not in answer, 'w' for wrong sport and 'C' for Correct") } } grade = stringToGrade(gradeIn) remaining.removeIf { !checkWord(guess, it, grade) } guess = bestGuess(remaining) } println("Word is $guess, took $tries tries") } fun runTest(input: String?) { val answer = input ?: allWords.random() println("Testing for the answer $answer") val remaining = allWords.toMutableSet() var tries = 1 var guess = "lares" while (guess != answer && remaining.size > 0) { tries++ val grade = gradeWord(guess, answer) println("Guessing $guess, scored a ${prettyGrade(grade)}") remaining.removeIf { !checkWord(guess, it, grade) } println("There are ${remaining.size} potential words left") guess = bestGuess(remaining) } println("Word is $guess, took $tries tries") } fun testAnswer() { var answer = "" while (answer.length != 5 || !allWords.contains(answer)) { print("Enter answer > ") answer = readLine() ?: "" if (answer.length != 5 || !allWords.contains(answer)) { println("Please enter a valid 5 letter word") } } runTest(answer) } fun bestFirstGuess() { val rankedWords = allWords.associateWith { guess -> var totalRemaining = 0L for (answer in allWords) { val grade = gradeWord(guess, answer) totalRemaining += allWords.filter { checkWord(guess, it, grade) }.size } println("$guess scored a ${totalRemaining.toFloat() / allWords.size}") File("results.txt").appendText("$guess scored a ${totalRemaining.toFloat() / allWords.size}\n") totalRemaining } println(); println(); println(); println(); println() println("RESULTS - ") val sorted = rankedWords.toList().sortedBy { it.second } for (result in sorted) { println("${result.first} - ${result.second.toFloat() / allWords.size}") File("sorted.txt").appendText("${result.first} - ${result.second.toFloat() / allWords.size}\n") } } fun buildCheatSheet() { val first = getValidWord() for (l1 in 0..2) { for (l2 in 0..2) { for (l3 in 0..2) { for (l4 in 0..2) { for (l5 in 0..2) { val grade = (l1 shl 8) or (l2 shl 6) or (l3 shl 4) or (l4 shl 2) or l5 val remaining = allWords.filter { checkWord(first, it, grade) } if (remaining.isNotEmpty()) { val best = bestGuess(remaining = remaining.toSet()) println("${prettyGrade(grade)} - $best") File("$first.txt").appendText("${prettyGrade(grade)} - $best\n") } } } } } } } fun bestGuess(remaining: Set<String>): String { var best = "" var bestTotal = Long.MAX_VALUE for (guess in remaining) { var totalRemaining = 0L for (answer in remaining) { val grade = gradeWord(guess, answer) totalRemaining += remaining.filter { checkWord(guess, it, grade) }.size if (totalRemaining > bestTotal) break } if (totalRemaining < bestTotal) { bestTotal = totalRemaining best = guess } } return best } fun prettyGrade(grade: Int): String { var retval = "" for (i in 8 downTo 0 step 2) { retval += when ((grade shr i) and 3) { 0 -> "C" 1 -> "w" 2 -> "." else -> throw RuntimeException("Invalid grade sent in") } } return retval } fun stringToGrade(input: String): Int { if (input.length != 5) throw RuntimeException("Invalid grade input") var grade = 0 for (i in input) { grade = grade shl 2 grade += when (i) { 'C' -> 0 'w' -> 1 '.' -> 2 else -> throw RuntimeException("Invalid grade input") } } return grade } fun loadWords() { val uncommon = mutableSetOf<String>() val common = mutableSetOf<String>() File("assets/wordlists/uncommon.txt").forEachLine { uncommon.add(it) } File("assets/wordlists/common.txt").forEachLine { common.add(it) } commonWords = common.toSet() allWords = uncommon union common } // TODO - This doesn't do repeat letters correctly. Still works, just not optimal fun gradeWord(guess: String, answer: String) : Int { // Return 5 sets of 2 bits // 00 - Correct // 01 - Wrong spot // 10 - Not in string var total = 0 for (i in 0 until 5) { total = total shl 2 val thisSpot = when { guess[i] == answer[i] -> 0 answer.contains(guess[i]) -> 1 else -> 2 } total += thisSpot } return total } fun checkWord(guess: String, answer: String, grade: Int) : Boolean { return gradeWord(guess, answer) == grade } fun getValidWord(remaining: Set<String> = allWords): String { var word = "" while (word.length != 5 || !remaining.contains(word)) { print("Enter word > ") word = readLine() ?: "" if (word.length != 5 || !allWords.contains(word)) { println("Please enter a valid 5 letter word") } } return word } fun getSecondGuesses(first: String): Map<Int, String> { val seconds = mutableMapOf<Int, String>() val lines = File("$first.txt").readLines() for (line in lines) { val grade = stringToGrade(line.substring(0, 5)) seconds[grade] = line.substring(8, 13) } return seconds } fun testAllWords() { val first = getValidWord() val seconds = getSecondGuesses(first) val totalTries = IntArray(20) { 0 } for (answer in allWords) { println("Testing for the answer $answer") val remaining = allWords.toMutableSet() // First guess var tries = 1 var guess = first if (answer != guess) { val grade = gradeWord(guess, answer) remaining.removeIf { !checkWord(guess, it, grade) } guess = seconds[grade] ?: throw Exception("Second word not found for ${prettyGrade(grade)}") tries++ } while (guess != answer && remaining.size > 0) { val grade = gradeWord(guess, answer) remaining.removeIf { !checkWord(guess, it, grade) } guess = bestGuess(remaining) tries++ } totalTries[tries]++ println("Word is $guess, took $tries tries") } for (i in 0 until 20) { println("Number of words in $i tries: ${totalTries[i]}, ${totalTries[i].toFloat() * 100.0f / allWords.size.toFloat()}%") } }
[ { "class_path": "NextTurnGames__Wordle__5e0f21a/games/nextturn/MainKt$bestFirstGuess$$inlined$sortedBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class games.nextturn.MainKt$bestFirstGuess$$inlined$sortedBy$1<T> implements java.util.Comparator {\n public games.nextturn.MainKt$bestFi...
fifth-postulate__parser-combinators__61f2c62/presentation/javagilde/code/src/main/kotlin/javagilde/final.kt
package javagilde // We willen expressies parsen, d.w.z 5*2 + 1 sealed class Expression { abstract fun evaluate(): Int } data class Multiplication(val left: Expression, val right: Expression): Expression() { override fun evaluate(): Int = left.evaluate() * right.evaluate() } data class Addition(val left: Expression, val right: Expression) : Expression() { override fun evaluate(): Int = left.evaluate() + right.evaluate() } data class Constant(val value: Int): Expression() { override fun evaluate(): Int = value } typealias Parser<T> = (String) -> List<Pair<T, String>> fun parserA(input: String): List<Pair<Char, String>> { return if (input.startsWith('A')) { listOf('A' to input.drop(1)) } else { emptyList() }} fun character(target: Char): Parser<Char> = { input: String -> if (input.startsWith(target)) { listOf( target to input.drop(1)) } else { emptyList() } } //val parserA = character('A') fun satisfy(predicate: (Char) -> Boolean): Parser<Char> = { input: String -> if (input.length > 0 && predicate(input[0])) { listOf(input[0] to input.drop(1)) } else { emptyList() } } val parserAorB = satisfy { it == 'A' || it == 'B'} fun <T> or(p: Parser<T>, q: Parser<T>): Parser<T> = { input -> // How to implement? p(input) + q(input) } infix fun <T> Parser<T>.`|||`(p: Parser<T>): Parser<T> = or(this, p) fun <S, T> and(p: Parser<S>, q: Parser<T>): Parser<Pair<S,T>> = {input -> p(input) .flatMap { (s, intermediate) -> q(intermediate).map { (t, rest) -> (s to t) to rest } } } infix fun <S, T> Parser<S>.`|&|`(p: Parser<T>): Parser<Pair<S, T>> = and(this, p) fun <S, T> map(p: Parser<S>, transform: (S) -> T): Parser<T> = { input -> p(input) .map {(s, rest) -> transform(s) to rest } } infix fun <S, T> Parser<S>.`&|`(p: Parser<T>): Parser<T> = map(and(this, p)) {(_, t) -> t} infix fun <S, T> Parser<S>.`|&`(p: Parser<T>): Parser<S> = map(and(this, p)) {(s, _) -> s} fun <T> succeed(result: T): Parser<T> = {input -> listOf( result to input ) } fun <T> lazy(p: () -> Parser<T>): Parser<T> = { input -> p()(input) } fun <T> many(p: Parser<T>): Parser<List<T>> = or( map(and(p, lazy {many(p)})) { (r, rs) -> listOf(r) + rs}, succeed(emptyList()) ) fun <T> many1(p: Parser<T>): Parser<List<T>> = map(p `|&|` many(p)) {(r,rs) -> listOf(r) + rs} val digit: Parser<Int> = map(satisfy { c -> c in '0' .. '9'}) { it - '0' } val number: Parser<Int> = map(many1(digit)) { it.fold(0) {acc, d -> 10*acc + d} } val constant: Parser<Expression> = map(number) {n -> Constant(n)} fun multiplication(): Parser<Expression> = constant `|||` map(constant `|&` character('*') `|&|` lazy(::multiplication)) { (left, right) -> Multiplication(left, right) } fun addition(): Parser<Expression> = multiplication() `|||` map(multiplication() `|&` character('+') `|&|` lazy(::addition)) { (left, right) -> Addition(left, right) } fun expression() : Parser<Expression> = addition() fun <T> just(p: Parser<T>): Parser<T> = {input -> p(input) .filter {(_, rest) -> rest.isEmpty() } } fun <T> parse(parser: Parser<T>, input: String): T? = just(parser)(input).get(0).first fun main() { // 5*2 + 1 val expr = parse(expression(), "5*2+1")//Addition(Multiplication(Constant(5), Constant(2)), Constant(1)) println(expr) println(expr!!.evaluate()) }
[ { "class_path": "fifth-postulate__parser-combinators__61f2c62/javagilde/FinalKt$addition$1.class", "javap": "Compiled from \"final.kt\"\nfinal class javagilde.FinalKt$addition$1 extends kotlin.jvm.internal.FunctionReferenceImpl implements kotlin.jvm.functions.Function0<kotlin.jvm.functions.Function1<? super...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day4/Day4.kt
package day4 class Day4 { fun getOrganizer(filename: String): SupplyOrganizer { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return SupplyOrganizer(readLines) } } class SupplyOrganizer(input: List<String>) { val elfPairs = input.map { ElfPair(it) } val fullyContained = elfPairs.count { it.fullyContains } val overlapped = elfPairs.count { it.overlaps } } data class ElfPair(val input: String) { private val firstSection = AssignedSection(input.split(",").first()) private val secondSection = AssignedSection(input.split(",").last()) val fullyContains = firstSection.sections.intersect(secondSection.sections) == firstSection.sections || secondSection.sections.intersect(firstSection.sections) == secondSection.sections val overlaps = firstSection.sections.intersect(secondSection.sections).isNotEmpty() override fun toString(): String { return "ElfPair[${firstSection.range}][${secondSection.range}][fullyContains=$fullyContains][overlaps=$overlaps]" } } data class AssignedSection(val input: String) { val from = input.split("-")[0].toInt() val to = input.split("-")[1].toInt() val range = (from..to) val sections = range.toSet() override fun toString(): String { return "AssignedSection[$range]" } } fun main() { val organizerTest = Day4().getOrganizer("/day4_test.txt") val organizerInput = Day4().getOrganizer("/day4_input.txt") //println("elfpairs: ${organizerTest.elfPairs}") organizerInput.elfPairs.filter { !it.fullyContains }.forEach { println(it)} println("Part 1 test: ${organizerTest.fullyContained}") println("Part 1 input: ${organizerInput.fullyContained}") println("Part 1 test: ${organizerTest.overlapped}") println("Part 1 input: ${organizerInput.overlapped}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day4/Day4.class", "javap": "Compiled from \"Day4.kt\"\npublic final class day4.Day4 {\n public day4.Day4();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n pu...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day3/Day3.kt
package day3 class Day3 { fun getOrganizer(filename: String): RucksackOrganizer { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return RucksackOrganizer(readLines) } } data class RucksackOrganizer(val input: List<String>) { val rucksacks = input.map { Rucksack(it) } val elfGroups = createElfGroups(listOf(), rucksacks) private fun createElfGroups(accumulator: List<ElfGroup>, input: List<Rucksack>): List<ElfGroup> { if (input.isEmpty()) return accumulator return createElfGroups(accumulator + ElfGroup(input.take(3)), input.drop(3)) } val part1Score = rucksacks.sumOf { it.score() } val part2Score = elfGroups.sumOf { it.score() } } data class ElfGroup(val rucksacks: List<Rucksack>) { val badge = rucksacks[0].types.intersect(rucksacks[1].types).intersect(rucksacks[2].types).first() fun score() = badge.day3Score() override fun toString(): String { return "[${rucksacks[0].input}][${rucksacks[1].input}][${rucksacks[2].input}][badge=$badge]" } } data class Rucksack(val input: String) { private val compartment1 = input.take(input.length / 2) private val compartment2 = input.takeLast(input.length / 2) private val duplicate = compartment1.toList().toSet().intersect(compartment2.toList().toSet()).first() val types = input.toList().toSet() fun score(): Int { return duplicate.day3Score() } override fun toString(): String { return "[Compartment1=$compartment1][Compartment2 = $compartment2][duplicate = $duplicate][score = ${score()}]" } } fun Char.day3Score(): Int { return if (this.isLowerCase()) { this.toInt() - 96 } else { this.toInt() - 38 } } fun main() { val rucksackOrganizerTest = Day3().getOrganizer("/day3_test.txt") val rucksackOrganizerInput = Day3().getOrganizer("/day3_input.txt") //rucksackOrganizer.rucksacks.forEach { println(it) } println("Part 1 score: ${rucksackOrganizerTest.part1Score}") println("Part 1 score: ${rucksackOrganizerInput.part1Score}") println("Part 2 score: ${rucksackOrganizerTest.part2Score}") println("Part 2 score: ${rucksackOrganizerInput.part2Score}") //println("ElfGroups: ${rucksackOrganizerTest.elfGroups}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day3/Day3.class", "javap": "Compiled from \"Day3.kt\"\npublic final class day3.Day3 {\n public day3.Day3();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n pu...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day2/Day2.kt
package day2 import java.lang.IllegalArgumentException class Day2 { fun getGameStore(filename: String): GameStore { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return GameStore( readLines.map { Round(Shape.fromString(it[0]), Shape.fromString(it[2])) }, readLines.map { Round(Shape.fromString(it[0]), Shape.fromStringv2(Shape.fromString(it[0]), it[2])) } ) } } sealed class Shape { abstract fun score(): Int abstract fun winShape(): Shape abstract fun drawShape(): Shape abstract fun loseShape(): Shape object Rock: Shape() { override fun score(): Int = 1 override fun winShape(): Shape = Paper override fun drawShape(): Shape = Rock override fun loseShape(): Shape = Scissors } object Paper: Shape() { override fun score(): Int = 2 override fun winShape(): Shape = Scissors override fun drawShape(): Shape = Paper override fun loseShape(): Shape = Rock } object Scissors: Shape() { override fun score(): Int = 3 override fun winShape(): Shape = Rock override fun drawShape(): Shape = Scissors override fun loseShape(): Shape = Paper } companion object { fun fromString(input: Char): Shape { return when(input) { 'A' -> Rock 'B' -> Paper 'C' -> Scissors 'Y' -> Paper 'X' -> Rock 'Z' -> Scissors else -> throw IllegalArgumentException("Unknown shape $input") } } fun fromStringv2(opponent: Shape, input: Char): Shape { return when(input) { 'Y' -> opponent.drawShape() 'X' -> opponent.loseShape() 'Z' -> opponent.winShape() else -> throw IllegalArgumentException("Unknown shape $input") } } } } class Round(private val opponent: Shape, private val you: Shape) { override fun toString(): String { return "$opponent vs $you" } private fun shapeScore(): Int = you.score() private fun roundScore(): Int { return when(opponent) { Shape.Paper -> when(you) { Shape.Paper -> 3 Shape.Rock -> 0 Shape.Scissors -> 6 } Shape.Rock -> when(you) { Shape.Paper -> 6 Shape.Rock -> 3 Shape.Scissors -> 0 } Shape.Scissors -> when(you) { Shape.Paper -> 0 Shape.Rock -> 6 Shape.Scissors -> 3 } } } fun score(): Int = roundScore() + shapeScore() } class GameStore(val roundList: List<Round>, val roundListPart2: List<Round>) { fun score(): Int = roundList.sumOf { it.score() } fun scorePart2(): Int = roundListPart2.sumOf { it.score() } } fun main() { println(Day2().getGameStore("/day2_test.txt").score()) println(Day2().getGameStore("/day2_input.txt").score()) println(Day2().getGameStore("/day2_test.txt").scorePart2()) println(Day2().getGameStore("/day2_input.txt").scorePart2()) }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day2/Day2.class", "javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2 {\n public day2.Day2();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n pu...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day5/Day5.kt
package day5 class Day5 { fun getOrganizer(filename: String): CrateOrganizer { val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines() return CrateOrganizer(readLines) } } /* [N] [C] [Z] [Q] [G] [V] [S] [V] [L] [C] [M] [T] [W] [L] [S] [H] [L] [C] [D] [H] [S] [C] [V] [F] [D] [D] [B] [Q] [F] [Z] [T] [Z] [T] [C] [J] [G] [S] [Q] [P] [P] [C] [W] [W] [F] [W] [J] [C] [T] [L] [D] [G] [P] [P] [V] [N] [R] 1 2 3 4 5 6 7 8 9 stackNumber 1 => 0-2 2 => 4-6 3 => 8-10 4 => 12-14 5 => 16-18 6 => 20-22 7 => 24-26 8 => 28-30 9 => 32-34 */ data class CrateOrganizer(val input: List<String>) { val stackSize: Int val stacks: Map<Int, Stack> val commands: List<Command> init { println(input.first { it.startsWith(" 1 ") }.trim().replace("\\s{2,}".toRegex(), " ").split(" ")) // 1 2 3 4 5 6 7 8 9 ==> 1 2 3 4 5 6 7 8 9 ==> 9 stackSize = input.first { it.startsWith(" 1 ") }.trim().replace("\\s{2,}".toRegex(), " ").split(" ").size val cratesInput = input.takeWhile { !it.startsWith( " 1 ") } println(cratesInput) stacks = (1..stackSize) .map { stackNumber -> cratesInput.map { it.substring((stackNumber-1)*4, (stackNumber-1)*4 + 2) } } .map { crateInput -> crateInput.mapNotNull { Crate.fromString(it) }} .map { Stack(it) } .withIndex().associateBy({it.index + 1}, {it.value}) commands = input.takeLastWhile { it.startsWith("move") }.map { Command.fromString(it) } } fun organizeWithCrateMover9000(): Stacks { return Stacks(commands.fold(stacks) { acc, command -> performCommand9000(acc, command) }) } fun organizeWithCrateMover9001(): Stacks { return Stacks(commands.fold(stacks) { acc, command -> performCommand9001(acc, command) }) } private fun performCommand9000(stacks: Map<Int, Stack>, command: Command): Map<Int, Stack> { if (command.repetitions == 0) return stacks //println("Moving ${command.repetitions} from ${command.from} to ${command.to}") val fromStack = stacks[command.from]!! val toStack = stacks[command.to]!! val movedCrates = fromStack.crates.take(1) val outputStack = stacks.toMutableMap() outputStack[command.from] = Stack(fromStack.crates.drop(1)) outputStack[command.to] = Stack(movedCrates + toStack.crates) //println("Operation resulted in $outputStack") return performCommand9000(outputStack, Command(repetitions = command.repetitions -1, from = command.from, to = command.to)) } private fun performCommand9001(stacks: Map<Int, Stack>, command: Command): Map<Int, Stack> { //println("Moving ${command.repetitions} from ${command.from} to ${command.to}") val fromStack = stacks[command.from]!! val toStack = stacks[command.to]!! val movedCrates = fromStack.crates.take(command.repetitions) val outputStack = stacks.toMutableMap() outputStack[command.from] = Stack(fromStack.crates.drop(command.repetitions)) outputStack[command.to] = Stack(movedCrates + toStack.crates) //println("Operation resulted in $outputStack") return outputStack } } data class Stacks(val input: Map<Int, Stack>) { val topCrates = input.entries.sortedBy { it.key }.map { it.value }.map {it.topCrate()}.map { it.value }.joinToString("") } data class Stack(val crates: List<Crate>) { fun topCrate(): Crate = crates[0] override fun toString(): String { return crates.toString() } } data class Crate(val value: Char) { override fun toString(): String { return "[$value]" } companion object { fun fromString(input: String): Crate? { if (input.isNullOrBlank()) return null return Crate(input[1]) } } } data class Command(val repetitions: Int, val from: Int, val to: Int) { override fun toString(): String { return "[repetitions=$repetitions][from=$from][to=$to]" } companion object { fun fromString(input: String): Command { val parts = input.split(" ") val repetitions = parts[1].toInt() val from = parts[3].toInt() val to = parts[5].toInt() return Command(repetitions, from, to) } } } fun main() { val testOrganizer = Day5().getOrganizer("/day5_test.txt") val inputOrganizer = Day5().getOrganizer("/day5_input.txt") println("Test stacks: ${testOrganizer.stackSize}") println("Test stacks: ${testOrganizer.stacks}") println("Test stacks: ${testOrganizer.commands}") val resultingStacks = testOrganizer.organizeWithCrateMover9000() println("Test stacks top crates: ${resultingStacks.topCrates}") val inputResultingStacks = inputOrganizer.organizeWithCrateMover9000() println("Input stacks top crates: ${inputResultingStacks.topCrates}") val resultingStacks9001 = testOrganizer.organizeWithCrateMover9001() println("Test stacks top crates: ${resultingStacks9001.topCrates}") val inputResultingStacks9001 = inputOrganizer.organizeWithCrateMover9001() println("Input stacks top crates: ${inputResultingStacks9001.topCrates}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day5/Day5.class", "javap": "Compiled from \"Day5.kt\"\npublic final class day5.Day5 {\n public day5.Day5();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4: return\n\n pu...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day7/Day7.kt
package day7 import day6.Day6 class Day7(input: List<String>) { val commands = parseCommands(listOf(), input) private val pathMap = buildMap() private fun parseCommands(initial: List<Command>, input: List<String>): List<Command> { if (input.isEmpty()) return initial val line = input.first().split(" ") val commandInput = line[1] val tail = input.drop(1) if (commandInput == "cd") return parseCommands(initial + Command.Cd(line[2]), tail) if (commandInput == "ls") { val results = tail.takeWhile { !it.startsWith("$") } return parseCommands(initial + Command.Ls(results), tail.drop(results.size)) } println("Should not reach this..?") return initial } private fun buildMap(): Map<String, Pair<Int, List<String>>> { val resultMap = mutableMapOf<String, Pair<Int, List<String>>>() var currentDir: List<String> = listOf() commands.forEach { when (it) { is Command.Cd -> { currentDir = when (it.path) { "/" -> { listOf() } ".." -> { currentDir.dropLast(1) } else -> { currentDir.plus(it.path) } } } is Command.Ls -> { val currnetPath = computePath(currentDir) val dirs = it.result.filter { c -> c.startsWith("dir") }.map { c -> c.split(" ")[1] }.map { path -> computePath(currentDir + path) } val size = it.result.filter { c -> !c.startsWith("dir") }.map { c -> c.split(" ")[0].toInt() }.sum() resultMap[currnetPath] = Pair(size, dirs) } } } return resultMap } private fun computePath(currentDir: List<String>): String { if (currentDir.isEmpty()) return "/" return "/" + currentDir.joinToString("/") } fun part1(): Int { val scoreMap = scoreMap() return scoreMap.filter { it.second < 100000 }.sumOf { it.second } } private fun scoreMap(): List<Pair<String, Int>> { return pathMap.keys.map { it to computeScore(it) } } fun part2(): Int { val totalSpace = 70000000 val neededSpace = 30000000 val usedSpace = computeScore("/") val availableSpace = totalSpace - usedSpace val toBeDeleted = neededSpace - availableSpace //println("UsedSpace = $usedSpace, toBeDeleted=$toBeDeleted") return scoreMap().map { it.second }.filter { it > toBeDeleted }.minBy { it } } private fun computeScore(path: String): Int { val pathScore = pathMap[path]!! val dirScore = pathScore.first val subdirScore = pathScore.second.sumOf { computeScore(it) } return dirScore.plus(subdirScore) } } sealed class Command { data class Cd(val path: String): Command() data class Ls(val result: List<String>): Command() } fun main() { val testInput = Day6::class.java.getResourceAsStream("/day7_test.txt").bufferedReader().readLines() val input = Day6::class.java.getResourceAsStream("/day7_input.txt").bufferedReader().readLines() val day7Test = Day7(testInput) // println(day7Test.commands) // println(day7Test.buildMap()) println("Part 1 test answer: ${day7Test.part1()}") println("Part 2 test answer: ${day7Test.part2()}") val day7Input = Day7(input) // println(day7Input.commands) // println(day7Input.buildMap()) println("Part 1 answer: ${day7Input.part1()}") println("Part 2 answer: ${day7Input.part2()}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day7/Day7.class", "javap": "Compiled from \"Day7.kt\"\npublic final class day7.Day7 {\n private final java.util.List<day7.Command> commands;\n\n private final java.util.Map<java.lang.String, kotlin.Pair<java.lang.Integer, java.util.List<java.lang.St...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day9/Day9.kt
package day9 import java.lang.IllegalArgumentException class Day9(val input: List<String>) { private val board = Board(Point(0, 0), Point(0, 0), Point(0, 0), mapOf()) private val rope = (1..10).map { Point(0, 0) }.toMutableList() private val board2 = Board2(Point(0, 0), rope, mutableMapOf()) private fun toCommandList(input: String): List<Command> { val direction = input.split(" ")[0] val repetitions = input.split(" ")[1].toInt() return when (direction) { "U" -> (1..repetitions).map { Command.Up(1) } "D" -> (1..repetitions).map { Command.Down(1) } "L" -> (1..repetitions).map { Command.Left(1) } "R" -> (1..repetitions).map { Command.Right(1) } else -> { throw IllegalArgumentException() } } } fun part1(): Int { val resultingBoard = input.flatMap { toCommandList(it) } .fold(board) { board, command -> board.handleCommand(command) } return resultingBoard.tailVisitationMap.size } fun part2(): Int { val resultingBoard = input.flatMap { toCommandList(it) } .fold(board2) { board2, command -> board2.handleCommand(command) } return resultingBoard.tailVisitationMap.size } } data class Board(val start: Point, val head: Point, val tail: Point, val tailVisitationMap: Map<Point, Int>) { fun handleCommand(command: Command): Board { when (command) { is Command.Down -> { val newHead = Point(head.x, head.y - 1) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Left -> { val newHead = Point(head.x - 1, head.y) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Right -> { val newHead = Point(head.x + 1, head.y) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } is Command.Up -> { val newHead = Point(head.x, head.y + 1) val newTail = calculateTail(newHead, tail) val count = tailVisitationMap[newTail] ?: 0 return this.copy( head = newHead, tail = newTail, tailVisitationMap = tailVisitationMap + (newTail to count + 1) ) } } } } data class Board2(val start: Point, val points: MutableList<Point>, val tailVisitationMap: MutableMap<Point, Int>) { fun handleCommand(command: Command): Board2 { when (command) { is Command.Down -> { points[0] = Point(points[0].x, points[0].y - 1) calculate() return this } is Command.Left -> { points[0] = Point(points[0].x - 1, points[0].y) calculate() return this } is Command.Right -> { points[0] = Point(points[0].x + 1, points[0].y) calculate() return this } is Command.Up -> { points[0] = Point(points[0].x, points[0].y + 1) calculate() return this } } } private fun calculate() { for (i in 1 until points.size) { points[i] = calculateTail(points[i - 1], points[i]) } tailVisitationMap.compute(points.last()) { _, oldValue -> (oldValue ?: 0) + 1 } } } private fun calculateTail(newHead: Point, existingTail: Point): Point { if (newHead == existingTail) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x && newHead.y == existingTail.y + 1) return existingTail if (newHead.x == existingTail.x && newHead.y == existingTail.y - 1) return existingTail if (newHead.x == existingTail.x + 1 && newHead.y == existingTail.y) return existingTail if (newHead.x == existingTail.x - 1 && newHead.y == existingTail.y) return existingTail // same column if (newHead.x == existingTail.x) { // Only one space apart if (newHead.y == existingTail.y + 1 || newHead.y == existingTail.y - 1) { return existingTail } return if (newHead.y > existingTail.y) { Point(existingTail.x, existingTail.y + 1) } else { Point(existingTail.x, existingTail.y - 1) } } if (newHead.y == existingTail.y) { // same row if (newHead.x == existingTail.x + 1 || newHead.x == existingTail.x - 1) { return existingTail } return if (newHead.x > existingTail.x) { Point(existingTail.x + 1, existingTail.y) } else { Point(existingTail.x - 1, existingTail.y) } } // neither on same row nor column /* ..... ..... ...H. ...H. ..... -> ...T. ..T.. ..... ..... ..... */ if (newHead.x > existingTail.x && newHead.y > existingTail.y) return Point(existingTail.x + 1, existingTail.y + 1) if (newHead.x < existingTail.x && newHead.y > existingTail.y) return Point(existingTail.x - 1, existingTail.y + 1) return if (newHead.x > existingTail.x) { Point(existingTail.x + 1, existingTail.y - 1) } else { Point(existingTail.x - 1, existingTail.y - 1) } } sealed class Command { abstract val repetitions: Int data class Up(override val repetitions: Int) : Command() data class Down(override val repetitions: Int) : Command() data class Left(override val repetitions: Int) : Command() data class Right(override val repetitions: Int) : Command() } data class Point(val x: Int, val y: Int) fun main() { val testInput = Day9::class.java.getResourceAsStream("/day9_test.txt").bufferedReader().readLines() val test2Input = Day9::class.java.getResourceAsStream("/day9_test2.txt").bufferedReader().readLines() val input = Day9::class.java.getResourceAsStream("/day9_input.txt").bufferedReader().readLines() val day9test = Day9(testInput) val day9test2 = Day9(test2Input) val day9input = Day9(input) println("Day9 part 1 test result: ${day9test.part1()}") println("Day9 part 1 result: ${day9input.part1()}") println("Day9 part 2 test result: ${day9test2.part2()}") println("Day9 part 2 result: ${day9input.part2()}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day9/Day9Kt.class", "javap": "Compiled from \"Day9.kt\"\npublic final class day9.Day9Kt {\n private static final day9.Point calculateTail(day9.Point, day9.Point);\n Code:\n 0: aload_0\n 1: aload_1\n 2: invokestatic #12 ...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day8/Day8.kt
package day8 class Day8(val input: List<String>) { private val transposed = transpose(input) val inputInts = input.map { it.toCharArray().map { it.digitToInt() } } val transposedInts = transposed.map { it.toCharArray().map { it.digitToInt() } } val visibleFromLeft = input.mapIndexed { rowNo, row -> visibleFromStart(rowNo, row) }.flatten().toSet() val visibleFromRight = input.mapIndexed { rowNo, row -> visibleFromEnd(rowNo, row) }.flatten().toSet() val visibleFromTop = transposed.mapIndexed { rowNo, row -> visibleFromTop(rowNo, row) }.flatten().toSet() val visibleFromBottom = transposed.mapIndexed { rowNo, row -> visibleFromBottom(rowNo, row) }.flatten().toSet() fun visibleFromStart(rowNo: Int, row: String): Set<Pair<Int, Int>> { if (row.isBlank()) return setOf() val rowInfo = row.foldIndexed(RowInfo(rowNo, -1, setOf())) { index, rowInfo, char -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(rowNo, it) }.toSet() } fun visibleFromEnd(rowNo: Int, row: String): Set<Pair<Int, Int>> { if (row.isBlank()) return setOf() val rowInfo = row.foldRightIndexed(RowInfo(rowNo, -1, setOf())) { index, char, rowInfo -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(rowNo, it) }.toSet() } fun visibleFromTop(colNo: Int, col: String): Set<Pair<Int, Int>> { if (col.isBlank()) return setOf() val rowInfo = col.foldIndexed(RowInfo(colNo, -1, setOf())) { index, rowInfo, char -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(it, colNo) }.toSet() } fun visibleFromBottom(colNo: Int, col: String): Set<Pair<Int, Int>> { if (col.isBlank()) return setOf() val rowInfo = col.foldRightIndexed(RowInfo(colNo, -1, setOf())) { index, char, rowInfo -> rowInfo.add(char, index) } return rowInfo.positions.map { Pair(it, colNo) }.toSet() } fun part1(): Int { val union = visibleFromLeft.union(visibleFromRight).union(visibleFromTop).union(visibleFromBottom) println("Union: ${union.sortedWith(compareBy<Pair<Int, Int>> { it.first }.thenBy { it.second })}") return union.size } val pairs = (input.indices).map { column -> (transposed.indices).map { row -> Pair(row, column) } }.flatten() fun part2(): Int { val associateWith = pairs.associateWith { sightLeft(it) * sightRight(it) * sightDown(it) * sightUp(it) } val entry = associateWith.maxWith { a, b -> a.value.compareTo(b.value) } println("Max pair is ${entry.key} = ${entry.value}") return entry.value } fun calculateScenicScore(pair: Pair<Int, Int>): Int { val up = sightUp(pair) val left = sightLeft(pair) val down = sightDown(pair) val right = sightRight(pair) println("[up=$up][left=$left][down=$down][right=$right]") val sum = up * left * down * right println("sum = $sum") return sum } fun sightUp(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = transposedInts[position.second].take(position.first) val count = consideredTrees.takeLastWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightDown(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = transposedInts[position.second].drop(position.first + 1) val count = consideredTrees.takeWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightRight(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = inputInts[position.first].drop(position.second + 1) val count = consideredTrees.takeWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } fun sightLeft(position: Pair<Int, Int>): Int { val height = inputInts[position.first][position.second] val consideredTrees = inputInts[position.first].take(position.second) val count = consideredTrees.takeLastWhile { it < height }.count() if (count == consideredTrees.count()) return count return count + 1 } } data class RowInfo(val rowNo: Int, val highestNumber: Int, val positions: Set<Int>) { fun add(input: Char, index: Int): RowInfo { val inputDigit = input.digitToInt() if (highestNumber == 9 || inputDigit <= highestNumber) return this return this.copy(highestNumber = inputDigit, positions = positions + index) } } private fun transpose(input: List<String>): List<String> { val columns = input.first().length - 1 return (0..columns).map { column -> input.map { string -> string[column] }.joinToString("") } } fun main() { val testInput = Day8::class.java.getResourceAsStream("/day8_test.txt").bufferedReader().readLines() val input = Day8::class.java.getResourceAsStream("/day8_input.txt").bufferedReader().readLines() val day8test = Day8(testInput) val day8input = Day8(input) println("From left: ${day8test.visibleFromLeft}") println("From right: ${day8test.visibleFromRight}") println("From top: ${day8test.visibleFromTop}") println("From bottom: ${day8test.visibleFromBottom}") println("Part 1 test result: ${day8test.part1()}") println("Part 1 result: ${day8input.part1()}") println("Part 2 test result: ${day8test.part2()}") println("Part 2 result: ${day8input.part2()}") // println(day8test.sightUp(Pair(3,2))) // println(day8test.sightLeft(Pair(3,2))) // println(day8test.sightDown(Pair(3,2))) // println(day8test.sightRight(Pair(3,2))) // // println("1,1=" + day8test.calculateScenicScore(Pair(1,1))) // println("1,2=" + day8test.calculateScenicScore(Pair(1,2))) // println("3,2=" + day8test.calculateScenicScore(Pair(3,2))) } /* abc def ghi */
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day8/Day8$part1$$inlined$compareBy$1.class", "javap": "Compiled from \"Comparisons.kt\"\npublic final class day8.Day8$part1$$inlined$compareBy$1<T> implements java.util.Comparator {\n public day8.Day8$part1$$inlined$compareBy$1();\n Code:\n ...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day6/Day6.kt
package day6 class Day6(val input: String) { private val listOfWindows = (0..input.length-4).map { input.substring(it, it+4) } private val messageMarkerWindows = (0..input.length-14).map { input.substring(it, it+14) } fun startOfPacket(): Int { return listOfWindows.indexOfFirst { !it.containsDuplicates() } + 4 } fun startOfMessage(): Int { return messageMarkerWindows.indexOfFirst { !it.containsDuplicates() } + 14 } override fun toString(): String { return input } } fun String.containsDuplicates(): Boolean { return this.toCharArray().distinct().size != this.toCharArray().size } fun main() { val test1 = Day6("mjqjpqmgbljsphdztnvjfqwrcgsmlb") val test2 = Day6("bvwbjplbgvbhsrlpgdmjqwftvncz") val test3 = Day6("nppdvjthqldpwncqszvftbrmjlhg") val test4 = Day6("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") val test5 = Day6("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") check(test1.startOfPacket() == 7) check(test2.startOfPacket() == 5) check(test3.startOfPacket() == 6) check(test4.startOfPacket() == 10) check(test5.startOfPacket() == 11) check(test1.startOfMessage() == 19) check(test2.startOfMessage() == 23) check(test3.startOfMessage() == 23) check(test4.startOfMessage() == 29) check(test5.startOfMessage() == 26) val input = Day6::class.java.getResourceAsStream("/day6_input.txt").bufferedReader().readLines().first() val day6 = Day6(input) println("Part1 = ${day6.startOfPacket()}") println("Part2 = ${day6.startOfMessage()}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day6/Day6.class", "javap": "Compiled from \"Day6.kt\"\npublic final class day6.Day6 {\n private final java.lang.String input;\n\n private final java.util.List<java.lang.String> listOfWindows;\n\n private final java.util.List<java.lang.String> messa...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day11/Day11.kt
package day11 import java.lang.IllegalArgumentException class Day11(val input: List<String>) { fun part1(): Long { val monkies = parseInput(input, true) println(monkies) val game = Game(monkies) (0 until 20).forEach { _ -> game.performRound(1) } println(game.monkies) return monkies.map { it.inspectCounter }.sortedDescending().take(2).reduce {a, b -> a*b} } fun part2(): Long { val monkies = parseInput(input, false) val lcm = monkies.map { it.divisor }.reduce { acc, i -> acc * i }.toLong() val game = Game(monkies) (0 until 10000).forEach { it -> game.performRound(lcm) } println(game.monkies) // 2147483647 // 2713310158 return monkies.map { it.inspectCounter }.sortedDescending().take(2).reduce {a, b -> a*b} } fun parseInput(input: List<String>, worryDivisor: Boolean): List<Monkey> { return input.chunked(7).map { toMonkey(it, worryDivisor) } } fun toMonkey(input: List<String>, worryDivisor: Boolean): Monkey { val id = Regex("""Monkey (\d+):""").find(input[0])!!.destructured.toList()[0].toInt() val startingItems = input[1].split(":")[1].trim().split(",").map { it.trim().toLong() }.toMutableList() val operationValues = "Operation: new = old ([*+]) ([a-zA-Z0-9]+)".toRegex().find(input[2])!!.destructured.toList() val operation = Operation.create(operationValues) val divisor = "Test: divisible by ([0-9]+)".toRegex().find(input[3])!!.destructured.toList()[0].toInt() val trueMonkey = "If true: throw to monkey ([0-9]+)".toRegex().find(input[4])!!.destructured.toList()[0].toInt() val falseMonkey = "If false: throw to monkey ([0-9]+)".toRegex().find(input[5])!!.destructured.toList()[0].toInt() return Monkey(id, startingItems, divisor, worryDivisor, operation::calculate) { input -> if (input) { trueMonkey } else { falseMonkey } } } } sealed class Operation { abstract fun calculate(old: Long): Long data class MultiplyWithNumber(val number: Long): Operation() { override fun calculate(old: Long): Long { return old * number } } object MultiplyWithOld: Operation() { override fun calculate(old: Long): Long { return old * old } } data class PlusWithNumber(val number: Long): Operation() { override fun calculate(old: Long): Long { return old + number } } object PlusWithOld: Operation() { override fun calculate(old: Long): Long { return old + old } } companion object { fun create(operationValues: List<String>): Operation { val operand = operationValues[0] val factor = operationValues[1] return when (operand) { "*" -> if (factor == "old") { MultiplyWithOld } else { MultiplyWithNumber(factor.toLong()) } "+" -> if (factor == "old") { PlusWithOld } else { PlusWithNumber(factor.toLong()) } else -> throw IllegalArgumentException("could not parse operation: $operationValues") } } } } class Game(val monkies: List<Monkey>) { fun performRound(lcm: Long) { monkies.forEach { it.performAction(monkies, lcm) } } } class Monkey( val id: Int, val items: MutableList<Long>, val divisor: Int, val worryDivisor: Boolean, val operation: (Long) -> Long, val monkeyChooser: (Boolean) -> Int ) { var inspectCounter = 0L fun performAction(monkies: List<Monkey>, lcm: Long) { val iterator = items.iterator() while (iterator.hasNext()) { inspectCounter++ val item = iterator.next() val newWorryLevel = operation.invoke(item) val boredWorryLevel = if (worryDivisor) { newWorryLevel / 3 } else { newWorryLevel % lcm } val monkeyReceiverId = monkeyChooser.invoke(boredWorryLevel % divisor == 0L) monkies[monkeyReceiverId].receive(boredWorryLevel) iterator.remove() } } fun receive(value: Long) { items.add(value) } override fun toString(): String { return "Monkey$id: inpsectCounter=$inspectCounter. '${items}'" } } fun main() { val testInput = Day11::class.java.getResourceAsStream("/day11_test.txt").bufferedReader().readLines() val input = Day11::class.java.getResourceAsStream("/day11_input.txt").bufferedReader().readLines() val day11test = Day11(testInput) val day11input = Day11(input) println("Day11 part 1 test result: ${day11test.part1()}") println("Day11 part 1 result: ${day11input.part1()}") println("Day11 part 2 test result: ${day11test.part2()}") println("Day11 part 2 result: ${day11input.part2()}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day11/Day11.class", "javap": "Compiled from \"Day11.kt\"\npublic final class day11.Day11 {\n private final java.util.List<java.lang.String> input;\n\n public day11.Day11(java.util.List<java.lang.String>);\n Code:\n 0: aload_1\n 1: ldc...
mortenberg80__adventofcode2022__b21978e/src/main/kotlin/day10/Day10.kt
package day10 class Day10(private val input: List<String>) { private val commands = parseCommands(input) private fun parseCommands(input: List<String>): List<Command> { return input.flatMap { parseCommand(it) } } private fun parseCommand(input: String): List<Command> { if (input == "noop") return listOf(Command.Noop) val split = input.split(" ") if (split[0] == "addx") return listOf(Command.AddFirstCycle(split[1].toInt()), Command.AddSecondCycle(split[1].toInt())) return listOf() } fun part1(): Int { val _20 = commands.take(19).fold(1) { initial, command -> initial + command.compute() } * 20 val _60 = commands.take(59).fold(1) { initial, command -> initial + command.compute() } * 60 val _100 = commands.take(99).fold(1) { initial, command -> initial + command.compute() } * 100 val _140 = commands.take(139).fold(1) { initial, command -> initial + command.compute() } * 140 val _180 = commands.take(179).fold(1) { initial, command -> initial + command.compute() } * 180 val _220 = commands.take(219).foldIndexed(1) { i, initial, command -> initial + command.compute() } * 220 return _20 + _60 + _100 + _140 + _180 + _220 } fun part2(): String { val emptyRow = (0 until 40).joinToString("") { "." } val firstRow = Row(cyclePosition = 0, currentRow = emptyRow, 1) val row1 = commands.take(40).fold(firstRow) { row, command -> row.handleCommand(command)} val secondRow = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row1.registerX) val row2 = commands.drop(40).take(40).fold(secondRow) { row, command -> row.handleCommand(command)} val third = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row2.registerX) val row3 = commands.drop(80).take(40).fold(third) { row, command -> row.handleCommand(command)} val fourth = Row(cyclePosition = 0, currentRow = emptyRow, row3.registerX) val row4 = commands.drop(120).take(40).fold(fourth) { row, command -> row.handleCommand(command)} val fifth = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row4.registerX) val row5 = commands.drop(160).take(40).fold(fifth) { row, command -> row.handleCommand(command)} val sixth = Row(cyclePosition = 0, currentRow = emptyRow, registerX = row5.registerX) val row6 = commands.drop(200).take(40).fold(sixth) { row, command -> row.handleCommand(command)} return "\n${row1.currentRow}\n" + "${row2.currentRow}\n" + "${row3.currentRow}\n" + "${row4.currentRow}\n" + "${row5.currentRow}\n" + "${row6.currentRow}\n" } } sealed class Command { abstract fun compute(): Int object Noop : Command() { override fun compute(): Int = 0 } data class AddFirstCycle(val value: Int) : Command() { override fun compute(): Int = 0 } data class AddSecondCycle(val value: Int) : Command() { override fun compute(): Int = value } } data class Row(val cyclePosition: Int, val currentRow: String, val registerX: Int) { fun handleCommand(command: Command): Row { val nextRow = drawPixel() val nextCyclePosition = cyclePosition + 1 val nextRegisterX = registerX + command.compute() return Row(nextCyclePosition, nextRow, nextRegisterX) } fun drawPixel(): String { return if ((registerX - 1..registerX + 1).contains(cyclePosition)) currentRow.replaceRange(cyclePosition, cyclePosition+1, "#") else currentRow } } data class Row2(val cyclePosition: Int, val currentRow: String, val registerX: Int) { fun handleCommand(command: Command): Row { val nextRow = drawPixel() val nextCyclePosition = cyclePosition + 1 val nextRegisterX = registerX + command.compute() return Row(nextCyclePosition, nextRow, nextRegisterX) } fun drawPixel(): String { return if ((registerX - 1..registerX + 1).contains(cyclePosition)) currentRow.replaceRange(cyclePosition, cyclePosition+1, "#") else currentRow } } fun main() { val testInput = Day10::class.java.getResourceAsStream("/day10_test.txt").bufferedReader().readLines() val input = Day10::class.java.getResourceAsStream("/day10_input.txt").bufferedReader().readLines() val day10test = Day10(testInput) val day10input = Day10(input) println("Day10 part 1 test result: ${day10test.part1()}") println("Day10 part 1 result: ${day10input.part1()}") println("Day10 part 2 test result: ${day10test.part2()}") println("Day10 part 2 result: ${day10input.part2()}") }
[ { "class_path": "mortenberg80__adventofcode2022__b21978e/day10/Day10.class", "javap": "Compiled from \"Day10.kt\"\npublic final class day10.Day10 {\n private final java.util.List<java.lang.String> input;\n\n private final java.util.List<day10.Command> commands;\n\n public day10.Day10(java.util.List<java....
erolsvik__advent-of-code-2022__82f1bbb/src/main/kotlin/day2/Day2.kt
package day2 import java.io.File val values = mapOf("A" to 1, "B" to 2, "C" to 3) val values2 = mapOf("X" to 1, "Y" to 2, "Z" to 3) val winValues = mapOf("X" to "C", "Y" to "A", "Z" to "B") val lossValues = mapOf("X" to "B", "Y" to "C", "Z" to "A") val drawValues = mapOf("X" to "A", "Y" to "B", "Z" to "C") var totalScore = 0 fun main() { task2() println(totalScore) } fun task1() { loadFile().useLines { it.iterator().forEachRemaining { line -> val hand = line.split(" ") if (hand[0] == drawValues[hand[1]]) { totalScore += 3 } else if(hand[0] == winValues[hand[1]]) { totalScore += 6 } totalScore += values[drawValues[hand[1]]]!!.toInt() } } } fun task2() { loadFile().useLines { it.iterator().forEachRemaining { line -> val hand = line.split(" ") when(hand[1]) { "Y" -> totalScore += 3 + values2[invertMap(drawValues)[hand[0]]!!]!!.toInt() "Z" -> totalScore += 6 + values2[invertMap(winValues)[hand[0]]!!]!!.toInt() else -> totalScore += values2[invertMap(lossValues)[hand[0]]!!]!!.toInt() } } } } private fun loadFile(): File { return File("C:\\dev\\Advent_of_code_2022\\src\\main\\kotlin\\day2\\input.txt") } private fun invertMap(ogMap: Map<String, String>): Map<String, String> = ogMap.entries.associateBy({ it.value }) { it.key }
[ { "class_path": "erolsvik__advent-of-code-2022__82f1bbb/day2/Day2Kt.class", "javap": "Compiled from \"Day2.kt\"\npublic final class day2.Day2Kt {\n private static final java.util.Map<java.lang.String, java.lang.Integer> values;\n\n private static final java.util.Map<java.lang.String, java.lang.Integer> va...
KosmX__jneedle__b8d3ed1/api/src/main/kotlin/dev/kosmx/needle/util/KMP.kt
package dev.kosmx.needle.util /** * O(n+m) pattern matching with Knuth-Morris-Pratt algo * * @param T has to be comparable (== or .equals has to work as data-classes) */ class Word<T>(val word: Array<T>, private val comparator: (T, T) -> Boolean = { a, b -> a == b }) { init { require(word.isNotEmpty()) { "Matcher can't match empty word" } } private val pattern = Pattern() fun matcher() = Matcher(pattern) inner class Matcher internal constructor (private val pattern: Pattern) { val word: Array<T> get() = this@Word.word private var pos = -1 /** * Matcher check next entry * @return true if full match present */ fun checkNextChar(char: T): Boolean { pos++ findLoop@ while (pos >= 0) { if (comparator(char, word[pos]) ) { break@findLoop } else { pos = pattern.table[pos] } } if (pos + 1 == word.size) { pos = pattern.table[pos + 1] return true } return false } } inner class Pattern internal constructor() { internal val table: IntArray = IntArray(word.size + 1) //https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Description_of_pseudocode_for_the_table-building_algorithm init { table[0] = -1 var cnd = 0 for (i in word.indices.drop(1)) { if (comparator(word[i], word[cnd])) { table[i] = table[cnd] } else { table[i] = cnd while (cnd >= 0 && !comparator(word[cnd], word[i])) { cnd = table[cnd] } } cnd++ } table[word.size] = cnd } } } fun <T> Word<T>.match(iterable: Iterable<T>) = match(iterable.asSequence()) fun <T> Word<T>.match(sequence: Sequence<T>): Int = match(sequence.iterator()) fun <T> Word<T>.match(sequence: Iterator<T>): Int { val m = matcher() var pos = 0 sequence.forEach { if (m.checkNextChar(it)) { return@match pos - word.size + 1 } pos++ } return -1 }
[ { "class_path": "KosmX__jneedle__b8d3ed1/dev/kosmx/needle/util/KMPKt.class", "javap": "Compiled from \"KMP.kt\"\npublic final class dev.kosmx.needle.util.KMPKt {\n public static final <T> int match(dev.kosmx.needle.util.Word<T>, java.lang.Iterable<? extends T>);\n Code:\n 0: aload_0\n 1: ldc...
RedwanSharafatKabir__OOP-Kotlin__f764850/src/All_Filters_and_Built_In_Functions/getOrElse_first_last_map_max_min_filter_all_any_associateBy_groupBy.kt
package All_Filters_and_Built_In_Functions data class Hero( val name: String, val age: Int, val gender: Gender? ) enum class Gender { MALE, FEMALE } fun main (args: Array<String>){ val heroes = listOf( Hero("The Captain", 60, Gender.MALE), Hero("Frenchy", 42, Gender.MALE), Hero("<NAME>", 9, null), Hero("<NAME>", 29, Gender.FEMALE), Hero("<NAME>", 29, Gender.MALE), Hero("<NAME>", 37, Gender.MALE)) println(heroes.last().name) println(heroes.firstOrNull { it.age == 30 }?.name) println() try { println(heroes.first { it.age == 30 }.name) // It will throw exception } catch (e: Exception){ println(e)} println() println(heroes.map { it.gender }) println() println(heroes.map { it.age }) println(heroes.map { it.age }.distinct()) println(heroes.map { it.age }.distinct().size) // distinct() function will count two 29 ages once println() println(heroes.filter { it.age<30 }.size) // .filter shows output based on the given condition val (youngest, oldest) = heroes.partition { it.age < 30 } // .partition is similar to .filter println(oldest.size) println(youngest.size) println() println(heroes.maxBy { it.age }?.name) // .maxBy shows output based on the maximum value of given condition println(heroes.minBy { it.age }?.name) // .minBy shows output based on the minimum value of given condition println(heroes.groupBy { it.age==29 }) println() println(heroes.all { it.age<50 }) // here .all checks if all the values of ages are less than 50 println() println(heroes.any { it.gender == Gender.FEMALE }) // checks if any gender is FEMALE println() val mapByAge: Map<Int, List<Hero>> = heroes.groupBy { it.age } val (age, group) = mapByAge.maxBy { (_, group) -> group.size }!! println("$age $group") val mapByName: Map<String, Hero> = heroes.associateBy { it.name } // age of Frenchy println(mapByName["Frenchy"]?.age) // map[key] println(mapByName.getValue("Frenchy").age) // map.getValue(key) println(mapByName["Unknown"]?.age) // map[key] try { println(mapByName.getValue("Unknown").age) // map.getValue(key) } catch (e:Exception){ println(e) } val mapByName1 = heroes.associate { it.name to it.age } println(mapByName1.getOrElse("Unknown") { 0 }) val mapByName2 = heroes.associateBy { it.name } val unknownHero = Hero("Unknown", 25, null) println(mapByName2.getOrElse("unknown") { unknownHero }.age) // print maximum and minimum value using "flatMap" function val allPossiblePairs = heroes .flatMap { first -> heroes.map { second -> first to second }} val (older, younger) = allPossiblePairs.maxBy { it.first.age - it.second.age }!! println(older.name + ", " + younger.name) }
[ { "class_path": "RedwanSharafatKabir__OOP-Kotlin__f764850/All_Filters_and_Built_In_Functions/GetOrElse_first_last_map_max_min_filter_all_any_associateBy_groupByKt.class", "javap": "Compiled from \"getOrElse_first_last_map_max_min_filter_all_any_associateBy_groupBy.kt\"\npublic final class All_Filters_and_Bu...
TurpIF__coursera-algo-toolbox__86860f8/src/main/kotlin/fr/pturpin/coursera/greedy/MaximumValueOfTheLoot.kt
package fr.pturpin.coursera.greedy import java.util.* class MaximumValueOfTheLoot(private val knapsackCapacity: Int) { private val formatPrecision = 4 private var weightOfCandidates = 0 private val sortedByLowValuationCandidates = PriorityQueue<Item>() fun addPotentialItem(itemValue: Int, itemWeight: Int) { addNewCandidate(Item(itemValue, itemWeight)) if (!isLowestCandidateUseful()) { removeLowestCandidate() } } private fun isLowestCandidateUseful(): Boolean { if (weightOfCandidates <= knapsackCapacity) { return true } val lowestValuableCandidate = sortedByLowValuationCandidates.element() return weightOfCandidates - lowestValuableCandidate.weight < knapsackCapacity } private fun addNewCandidate(newCandidate: Item) { sortedByLowValuationCandidates.add(newCandidate) weightOfCandidates += newCandidate.weight } private fun removeLowestCandidate() { val lowestCandidate = sortedByLowValuationCandidates.remove() weightOfCandidates -= lowestCandidate.weight } fun getMaximalValueOfFractionsOfItemsFittingIn(): Double { if (knapsackCapacity == 0) { return 0.0 } val highestValuationsValue = sortedByLowValuationCandidates.stream() .skip(1) .mapToDouble { it.value.toDouble() } .sum() val lowestValuableCandidate = sortedByLowValuationCandidates.element() val partialValue = if (weightOfCandidates <= knapsackCapacity) { lowestValuableCandidate.value.toDouble() } else { val remainingWeight = knapsackCapacity - (weightOfCandidates - lowestValuableCandidate.weight) lowestValuableCandidate.value * remainingWeight.toDouble() / lowestValuableCandidate.weight } return highestValuationsValue + partialValue } fun formatOutput(value: Double): String { val format = "%." + formatPrecision + "f" return format.format(Locale.US, value) } private data class Item(val value: Int, val weight: Int) : Comparable<Item> { private fun getValueByWeight() = value.toDouble() / weight override fun compareTo(other: Item): Int { return getValueByWeight().compareTo(other.getValueByWeight()) } } } fun main(args: Array<String>) { val (n, knapsackCapacity) = readLine()!!.split(" ").map { it.toInt() } val maximumValueOfTheLoot = MaximumValueOfTheLoot(knapsackCapacity) for (i in 0 until n) { val (value, weight) = readLine()!!.split(" ").map { it.toInt() } maximumValueOfTheLoot.addPotentialItem(value, weight) } val maximalValue = maximumValueOfTheLoot.getMaximalValueOfFractionsOfItemsFittingIn() print(maximumValueOfTheLoot.formatOutput(maximalValue)) }
[ { "class_path": "TurpIF__coursera-algo-toolbox__86860f8/fr/pturpin/coursera/greedy/MaximumValueOfTheLoot$Item.class", "javap": "Compiled from \"MaximumValueOfTheLoot.kt\"\nfinal class fr.pturpin.coursera.greedy.MaximumValueOfTheLoot$Item implements java.lang.Comparable<fr.pturpin.coursera.greedy.MaximumValu...
TurpIF__coursera-algo-toolbox__86860f8/src/main/kotlin/fr/pturpin/coursera/dynprog/ArithmeticExpression.kt
package fr.pturpin.coursera.dynprog class ArithmeticExpression(private val strExpression: String) { private val cache = ArrayList<MutableList<MinMaxExpression?>>(strExpression.length) fun getMaximumValue(): Long { clearCache() return computeCachedMaximumValue(0, strExpression.length).maxExpression } private fun clearCache() { cache.clear() for (i in 0..strExpression.length) { val elements = ArrayList<MinMaxExpression?>(strExpression.length) for (j in 0..strExpression.length) { elements.add(null) } cache.add(elements) } } private fun computeCachedMaximumValue(indexFrom: Int, indexTo: Int): MinMaxExpression { cache[indexFrom][indexTo]?.let { return it } val result = computeMaximumValue(indexFrom, indexTo) cache[indexFrom][indexTo] = result return result } private fun computeMaximumValue(indexFrom: Int, indexTo: Int): MinMaxExpression { if (indexFrom == indexTo - 1) { val strNumber = strExpression[indexFrom] val value = strNumber.toLong() - '0'.toLong() return MinMaxExpression(value, value) } var minimum = Long.MAX_VALUE var maximum = Long.MIN_VALUE getSplitExpressions(indexFrom, indexTo) .flatMap { computeCandidateValues(it) } .forEach { candidate -> if (candidate >= maximum) { maximum = candidate } if (candidate <= minimum) { minimum = candidate } } return MinMaxExpression(minimum, maximum) } private fun computeCandidateValues(splitExpression: SplitExpression): Sequence<Long> { val leftMinMax = computeCachedMaximumValue(splitExpression.leftFrom, splitExpression.leftTo) val rightMinMax = computeCachedMaximumValue(splitExpression.rightFrom, splitExpression.rightTo) return sequenceOf( evaluate(splitExpression.operator, leftMinMax.minExpression, rightMinMax.minExpression), evaluate(splitExpression.operator, leftMinMax.maxExpression, rightMinMax.minExpression), evaluate(splitExpression.operator, leftMinMax.minExpression, rightMinMax.maxExpression), evaluate(splitExpression.operator, leftMinMax.maxExpression, rightMinMax.maxExpression)) } private fun evaluate(operator: Char, left: Long, right: Long): Long { when (operator) { '+' -> return left + right '-' -> return left - right '*' -> return left * right } throw UnsupportedOperationException() } private fun getSplitExpressions(indexFrom: Int, indexTo: Int): Sequence<SplitExpression> { return (indexFrom + 1 until indexTo).step(2) .asSequence() .map { SplitExpression( indexFrom, it, it + 1, indexTo, strExpression[it] ) } } private data class SplitExpression( val leftFrom: Int, val leftTo: Int, val rightFrom: Int, val rightTo: Int, val operator: Char) private data class MinMaxExpression( val minExpression: Long, val maxExpression: Long) } fun main(args: Array<String>) { val expression = readLine()!! val arithmeticExpression = ArithmeticExpression(expression) val maximumValue = arithmeticExpression.getMaximumValue() print(maximumValue) }
[ { "class_path": "TurpIF__coursera-algo-toolbox__86860f8/fr/pturpin/coursera/dynprog/ArithmeticExpression.class", "javap": "Compiled from \"ArithmeticExpression.kt\"\npublic final class fr.pturpin.coursera.dynprog.ArithmeticExpression {\n private final java.lang.String strExpression;\n\n private final java...
TurpIF__coursera-algo-toolbox__86860f8/src/main/kotlin/fr/pturpin/coursera/dynprog/PrimitiveCalculator.kt
package fr.pturpin.coursera.dynprog class PrimitiveCalculator(private val number: Int) { private val availableOperations = listOf( MultByOperation(2), MultByOperation(3), AddToOperation(1) ) private val cache = mutableMapOf<Int, OperationStates>() fun getMinimumOperationsToCompute(): OperationStates { cache.clear() cache[1] = NoOpStates(1) for (currentNumber in 1..number) { val currentOperation = cache[currentNumber]!! availableOperations.forEach { val appliedNumber = it.apply(currentNumber) cache.compute(appliedNumber) { _, oldState -> val newState = LinkedOperationStates( appliedNumber, currentOperation ) if (oldState == null || newState.size() < oldState.size()) { newState } else { oldState } } if (appliedNumber == number) { return cache[number]!! } } } return cache[number]!! } private interface Operation { fun apply(number: Int): Int } private class MultByOperation(private val factor: Int) : Operation { override fun apply(number: Int): Int { return number * factor } } private class AddToOperation(private val term: Int) : Operation { override fun apply(number: Int): Int { return number + term } } interface OperationStates { fun size(): Int fun getStates(): Iterable<Int> } private class LinkedOperationStates( private val currentState: Int, private val nextState: OperationStates ) : OperationStates { private val size = nextState.size() + 1 override fun size() = size override fun getStates(): Iterable<Int> { return listOf(currentState) + nextState.getStates() } } private class NoOpStates(private val initialValue: Int): OperationStates { override fun size() = 0 override fun getStates() = listOf(initialValue) } } fun main(args: Array<String>) { val number = readLine()!!.toInt() val primitiveCalculator = PrimitiveCalculator(number) val minimumOperationsToCompute = primitiveCalculator.getMinimumOperationsToCompute() println(minimumOperationsToCompute.size()) print(minimumOperationsToCompute.getStates().reversed().joinToString(" ")) }
[ { "class_path": "TurpIF__coursera-algo-toolbox__86860f8/fr/pturpin/coursera/dynprog/PrimitiveCalculator$NoOpStates.class", "javap": "Compiled from \"PrimitiveCalculator.kt\"\nfinal class fr.pturpin.coursera.dynprog.PrimitiveCalculator$NoOpStates implements fr.pturpin.coursera.dynprog.PrimitiveCalculator$Ope...
TurpIF__coursera-algo-toolbox__86860f8/src/main/kotlin/fr/pturpin/coursera/divconquer/QuickSort.kt
package fr.pturpin.coursera.divconquer import java.util.* class QuickSort(private val elements: IntArray) { private val random = Random(42) fun sortInPlace(): IntArray { sortInPlace(0, elements.size) return elements } private fun sortInPlace(from: Int, untilExcluded: Int) { if (from == untilExcluded) { return } val pivotIndex = getPivotIndex(from, untilExcluded) val partition = partitionAround(elements[pivotIndex], from, untilExcluded) sortInPlace(partition.lowerFrom, partition.lowerUntil) sortInPlace(partition.higherFrom, partition.higherUntil) } private fun partitionAround(pivotValue: Int, from: Int, untilExcluded: Int): Partition { var lowerUntil = from var higherFrom = untilExcluded var i = from while(i < higherFrom) { val currentValue = elements[i] if (currentValue < pivotValue) { swap(lowerUntil, i) lowerUntil++ } else if (currentValue > pivotValue) { higherFrom-- swap(higherFrom, i) i-- } i++ } elements.fill(pivotValue, lowerUntil, higherFrom - 1) return Partition(from, lowerUntil, higherFrom, untilExcluded) } private fun swap(i: Int, j: Int) { val tmp = elements[i] elements[i] = elements[j] elements[j] = tmp } private fun getPivotIndex(from: Int, untilExcluded: Int): Int { return random.nextInt(untilExcluded - from) + from } private data class Partition(val lowerFrom: Int, val lowerUntil: Int, val higherFrom: Int, val higherUntil: Int) { init { assert(lowerFrom <= lowerUntil) assert(lowerUntil < higherFrom) assert(higherFrom <= higherUntil) } } } fun main(args: Array<String>) { readLine()!! val elements = readLine()!!.split(" ").map { it.toInt() }.toIntArray() val quickSort = QuickSort(elements) val sorted = quickSort.sortInPlace() print(sorted.joinToString(" ")) }
[ { "class_path": "TurpIF__coursera-algo-toolbox__86860f8/fr/pturpin/coursera/divconquer/QuickSort.class", "javap": "Compiled from \"QuickSort.kt\"\npublic final class fr.pturpin.coursera.divconquer.QuickSort {\n private final int[] elements;\n\n private final java.util.Random random;\n\n public fr.pturpin...
eugenenosenko__coding-problems__673cc3e/src/test/kotlin/com/eugenenosenko/coding/problems/arrays/compose_from_old/ComposeArrayFromOldSolution.kt
package com.eugenenosenko.coding.problems.arrays.compose_from_old // brute force approach fun createArray(arr: IntArray): IntArray { val result = mutableListOf<Int>() for (i in arr.indices) { result.add( arr.foldIndexed(1) { index: Int, acc: Int, item: Int -> // ignore current index if (i == index) acc else acc * item } ) } return result.toIntArray() } // more efficient fun createArrayMoreEfficientWithDivision(arr: IntArray): IntArray { val product = arr.reduce { acc, v -> acc * v } val result = IntArray(arr.size) for ((i, v) in arr.withIndex()) { result[i] = product / v } return result } fun createArrayMoreEfficientWithoutDivision(arr: IntArray): IntArray { val prefixes = arrayListOf<Int>() for (number in arr) { if (prefixes.isNotEmpty()) { prefixes.add(prefixes.last() * number) } else { prefixes.add(number) } } // peak prefixes println("Prefixes are $prefixes") val suffixes = arrayListOf<Int>() for (number in arr.reversed()) { if (suffixes.isNotEmpty()) { suffixes.add(suffixes.last() * number) } else { suffixes.add(number) } } // peak suffixes suffixes.reverse() println("Suffixes are $suffixes") val result = arrayListOf<Int>() for (i in arr.indices) { when (i) { 0 -> result.add(suffixes[i + 1]) arr.lastIndex -> result.add(prefixes[i - 1]) else -> result.add(suffixes[i + 1] * prefixes[i - 1]) } } return result.toIntArray() }
[ { "class_path": "eugenenosenko__coding-problems__673cc3e/com/eugenenosenko/coding/problems/arrays/compose_from_old/ComposeArrayFromOldSolutionKt.class", "javap": "Compiled from \"ComposeArrayFromOldSolution.kt\"\npublic final class com.eugenenosenko.coding.problems.arrays.compose_from_old.ComposeArrayFromOl...
eugenenosenko__coding-problems__673cc3e/src/test/kotlin/com/eugenenosenko/coding/problems/arrays/pair_with_sum_x/FindPairWithSumXSolution.kt
package com.eugenenosenko.coding.problems.arrays.pair_with_sum_x fun findPairSolution(arr: IntArray, sum: Int): IntArray { // sort array first from smallest to largest // you'll end up with an array [0,1,2,3,5,6] arr.sort() // create two pointers var left = 0 var right = arr.size - 1 while (left < right) { val rightV = arr[right] val leftV = arr[left] when { // for example, sum is 7, result should be 1, 6 // upon first iteration you'll compare numbers 0, 6 // this will land you on the second case and increment left counter by one // next iteration will be between 1 and 6 which is what we're looking for // right value is too large leftV + rightV > sum -> right-- // left value is too small leftV + rightV < sum -> left++ // just right! leftV + rightV == sum -> return intArrayOf(leftV, rightV) } } return intArrayOf() } fun findPairOnceSolution(arr: IntArray, sum: Int): IntArray { val visited = HashSet<Int>() for (v in arr) { // calculate different, i.e. 17 - 7 = 10 val tmp = sum - v if (visited.contains(tmp)) { return intArrayOf(tmp, v) } visited.add(v) } return intArrayOf() }
[ { "class_path": "eugenenosenko__coding-problems__673cc3e/com/eugenenosenko/coding/problems/arrays/pair_with_sum_x/FindPairWithSumXSolutionKt.class", "javap": "Compiled from \"FindPairWithSumXSolution.kt\"\npublic final class com.eugenenosenko.coding.problems.arrays.pair_with_sum_x.FindPairWithSumXSolutionKt...
kcchoate__advent-of-kotlin__3e7c24b/src/main/kotlin/day03/Solution.kt
package day03 class Solution { fun solve(items: List<String>): Int { val sums = countArray(items) val target = items.size / 2 val gammaRate = count(sums) { if (it < target) 0 else 1 } val epsilonRate = count(sums) { if (it < target) 1 else 0 } return gammaRate * epsilonRate } private fun countArray(items: List<String>): IntArray { val sums = IntArray(items[0].length) for (item in items) { item.split("") .filter { it.isNotEmpty() } .map { it.toInt() } .forEachIndexed { idx, value -> sums[idx] += value } } return sums } private fun count(sums: IntArray, transform: (Int) -> Int): Int { val str = sums.map { transform(it) }.joinToString("") return str.toInt(2) } fun getOxygenGeneratorRating(input: List<String>): Int { return filter(input) { value, moreCommon -> value == moreCommon } } fun getCO2ScrubberRating(input: List<String>): Int { return filter(input) { value, moreCommon -> value != moreCommon } } private fun filter(input:List<String>, predicate: (Int, Int) -> Boolean): Int { val filtered = input.toMutableList(); for(i in 0..<input[0].length) { val sums = countArray(filtered) filtered.retainAll { predicate.invoke(it[i].toString().toInt(), moreCommon(sums[i], filtered)) } if (filtered.size == 1) { break } } return filtered[0].toInt(2) } private fun moreCommon(value: Int, input: List<String>): Int { val target = input.size / 2.0 return if (value >= target) 1 else 0 } fun solve2(input: List<String>): Int { return getCO2ScrubberRating(input) * getOxygenGeneratorRating(input) } }
[ { "class_path": "kcchoate__advent-of-kotlin__3e7c24b/day03/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class day03.Solution {\n public day03.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()V\n 4:...
kcchoate__advent-of-kotlin__3e7c24b/src/main/kotlin/day02/Solution.kt
package day02 class Solution { fun navigate(input: List<String>) = input.map { it.split(' ') } .map { Instruction(it[0], it[1].toInt()) } .fold(Result(0, 0)) { acc, instruction -> when (instruction.direction) { "up" -> Result(acc.horizontal, acc.depth - instruction.distance) "down" -> Result(acc.horizontal, acc.depth + instruction.distance) "forward" -> Result(acc.horizontal + instruction.distance, acc.depth) else -> throw IllegalArgumentException("Unknown direction: ${instruction.direction}") } } .calculateFinalValue() private data class Instruction(val direction: String, val distance: Int) private data class Result(val horizontal: Int, val depth: Int) { fun calculateFinalValue() = horizontal * depth } private data class Result2(val horizontal: Int, val depth: Int, val aim: Int = 0) { fun calculateFinalValue() = horizontal * depth fun process(instruction: Instruction): Result2 { return when (instruction.direction) { "up" -> UpCommand(instruction.distance) "down" -> DownCommand(instruction.distance) "forward" -> ForwardCommand(instruction.distance) else -> throw IllegalArgumentException("Unknown direction: ${instruction.direction}") }.process(this) } } private data class UpCommand(val distance: Int): Command { override fun process(state: Result2): Result2 { return Result2(state.horizontal, state.depth, state.aim - distance) } } private class DownCommand(val distance: Int): Command { override fun process(state: Result2): Result2 { return Result2(state.horizontal, state.depth, state.aim + distance) } } private class ForwardCommand(val distance: Int): Command { override fun process(state: Result2): Result2 { return Result2(state.horizontal + distance, state.depth + state.aim * distance, state.aim) } } private interface Command { fun process(state: Result2): Result2 } fun navigate2(input: List<String>) = input.map { it.split(' ') } .map { Instruction(it[0], it[1].toInt()) } .fold(Result2(0, 0, 0)) { acc, instruction -> acc.process(instruction) } .calculateFinalValue() }
[ { "class_path": "kcchoate__advent-of-kotlin__3e7c24b/day02/Solution$Result2.class", "javap": "Compiled from \"Solution.kt\"\nfinal class day02.Solution$Result2 {\n private final int horizontal;\n\n private final int depth;\n\n private final int aim;\n\n public day02.Solution$Result2(int, int, int);\n ...
snikiforov4__numeric-matrix-processor__ace36ad/src/main/kotlin/Matrix.kt
package processor import kotlin.math.pow class Matrix(private val matrix: Array<Array<Double>>) { companion object { fun empty(n: Int, m: Int = n): Matrix { require(n > 0) require(m > 0) return Matrix(Array(n) { Array(m) { 0.0 } }) } } val sizesOfDimensions: IntArray get() { val n = matrix.size val m = matrix.firstOrNull()?.size ?: 0 return intArrayOf(n, m) } operator fun get(n: Int, m: Int): Double = matrix[n][m] operator fun set(n: Int, m: Int, value: Double) { matrix[n][m] = value } fun swap(x1: Int, y1: Int, x2: Int, y2: Int) { val temp = this[x1, y1] this[x1, y1] = this[x2, y2] this[x2, y2] = temp } fun isSquare(): Boolean { val (x, y) = this.sizesOfDimensions return x == y } fun determinant(): Double { require(this.isSquare()) val (n) = this.sizesOfDimensions return when { n == 1 -> this[0, 0] n == 2 -> (this[0, 0] * this[1, 1]) - (this[0, 1] * this[1, 0]) n >= 3 -> { var res = 0.0 repeat(n) { res += this[0, it] * cofactor(0, it) } res } else -> 0.0 } } private fun cofactor(x: Int, y: Int): Double { return (-1.0).pow(x + y) * subMatrixExcluding(x, y).determinant() } private fun subMatrixExcluding(xExclude: Int, yExclude: Int): Matrix { val (n, m) = this.sizesOfDimensions require(xExclude in 0 until n) { "Index out of range: $xExclude" } require(yExclude in 0 until m) { "Index out of range: $yExclude" } val result = empty(n - 1, m - 1) var i = 0 for (x in 0 until n) { if (x == xExclude) { continue } var j = 0 for (y in 0 until m) { if (y == yExclude) { continue } result[i, j] = this[x, y] j++ } i++ } return result } fun toCofactorMatrix(): Matrix { require(isSquare()) val (n) = sizesOfDimensions val result = empty(n) for (x in 0 until n) { for (y in 0 until n) { result[x, y] = cofactor(x, y) } } return result } } interface TransposeStrategy { companion object { fun byNumber(number: Int): TransposeStrategy = when (number) { 1 -> MainDiagonalTransposeStrategy 2 -> SideDiagonalTransposeStrategy 3 -> VerticalLineTransposeStrategy 4 -> HorizontalLineTransposeStrategy else -> NullTransposeStrategy } } fun transpose(matrix: Matrix) } object MainDiagonalTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in 0 until x) { matrix.swap(x, y, y, x) } } } } object SideDiagonalTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in (0 until m - x - 1)) { matrix.swap(x, y, n - 1 - y, m - 1 - x) } } } } object VerticalLineTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n) { for (y in 0 until m / 2) { matrix.swap(x, y, x, m - 1 - y) } } } } object HorizontalLineTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions check(n == m) for (x in 0 until n / 2) { for (y in 0 until m) { matrix.swap(x, y, n - 1 - x, y) } } } } object NullTransposeStrategy : TransposeStrategy { override fun transpose(matrix: Matrix) { } }
[ { "class_path": "snikiforov4__numeric-matrix-processor__ace36ad/processor/Matrix$Companion.class", "javap": "Compiled from \"Matrix.kt\"\npublic final class processor.Matrix$Companion {\n private processor.Matrix$Companion();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Met...
snikiforov4__numeric-matrix-processor__ace36ad/src/main/kotlin/Main.kt
package processor import java.text.DecimalFormat private val regexp = "\\s+".toRegex() var decimalFormat = DecimalFormat("#0.##") fun main() { while (true) { printMenu() print("Your choice: ") when (readln().toInt()) { 0 -> break 1 -> { val m1 = readMatrix("first") val m2 = readMatrix("second") if (isAdditionAllowed(m1, m2)) { printMatrix(addMatrices(m1, m2)) } else { println("The operation cannot be performed.") } } 2 -> { val m1 = readMatrix() print("Enter constant: ") val constant = readln().toDouble() printMatrix(multiplyMatrixByConstant(m1, constant)) } 3 -> { val m1 = readMatrix("first") val m2 = readMatrix("second") if (isMultiplicationAllowed(m1, m2)) { printMatrix(multiplyMatrices(m1, m2)) } else { println("The operation cannot be performed.") } } 4 -> { printTransposeMatrixMenu() print("Your choice: ") val strategy = TransposeStrategy.byNumber(readln().toInt()) val m = readMatrix() strategy.transpose(m) printMatrix(m) } 5 -> { val m = readMatrix() if (m.isSquare()) { println("The result is:") println(m.determinant()) } else { println("The operation cannot be performed.") } } 6 -> { val m = readMatrix() if (m.isSquare()) { val inverse = findMatrixInverse(m) if (inverse == null) { println("This matrix doesn't have an inverse.") } else { printMatrix(inverse) } } else { println("The operation cannot be performed.") } } else -> println("Wrong choice!") } } } private fun printMenu() { println("1. Add matrices") println("2. Multiply matrix by a constant") println("3. Multiply matrices") println("4. Transpose matrix") println("5. Calculate a determinant") println("6. Inverse matrix") println("0. Exit") } private fun readMatrix(matrixName: String = ""): Matrix { val matrixNamePlaceholder = if (matrixName.isNotBlank()) " " else "" + matrixName.trim() print("Enter size of$matrixNamePlaceholder matrix: ") val (n, m) = readln().split(regexp).map { it.toInt() } val result = Matrix.empty(n, m) println("Enter$matrixNamePlaceholder matrix:") repeat(n) { x -> val row = readln().split(regexp).map { it.toDouble() } check(row.size == m) row.forEachIndexed { y, e -> result[x, y] = e } } return result } private fun isAdditionAllowed(m1: Matrix, m2: Matrix) = m1.sizesOfDimensions.contentEquals(m2.sizesOfDimensions) private fun addMatrices(m1: Matrix, m2: Matrix): Matrix { val (n, m) = m1.sizesOfDimensions val result = Matrix.empty(n, m) repeat(n) { x -> repeat(m) { y -> result[x, y] = m1[x, y] + m2[x, y] } } return result } private fun multiplyMatrixByConstant(matrix: Matrix, c: Double): Matrix { val (n, m) = matrix.sizesOfDimensions val result = Matrix.empty(n, m) repeat(n) { x -> repeat(m) { y -> result[x, y] = matrix[x, y] * c } } return result } private fun isMultiplicationAllowed(m1: Matrix, m2: Matrix): Boolean { val (_, m1d2) = m1.sizesOfDimensions val (m2d1, _) = m2.sizesOfDimensions return m1d2 == m2d1 } private fun multiplyMatrices(m1: Matrix, m2: Matrix): Matrix { val (n, m) = m1.sizesOfDimensions val (_, k) = m2.sizesOfDimensions val result = Matrix.empty(n, k) repeat(n) { x -> repeat(k) { y -> val dotProduct = (0 until m).sumOf { idx -> m1[x, idx] * m2[idx, y] } result[x, y] = dotProduct } } return result } private fun printMatrix(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions println("The result is:") repeat(n) { x -> repeat(m) { y -> print("${decimalFormat.format(matrix[x, y])} ") } println() } } private fun printTransposeMatrixMenu() { println("1. Main diagonal") println("2. Side diagonal") println("3. Vertical line") println("4. Horizontal line") } fun findMatrixInverse(matrix: Matrix): Matrix? { val determinant = matrix.determinant() if (determinant == 0.0) { return null } val cofactorMatrix = matrix.toCofactorMatrix() MainDiagonalTransposeStrategy.transpose(cofactorMatrix) return multiplyMatrixByConstant(cofactorMatrix, 1.0 / determinant) }
[ { "class_path": "snikiforov4__numeric-matrix-processor__ace36ad/processor/MainKt.class", "javap": "Compiled from \"Main.kt\"\npublic final class processor.MainKt {\n private static final kotlin.text.Regex regexp;\n\n private static java.text.DecimalFormat decimalFormat;\n\n public static final java.text....
emirhanaydin__ahp-android__7a58319/AnalyticHierarchyProcess/app/src/main/java/com/emirhanaydin/analytichierarchyprocess/math.kt
package com.emirhanaydin.analytichierarchyprocess fun getRandomIndex(n: Int): Float { return when (n) { 1, 2 -> 0f 3 -> 0.58f 4 -> 0.90f 5 -> 1.12f 6 -> 1.24f 7 -> 1.32f 8 -> 1.41f 9 -> 1.45f 10 -> 1.49f 11 -> 1.51f 12 -> 1.48f 13 -> 1.56f else -> -1f } } fun multiplyVectors(v1: FloatArray, v2: FloatArray): Float { val size = v1.size var sum = 0f for (i in 0 until size) { sum += v1[i] * v2[i] } return sum } private fun getWeights(ratings: Array<FloatArray>): Pair<Array<FloatArray>, FloatArray> { val size = ratings.size val weights = Array(size) { FloatArray(size) } val subtotals = FloatArray(size) // Calculate the weights for (i in 0 until size) { val child = ratings[i] for (j in 0 until child.size) { val index = j + i + 1 // Plus i to make the calculations triangular, plus 1 to skip diagonal weights[i][index] = child[j] weights[index][i] = 1 / weights[i][index] // Reciprocal // Add the values to subtotals by their column indexes subtotals[index] += weights[i][index] subtotals[i] += weights[index][i] } // The diagonal indicates the alternative itself, so its weight is 1 weights[i][i] = 1f subtotals[i] += weights[i][i] } return Pair(weights, subtotals) } private fun getNormalizedWeights(weights: Array<FloatArray>, subtotals: FloatArray): Array<FloatArray> { val size = weights.size val normalizedWeights = Array(size) { FloatArray(size) } // Normalize the weights for (i in 0 until size) { for (j in 0 until size) { normalizedWeights[i][j] = weights[i][j] / subtotals[j] } } return normalizedWeights } private fun getPriorities(normalizedWeights: Array<FloatArray>): FloatArray { val size = normalizedWeights.size val priorities = FloatArray(size) // Calculate priorities with the normalized weights for (i in 0 until size) { var sum = 0f for (j in 0 until size) { sum += normalizedWeights[i][j] } priorities[i] = sum / size // Average of the row } return priorities } private fun getConsistencyRatio(priorities: FloatArray, subtotals: FloatArray): Pair<Float, Float> { val size = priorities.size // Calculate the consistency ratio val eMax = multiplyVectors(priorities, subtotals) val consistencyIndex = (eMax - size) / (size - 1) return Pair(consistencyIndex, getRandomIndex(size)) } fun performAhp(ratings: Array<FloatArray>): AhpResult { val weights: Array<FloatArray> val subtotals: FloatArray getWeights(ratings).apply { weights = first subtotals = second } val normalizedWeights = getNormalizedWeights(weights, subtotals) val priorities = getPriorities(normalizedWeights) val randomIndex: Float val consistencyIndex: Float getConsistencyRatio(priorities, subtotals).apply { consistencyIndex = first randomIndex = second } return AhpResult(priorities, consistencyIndex, randomIndex, consistencyIndex / randomIndex) } class AhpResult( val priorities: FloatArray, val consistencyIndex: Float, val randomIndex: Float, val consistencyRatio: Float )
[ { "class_path": "emirhanaydin__ahp-android__7a58319/com/emirhanaydin/analytichierarchyprocess/MathKt.class", "javap": "Compiled from \"math.kt\"\npublic final class com.emirhanaydin.analytichierarchyprocess.MathKt {\n public static final float getRandomIndex(int);\n Code:\n 0: iload_0\n 1: t...
mr-nothing__leetcode__0f7418e/src/main/kotlin/solved/p289/InPlaceSolution.kt
package solved.p289 /** The idea is that we will store in original array: * -1 for dead-alive transition * 0 for dead-dead transition * 1 for alive-alive transition * 2 for alive-dead transition */ class InPlaceSolution { class Solution { fun gameOfLife(board: Array<IntArray>) { for (i in 0..board.lastIndex) { for (j in 0..board[0].lastIndex) { val currentValue = board[i][j] val adjacentValue = adjacentSum(board, i, j) if (currentValue == 1) { if (adjacentValue < 2 || adjacentValue > 3) { board[i][j] = 2 } else { board[i][j] = 1 } } else { if (adjacentValue == 3) { board[i][j] = -1 } } } } for (i in 0..board.lastIndex) { for (j in 0..board[0].lastIndex) { val currentValue = board[i][j] if (currentValue == -1) { board[i][j] = 1 } else if (currentValue == 2) { board[i][j] = 0 } } } } private fun adjacentSum(arr: Array<IntArray>, i: Int, j: Int): Int { return adjValue(arr, i - 1, j - 1) + adjValue(arr, i - 1, j) + adjValue(arr, i - 1, j + 1) + adjValue(arr, i, j - 1) + adjValue(arr, i, j + 1) + adjValue(arr, i + 1, j - 1) + adjValue(arr, i + 1, j) + adjValue(arr, i + 1, j + 1) } private fun adjValue(arr: Array<IntArray>, i: Int, j: Int): Int { if (i >= 0 && i <= arr.lastIndex && j >= 0 && j <= arr[0].lastIndex) { val value = arr[i][j] if (value == 1 || value == 2) { return 1 } } return 0 } } }
[ { "class_path": "mr-nothing__leetcode__0f7418e/solved/p289/InPlaceSolution.class", "javap": "Compiled from \"InPlaceSolution.kt\"\npublic final class solved.p289.InPlaceSolution {\n public solved.p289.InPlaceSolution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method ja...
mr-nothing__leetcode__0f7418e/src/main/kotlin/solved/p672/Solution.kt
package solved.p672 class Solution { class BruteForceSolution { // This was the first idea: generate all possible combinations of button presses // and simulate it on given bulbs. Clearly it does't fit any time limits :D fun flipLights(n: Int, presses: Int): Int { val states = HashSet<MutableList<Boolean>>() val combinations = mutableListOf<MutableList<Int>>() generatePressesCombinations(combinations, MutableList(presses) { -1 }, presses) for (combination in combinations) { val lights = MutableList(n) { true } for (button in combination) { when (button) { 1 -> { for (i in 1..lights.size) { toggle(lights, i) } } 2 -> { for (i in 1..lights.size) { if (i % 2 == 0) { toggle(lights, i) } } } 3 -> { for (i in 1..lights.size) { if (i % 2 == 1) { toggle(lights, i) } } } 4 -> { for (i in 1..lights.size) { if ((i - 1) % 3 == 0) { toggle(lights, i) } } } } } states.add(lights) } return states.count() } private fun toggle(lights: MutableList<Boolean>, i: Int) { lights[i - 1] = lights[i - 1].not() } private fun generatePressesCombinations( combinations: MutableList<MutableList<Int>>, combination: MutableList<Int>, pressesRemaining: Int ) { if (pressesRemaining > 0) { for (button in 1..4) { val tempCombination = mutableListOf(*combination.toTypedArray()) tempCombination[tempCombination.size - pressesRemaining] = button generatePressesCombinations(combinations, tempCombination, pressesRemaining - 1) } } else { combinations.add(combination) } } } class GodHelpMeSolution { // I'm crying xD // This solution came to my mind when I realised there is a finite number of states for given bulbs for every n. // For different n it is different. So I built a table/graph representing this state machine. // What bulbs are switched on: // A - all // N - none // E - evens // O - odds // A# - all but thirds // N# - none but thirds // E# - evens except thirds // O# - odds except thirds // ___| 1B | 2B | 3B | 4B | // A | N | O | E | A# | // N | A | E | O | N# | // O | E | N | A | O# | // E | O | A | N | E# | // A# | N# | O# | E# | A | // N# | A# | E# | O# | N | // O# | E# | N# | A# | O | // E# | O# | A# | N# | E | // Starting from 3 bulbs and 3 presses this system can be in 8 different states described in this table. // When bulbs and presses are lower than 3 we can count number of states we can reach with use of table above. fun flipLights(bulbs: Int, presses: Int): Int { return when (bulbs) { 0 -> 1 1 -> when (presses) { 0 -> 1 else -> 2 } 2 -> when (presses) { 0 -> 1 1 -> 3 else -> 4 } else -> when (presses) { 0 -> 1 1 -> 4 2 -> 7 else -> 8 } } } } }
[ { "class_path": "mr-nothing__leetcode__0f7418e/solved/p672/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class solved.p672.Solution {\n public solved.p672.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()...
mr-nothing__leetcode__0f7418e/src/main/kotlin/solved/p1418/Solution.kt
package solved.p1418 class Solution { fun displayTable(orders: List<List<String>>): List<List<String>> { // A tree set of all tables sorted by natural order val tables = sortedSetOf<Int>() // A tree set of all dishes sorted by natural order val dishes = sortedSetOf<String>() // Result map containing unsorted display table (mapOf(table to mapOf(dish to quantity)) val resultMap = mutableMapOf<Int, MutableMap<String, Int>>() for (order in orders) { // Skip person name as we are not interested in it in the final solution // Parse table number val tableNumber = order[1].toInt() // Parse dish name val dishName = order[2] // Add table number to general table set tables.add(tableNumber) // Add dish to general dish set dishes.add(dishName) // Get already created table map info or initialize it with empty map val tableDishes = resultMap.getOrDefault(tableNumber, mutableMapOf()) // Get dish quantity already found for this table or initialize it with zero val dishQuantity = tableDishes.getOrDefault(dishName, 0) // Set dish quantity info and increment it by one tableDishes[dishName] = dishQuantity + 1 // Set table info resultMap[tableNumber] = tableDishes } // Initializing result list of list val result = mutableListOf<MutableList<String>>() // Create header table val header = mutableListOf<String>() // Add "Table" string since it is one of the requirements header.add("Table") for (dish in dishes) { // Add all the dishes' names sorted alphabetically header.add(dish) } // Add header to the result table result.add(header) // Go through all the tables and populate rows corresponding to each table for (table in tables) { // Initialize table row with zeroes at first // dishes.size + 1 is because we have first column populated with table numbers val resultRow = MutableList(dishes.size + 1) { "0" } // Populate table number resultRow[0] = table.toString() // Get all the dishes ordered for this table val tableDishes = resultMap[table]!! for (entry in tableDishes) { // Get "alphabetical" dish index to place it to the right position in the final table val dishIndex = dishes.indexOf(entry.key) + 1 // Populate the quantity of dishes ordered for this table (at corresponding index) resultRow[dishIndex] = entry.value.toString() } // Add populated row to the final table result.add(resultRow) } return result } }
[ { "class_path": "mr-nothing__leetcode__0f7418e/solved/p1418/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class solved.p1418.Solution {\n public solved.p1418.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\"...
mr-nothing__leetcode__0f7418e/src/main/kotlin/solved/p1679/Solution.kt
package solved.p1679 class Solution { class SortingApproach { fun maxOperations(nums: IntArray, k: Int): Int { val sorted = nums.sorted() var operations = 0 var head = 0 var tail = nums.lastIndex while (head < tail) { while (tail > head) { val headValue = sorted[head] val tailValue = sorted[tail] val kSum = headValue + tailValue if (kSum > k) { // if sum is greater than k then we need a lower number thus we need to move tail to the left tail-- } else if (kSum < k) { // if sum is lower than k then we need a greater number thus we need to move tail to the right head++ } else { // we found 2 numbers that sum up to k this move both head and tail pointers operations++ head++ tail-- } } } return operations } } class HashMapApproach { fun maxOperations(nums: IntArray, k: Int): Int { val frequencies = hashMapOf<Int, Int>() var operations = 0 for (first in nums) { val second = k - first val secondFrequency = frequencies.getOrDefault(second, 0) // get second number frequency if (secondFrequency > 0) { // if number has been already met (frequency > 0) then decrement frequency and increment result // since we found a pair that sum up to k frequencies[second] = secondFrequency - 1 operations++ } else { // if we have not met number yet, than increment numbers frequency val firstFrequency = frequencies.getOrDefault(first, 0) frequencies[first] = firstFrequency + 1 } } return operations } } }
[ { "class_path": "mr-nothing__leetcode__0f7418e/solved/p1679/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class solved.p1679.Solution {\n public solved.p1679.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\"...
mr-nothing__leetcode__0f7418e/src/main/kotlin/solved/p581/Solution.kt
package solved.p581 class Solution { class SortingApproach { // The idea is to sort initial array and compare both arrays from the start and from the end. // The index of first element from the: // - start that is not equal is the lower bound of the subsequence // - end that if not equal is the upper bound of the subsequence fun findUnsortedSubarray(nums: IntArray): Int { val sorted = nums.sorted() var lowerBound = -1 for (i in 0..nums.lastIndex) { if (nums[i] != sorted[i]) { lowerBound = i break } } var upperBound = -1 for (i in nums.lastIndex downTo 0) { if (nums[i] != sorted[i]) { upperBound = i break } } return if (lowerBound == upperBound) 0 else upperBound - lowerBound + 1 } } class TwoPointerApproach { // The idea is to find: // - the element that should be going next to the sorted part at the start of array // - the element that should be going right before the sorted part at the end of array // Lets describe the algorithm for the first part. // 1. It is easy if min element is somewhere in the middle, we just need to sort from the very beginning. // 2. In case the second minimal element is somewhere in the middle and lower elements are sorted in the beginning of array, then we need to sort from the second element. // ... // n. In case the nth minimal element is somewhere in the middle and lower elements are sorted in the beginning of array, then we need to sort from the nth element. // // So to find this element and its index we need to go through the array and if current element is lower than maximal element met, then this can be the upper bound of the subarray we need to sort if nothing similar will be met further. // For the lower bound - if current element is greater than minimal element met, then this can be the lower bound if nothing similar will be met further. fun findUnsortedSubarray(nums: IntArray): Int { var lowerBound = -1 var upperBound = -1 var min = Int.MAX_VALUE var max = Int.MIN_VALUE for (i in 0..nums.lastIndex) { val headPointer = i val headValue = nums[headPointer] if (headValue > max) { max = headValue } else if (headValue < max) { upperBound = headPointer } val tailPointer = nums.lastIndex - i val tailValue = nums[tailPointer] if (tailValue < min) { min = tailValue } else if (tailValue > min) { lowerBound = tailPointer } } return if (upperBound == lowerBound) 0 else upperBound - lowerBound + 1 } } }
[ { "class_path": "mr-nothing__leetcode__0f7418e/solved/p581/Solution.class", "javap": "Compiled from \"Solution.kt\"\npublic final class solved.p581.Solution {\n public solved.p581.Solution();\n Code:\n 0: aload_0\n 1: invokespecial #8 // Method java/lang/Object.\"<init>\":()...
mattianeroni__aoc__cbbe6f8/src/main/kotlin/day3.kt
package day3 import java.io.File import java.util.PriorityQueue val nums = Array<String>(10){ it.toString() }.toSet() fun exercise1 () { val filename = "./inputs/day3ex1.txt" var total: Int = 0 val allLines = File(filename).readLines().toList() for ((row, line) in allLines.withIndex()) { var cnum: String = "" var toAdd: Boolean = false for (col in 0..line.length - 1) { val x: String = line[col].toString() if (!nums.contains(x)) { if (toAdd) total += cnum.toInt() cnum = "" toAdd = false continue } cnum = cnum.plus(line[col]) extloop@ for (i in row-1..row+1) { if (i < 0 || i >= allLines.size) continue for (j in col-1..col+1) { if (j < 0 || j >= line.length) continue val str = allLines[i][j].toString() if (str != "." && !nums.contains(str)) { toAdd = true break@extloop } } } } // end line if (toAdd) { total += cnum.toInt() } } println("Total: ${total}") } data class Symbol(val name: String, val row: Int, val col: Int) fun exercise2 () { val filename = "./inputs/day3ex2.txt" var total: Int = 0 val allLines = File(filename).readLines().toList() for ((row, line) in allLines.withIndex()) { for (col in 0..line.length - 1) { if (line[col].toString() != "*") continue var neighbourNums = ArrayList<Int>() // Read the neighbourhood var explored = HashSet<Symbol>() var neighbours = ArrayList<Symbol>() for (i in row - 1..row + 1) for (j in col - 1..col + 1) if (nums.contains(allLines[i][j].toString())) { neighbours.add(Symbol(name = allLines[i][j].toString(), row = i, col = j)) } if (neighbours.size == 0) continue for (neighbour in neighbours) { if (explored.contains(neighbour)) continue var cnum: String = neighbour.name // Left numbers var pointer: Symbol = neighbour while (nums.contains(pointer.name) && pointer.col > 0) { pointer = Symbol( name=allLines[pointer.row][pointer.col - 1].toString(), row=pointer.row, col=pointer.col - 1 ) if (nums.contains(pointer.name)) { cnum = pointer.name.plus(cnum) explored.add(pointer) } } // RIGHT numbers pointer = neighbour while (nums.contains(pointer.name) && pointer.col < line.length - 1) { pointer = Symbol( name=allLines[pointer.row][pointer.col + 1].toString(), row=pointer.row, col=pointer.col + 1 ) if (nums.contains(pointer.name)) { cnum = cnum.plus(pointer.name) explored.add(pointer) } } neighbourNums.add(cnum.toInt()) } if (neighbourNums.size < 2) continue total += neighbourNums.reduce { acc, i -> acc * i } } } println("Total: ${total}") }
[ { "class_path": "mattianeroni__aoc__cbbe6f8/day3/Day3Kt.class", "javap": "Compiled from \"day3.kt\"\npublic final class day3.Day3Kt {\n private static final java.util.Set<java.lang.String> nums;\n\n public static final java.util.Set<java.lang.String> getNums();\n Code:\n 0: getstatic #12 ...
sdkei__KotlinJvmUtils__db6280c/src/main/kotlin/io/github/sdkei/kotlin_jvm_utils/PermutationAndCombination.kt
package io.github.sdkei.kotlin_jvm_utils /** * Returns permutation of elements of the receiver. * * ``` * listOf("A", "B", "C").permutation(2) // -> [[A, B], [A, C], [B, A], [B, C], [C, A], [C, B]] * ``` * * @param count number of elements of permutation. */ fun <T> Iterable<T>.permutation(count: Int): List<List<T>> { require(count >= 0) val inputList = if (this is List<T>) this else toList() require(count <= inputList.size) return inputList.subPermutation(count) } private fun <T> List<T>.subPermutation(count: Int): List<List<T>> { if (count == 1) return map { listOf(it) } return (0 until size).flatMap { index -> val first = listOf(this[index]) (subList(0, index) + subList(index + 1, size)) .subPermutation(count - 1) .map { first + it } } } /** * Returns combination of elements of the receiver. * * ``` * listOf("A", "B", "C", "D").combination(3) // -> [[A, B, C], [A, B, D], [A, C, D], [B, C, D]] * ``` * * @param count number of elements of combination. */ fun <T> Iterable<T>.combination(count: Int): List<List<T>> { require(count >= 0) val inputList = if (this is List<T>) this else toList() require(count <= inputList.size) return inputList.subCombination(count) } private fun <T> List<T>.subCombination(count: Int): List<List<T>> { if (count == 1) return map { listOf(it) } return (0 until size - (count - 1)).flatMap { index -> val first = listOf(this[index]) subList(index + 1, size) .subCombination(count - 1) .map { first + it } } }
[ { "class_path": "sdkei__KotlinJvmUtils__db6280c/io/github/sdkei/kotlin_jvm_utils/PermutationAndCombinationKt.class", "javap": "Compiled from \"PermutationAndCombination.kt\"\npublic final class io.github.sdkei.kotlin_jvm_utils.PermutationAndCombinationKt {\n public static final <T> java.util.List<java.util...
lilimapradhan9__kotlin-problems__356cef0/src/main/kotlin/dayFolders/day5/letterCombinationsOfPhone.kt
package dayFolders.day5 val digitToLetterMap = mapOf( 2 to listOf('a', 'b', 'c'), 3 to listOf('d', 'e', 'f'), 4 to listOf('g', 'h', 'i'), 5 to listOf('j', 'k', 'l'), 6 to listOf('m', 'n', 'o'), 7 to listOf('p', 'q', 'r', 's'), 8 to listOf('t', 'u', 'v'), 9 to listOf('w', 'x', 'y', 'z') ) fun letterCombinations(digits: String): List<String> { val result = mutableListOf<String>() if (digits.isEmpty()) return result addAllPermutations(digits, "", 0, result) return result } fun addAllPermutations(digits: String, permutation: String, k: Int, result: MutableList<String>) { if (k == digits.length) { result.add(permutation) return } val characters = digitToLetterMap.getValue(digits[k].toString().toInt()) for (element in characters) { addAllPermutations(digits, permutation + element, k + 1, result) } }
[ { "class_path": "lilimapradhan9__kotlin-problems__356cef0/dayFolders/day5/LetterCombinationsOfPhoneKt.class", "javap": "Compiled from \"letterCombinationsOfPhone.kt\"\npublic final class dayFolders.day5.LetterCombinationsOfPhoneKt {\n private static final java.util.Map<java.lang.Integer, java.util.List<jav...