path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
common/src/main/kotlin/me/haydencheers/nscpdt/Sequences.kt
hjc851
247,242,039
false
null
package me.haydencheers.nscpdt import java.util.function.BiPredicate object Sequences { // fun findLCS(X: String, Y: String, m: Int = X.length, n: Int = Y.length): String { // // Create a table to store lengths findLCS longest common // // suffixes findLCS substrings. Note that LCSuff[i][j] // // contains length findLCS longest common suffix findLCS X[0..i-1] // // and Y[0..j-1]. The first row and first column entries // // have no logical meaning, they are used only for // // simplicity findLCS program // val LCSuff = Array(m + 1) { IntArray(n + 1) } // // // To store length findLCS the longest common substring // var len = 0 // // // To store the index findLCS the cell which contains the // // maximum value. This cell's index helps in building // // up the longest common substring from right to left. // var row = 0 // var col = 0 // // /* Following steps build LCSuff[m+1][n+1] in bottom // up fashion. */ // for (i in 0..m) { // for (j in 0..n) { // if (i == 0 || j == 0) // LCSuff[i][j] = 0 // else if (X[i - 1] == Y[j - 1]) { // LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1 // if (len < LCSuff[i][j]) { // len = LCSuff[i][j] // row = i // col = j // } // } else // LCSuff[i][j] = 0 // } // } // // // if true, then no common substring exists // if (len == 0) { // return "" // } // // // allocate space for the longest common substring //// var resultStr = "" // val resultBuilder = StringBuilder(len) // // // traverse up diagonally form the (row, col) cell // // until LCSuff[row][col] != 0 // while (LCSuff[row][col] != 0) { //// resultStr = X[row - 1] + resultStr // or Y[col-1] // resultBuilder.insert(0, X[row-1]) // // --len // // // move diagonally up to previous cell // row-- // col-- // } // // // required longest common substring // val resultStr = resultBuilder.toString() // return resultStr // } // // fun <T> findLCS(X: List<T>, Y: List<T>, comp: BiPredicate<T, T>, m: Int = X.size, n: Int = Y.size): Result { // // Create a table to store lengths findLCS longest common // // suffixes findLCS substrings. Note that LCSuff[i][j] // // contains length findLCS longest common suffix findLCS X[0..i-1] // // and Y[0..j-1]. The first row and first column entries // // have no logical meaning, they are used only for // // simplicity findLCS program // val arr = Array(m+1) { IntArray(n+1) } // // // To store length findLCS the longest common substring // var len = 0 // // // To store the index findLCS the cell which contains the // // maximum value. This cell's index helps in building // // up the longest common substring from right to left. // var row = 0 // var col = 0 // // /* Following steps build LCSuff[m+1][n+1] in bottom // up fashion. */ // for (i in 0 .. m) { // for (j in 0 .. n) { // if (i == 0 || j == 0) { // arr[i][j] = 0 // } else if (comp.test(X[i-1], Y[j-1])) { // arr[i][j] = arr[i-1][j-1]+1 // if (len < arr[i][j]) { // len = arr[i][j] // row = i // col = j // } // } else { // arr[i][j] = 0 // } // } // } // // // if true, then no common substring exists // if (len == 0) // return Result(0, 0, 0) // // // Allocate space for the result // val result = ArrayList<T>(len) // // while (arr[row][col] != 0) { // result.add(0, X[row-1]) // // --len // // // move diagonally up to previous cell // row-- // col-- // } // // return Result(row, col, result.size) // } fun <T> findFCS( a: List<T>, b: List<T>, aoffset: Int, boffset: Int, minLength: Int, predicate: BiPredicate<T, T> ): Result { var l = aoffset while (l < a.size) { var r = boffset while (r < b.size) { if (predicate.test(a[l], b[r])) { val _l = l val _r = r var length = 0 while (l < a.size && r < b.size && predicate.test(a[l], b[r])) { length++ l++ r++ } if (length >= minLength) return Result(l - length, r - length, length) l = _l r = _r } r++ } l++ } return Result(-1, -1, -1) } // fun findFCS(a: CharSequence, b: CharSequence, aoffset: Int, boffset: Int, minLength: Int): Result { // var l = aoffset // while (l < a.length) { // // var r = 0 // while (r < b.length) { // // if (a[l] == b[r]) { // val _l = l // val _r = r // var length = 0 // // while (l < a.length && r < b.length && a[l] == b[r]) { // length++ // l++ // r++ // } // // if (length >= minLength) // return Result(l-length, r-length, length) // // l = _l // r = _r // } // // r++ // } // // l++ // } // // return Result(-1, -1, -1) // } data class Result( val lindex: Int, val rindex: Int, val length: Int ) fun <T> editDistance(lhs: List<T>, rhs: List<T>, comp: BiPredicate<T, T>): Int { var lhs = lhs var rhs = rhs /* This implementation use two variable to record the previous cost counts, So this implementation use less memory than previous impl. */ var n = lhs.size var m = rhs.size if (n == 0) return m else if (m == 0) return n // Swap the input strings to consume less memory if (n > m) { val temp = lhs lhs = rhs rhs = temp n = m m = rhs.size } val p = IntArray(n + 1) // indexes into strings left and right var i = 0 var j = 0 var upperLeft = 0 var upper = 0 var rightJ: T var cost = 0 i = 0 while (i <= n) { p[i] = i i++ } j = 1 while (j <= m) { upperLeft = p[0] rightJ = rhs[j - 1] p[0] = j i = 1 while (i <= n) { upper = p[i] cost = if (comp.test(lhs[i - 1], rightJ)) 0 else 1 // minimum of cell to the left+1, to the top+1, diagonally left and up +cost p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upperLeft + cost) upperLeft = upper i++ } j++ } return p[n] } }
0
Kotlin
0
0
b697648f04710a58722dfc1b764a3e43e56b4c4a
7,799
NaiveSCPDTools
MIT License
api/src/main/kotlin/glimpse/SquareMatrix.kt
glimpse-graphics
44,015,157
false
null
package glimpse internal class SquareMatrix(val size: Int, private val elements: (Int, Int) -> Float) { companion object { fun nullMatrix(size: Int) = SquareMatrix(size) { row, col -> 0f } fun identity(size: Int) = SquareMatrix(size) { row, col -> if (row == col) 1f else 0f } } operator fun get(row: Int, col: Int): Float { require(row in 0..size - 1) { "Row ${row} out of bounds: 0..${size - 1}" } require(col in 0..size - 1) { "Column ${col} out of bounds: 0..${size - 1}" } return elements(row, col) } /** * Determinant of the matrix. */ val det: Float by lazy { if (size == 1) this[0, 0] else (0..size - 1).map { item -> this[0, item] * comatrix[0, item] }.sum() } private val comatrix: SquareMatrix by lazy { SquareMatrix(size) { row, col -> cofactor(row, col) } } private fun cofactor(row: Int, col: Int): Float = minor(row, col) * if ((row + col) % 2 == 0) 1f else -1f private fun minor(row: Int, col: Int): Float = sub(row, col).det internal fun sub(delRow: Int, delCol: Int) = SquareMatrix(size - 1) { row, col -> this[if (row < delRow) row else row + 1, if (col < delCol) col else col + 1] } /** * Adjugate matrix. */ val adj: SquareMatrix by lazy { comatrix.transpose() } fun transpose(): SquareMatrix = SquareMatrix(size) { row, col -> this[col, row] } fun inverse(): SquareMatrix = SquareMatrix(size) { row, col -> adj[row, col] / det } operator fun times(other: SquareMatrix): SquareMatrix { require(other.size == size) { "Cannot multiply matrices of different sizes." } return SquareMatrix(size) { row, col -> (0..size - 1).map {this[row, it] * other[it, col] }.sum() } } fun asList(): List<Float> = (0..size * size - 1).map { this[it % size, it / size] } fun asMatrix(): Matrix = Matrix(asList()) }
0
Kotlin
0
16
5069cc1c3f2d8cb344740f3d33bcf11848f94583
1,800
glimpse-framework
Apache License 2.0
src/main/kotlin/days/day6/Day6.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day6 import days.Day class Day6 : Day(false) { override fun partOne(): Any { val times = readInput()[0].substringAfter(":").trim().split(" ").filter { it.isNotBlank() }.map { it.toInt() } val distances = readInput()[1].substringAfter(":").trim().split(" ").filter { it.isNotBlank() }.map { it.toInt() } var result = 1 for (i in times.indices) { var numberOfSolutions = 0 for (holddownTime in 1..<distances[i]) { val timeLeft = times[i] - holddownTime val distance = holddownTime * timeLeft if (distance > distances[i]) { numberOfSolutions++ } } result *= numberOfSolutions } return result } override fun partTwo(): Any { val times = readInput()[0].substringAfter(":").replace(" ", "").toLong() val distances = readInput()[1].substringAfter(":").replace(" ", "").toLong() var result: Long = 0 for (holddownTime in 1..<times) { val timeLeft = times - holddownTime val distance = holddownTime * timeLeft if (distance > distances) { result++ } } return result } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
1,295
advent-of-code_2023
The Unlicense
src/main/kotlin/g2901_3000/s2925_maximum_score_after_applying_operations_on_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2925_maximum_score_after_applying_operations_on_a_tree // #Medium #Dynamic_Programming #Depth_First_Search #Tree // #2024_01_16_Time_706_ms_(81.82%)_Space_84.7_MB_(27.27%) import kotlin.math.min class Solution { fun maximumScoreAfterOperations(edges: Array<IntArray>, values: IntArray): Long { var sum: Long = 0 val n = values.size val adj: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { adj.add(ArrayList()) } for (edge in edges) { adj[edge[0]].add(edge[1]) adj[edge[1]].add(edge[0]) } for (value in values) { sum += value.toLong() } val x = dfs(0, -1, adj, values) return sum - x } private fun dfs(node: Int, parent: Int, adj: List<MutableList<Int>>, values: IntArray): Long { if (adj[node].size == 1 && node != 0) { return values[node].toLong() } var sum: Long = 0 for (child in adj[node]) { if (child != parent) { sum += dfs(child, node, adj, values) } } return min(sum, values[node].toLong()) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,198
LeetCode-in-Kotlin
MIT License
Kotlin/RadixSort.kt
argonautica
212,698,136
false
{"Java": 42011, "C++": 24846, "C#": 15801, "Python": 14547, "Kotlin": 11794, "C": 10528, "JavaScript": 9054, "Assembly": 5049, "Go": 3662, "Ruby": 1949, "Lua": 687, "Elixir": 589, "Rust": 447}
fun main(args : Array<String>) { val sorted = radixSort(intArrayOf(4, 4, 4, 1, 7, 9, 5, 37564, 54, 0, 100)) sorted.forEach { print("$it, ") } } /** * Sorts positive numbers only using Radix Sort */ fun radixSort(input:IntArray):IntArray { var out = input val max = input.max() var exp = 1 while (max!!.div(exp) > 0) { //Loops through each place starting with the 0's place before incrementing out = countingRadixSort(out, exp) exp *= 10 } return out } fun countingRadixSort(input:IntArray, exp:Int):IntArray{ if(input.size == 1) { return input } //Array for counting the number of occurrences of each value var count = Array<MutableList<Int>>(10){ArrayList<Int>()} //Output array to store the sorted array var output = IntArray(input.size) //Stores each value in the array list corresponding with the value being checked in this round. input.forEach { value -> val radix = value.div(exp)%10 count[radix].add(value) } var pointer = 0 for(i in count.indices){ //Uses For loop rather than foreach to preserve the location in the count array. count[i].forEach { output[pointer] = it pointer++ } } return output }
4
Java
138
45
b9ebd2aadc6b59e5feba7d1fe9e0c6a036d33dba
1,294
sorting-algorithms
MIT License
solutions/src/AlmostSorted.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
class AlmostSorted { fun almostSorted(arr: Array<Int>) { var sorted = false; //Swap var swapIndicies = mutableSetOf<Int>() for (i in arr.indices) { if (i < arr.lastIndex && arr[i] > arr[i+1]) { swapIndicies.add(i) } if (i > 0 && arr[i] < arr[i-1]) { swapIndicies.add(i) } } var list = arr.toMutableList() var swapList = swapIndicies.toList() var swapOne = 0 var swapTwo = 0 when (swapIndicies.size) { 2 -> { //Possible Match swapTwo = 1 } 3 -> { swapTwo = 2 } 4 -> { swapTwo = 3 } } list[swapList[swapOne]] = arr[swapList[swapTwo]] list[swapList[swapTwo]] = arr[swapList[swapOne]] sorted = checkSorted(list) if (sorted) { println("yes") println("swap ${swapList[swapOne]+1} ${swapList[swapTwo]+1}") return } //Reverse var sortedAt = BooleanArray(arr.size) sortedAt[0] = true for (i in sortedAt.indices) { var sortedAtIndex = true; if (i > 0 && arr[i] < arr[i-1] ) { sortedAtIndex = false } if (i < sortedAt.lastIndex && arr[i] > arr[i+1]) { sortedAtIndex = false } sortedAt[i] = sortedAtIndex } var startIndex = -1 var endIndex = -1 var found = false for (i in sortedAt.indices) { if (!sortedAt[i] && startIndex == -1) { startIndex = i } if (!sortedAt[i] && !found) { endIndex = i } if (!sortedAt[i] && found) { println("no") return } if (sortedAt[i] && startIndex != -1 && endIndex != -1) { found = true } } var newList = if (startIndex > 0) { arr.toList().subList(0,startIndex) } else { listOf() } newList = newList+arr.toList().subList(startIndex,endIndex+1).reversed() if (endIndex < arr.lastIndex) { newList = newList+arr.toList().subList(endIndex+1,arr.size) } sorted = checkSorted(newList) if (sorted) { println("yes") println("reverse ${startIndex+1} ${endIndex+1}") return } println("no") } private fun checkSorted(list: List<Int>) : Boolean { var sorted = true var current = list[0] for (i in 1 until list.size) { if (list[i-1] >= list[i]) { sorted = false; } } return sorted } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
2,896
leetcode-solutions
MIT License
2023/4/solve-2.kts
gugod
48,180,404
false
{"Raku": 170466, "Perl": 121272, "Kotlin": 58674, "Rust": 3189, "C": 2934, "Zig": 850, "Clojure": 734, "Janet": 703, "Go": 595}
import java.io.File import kotlin.math.pow import kotlin.text.Regex class Card ( val id: Int, val winners: Set<Int>, val numbers: Set<Int>, ) { fun matchingNumbers () : Set<Int> = numbers.intersect(winners) } private fun String.findAllNumbers() = Regex("[0-9]+").findAll(this).map { it.value.toInt() } val cards = File(if (args.size == 0) "input" else args[0]).readLines().map { line -> var lineParts = Regex("[:|]").split(line) Card( id = Regex(" +").split(lineParts[0])[1].toInt(), winners = lineParts[1].findAllNumbers().toSet(), numbers = lineParts[2].findAllNumbers().toSet(), ) } var maxCardId = cards.last().id var cardKeeper = cards.map { Pair(it.id,1) }.toMap().toMutableMap() cards.map { card -> val copies = cardKeeper.get(card.id)!! (card.id + 1 .. card.id + card.matchingNumbers().count()).forEach { wonCardId -> if (wonCardId <= maxCardId) { cardKeeper.put(wonCardId, cardKeeper.get(wonCardId)!! + copies) } } } println(cardKeeper.values.sum().toString())
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,068
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day05.kt
rifkinni
573,123,064
false
{"Kotlin": 33155, "Shell": 125}
class LoadingDock(input: String) { val stacks: MutableList<Stack> init { val columnIndexes = regex.getMatchUnsafe(input, "columnIndex") val stacksString = regex.getMatchUnsafe(input, "stacks") val numColumns = maxColumn(columnIndexes) stacks = initializeStacks(numColumns) val rows = stacksString.split("\n") for (row in rows) { for (idx in row.indices step crateWidth) { val maybeCrate = row.slice(idx until idx + crateWidth - 1) val regex = Regex(Crate.pattern) val columnId = idx/ crateWidth if (regex.matches(maybeCrate)) { val value = regex.getMatchUnsafe(maybeCrate, "crate")[0] stacks[columnId].crates.add(Crate(value)) } } } } fun execute(instruction: Instruction) { val fromStack = stacks[instruction.startColumn - 1] val toStack = stacks[instruction.endColumn - 1] for (i in 1..instruction.numberOfCrates) { val element = fromStack.crates.removeFirst() toStack.crates.add(0, element) } } fun execute2(instruction: Instruction) { val fromStack = stacks[instruction.startColumn - 1] val toStack = stacks[instruction.endColumn - 1] val range = 0 until instruction.numberOfCrates val elementsToMove = fromStack.crates.slice(range) for (i in range) { fromStack.crates.removeAt(0) } toStack.crates.addAll(0, elementsToMove) } fun result(): String { return stacks .filter { it.crates.isNotEmpty() } .map { it.crates[0].value }.joinToString("") } private fun maxColumn(input: String): Int { return input.split(Regex("\\s")) .filter { it.isNotBlank() } .map { Integer.parseInt(it) } .max() } private fun initializeStacks(size: Int): MutableList<Stack> { val arr: MutableList<Stack> = ArrayList(size) for (i in 0 until size) { arr.add(i, Stack(i + 1, ArrayList())) } return arr } companion object { private const val crateWidth = 4 private val regex = Regex("^${Stack.pattern}(?<columnIndex>\\s*1[0-9\\s]+)") } } data class Crate(val value: Char) { companion object { const val pattern = "\\[(?<crate>[A-Z])\\]" } } data class Stack(val columnId: Int, val crates: MutableList<Crate>) { companion object { const val pattern = "(?<stacks>(\\s*${Crate.pattern})+)" } } class Instructions(input: String) { val instructions: List<Instruction> init { instructions = input.split("\n") .filter { it.isNotBlank() } .map { Instruction.buildViaRegex(it) } } } data class Instruction(val numberOfCrates: Int, val startColumn: Int, val endColumn: Int) { companion object { private const val pattern = "(move\\s(?<numberOfCrates>[0-9]+)\\sfrom\\s(?<startColumn>[0-9]+)\\sto\\s(?<endColumn>[0-9]+)[\n\\s]*)" fun buildViaRegex(input: String): Instruction { val regex = Regex(pattern) val numberOfCrates = Integer.parseInt(regex.getMatchUnsafe(input, "numberOfCrates")) val startColumn = Integer.parseInt(regex.getMatchUnsafe(input, "startColumn")) val endColumn = Integer.parseInt(regex.getMatchUnsafe(input, "endColumn")) return Instruction(numberOfCrates, startColumn, endColumn) } } } fun main() { fun part1(input: String, instructions: Instructions): String { var loadingDock = LoadingDock(input) instructions.instructions.forEach { instruction -> loadingDock.execute(instruction) } return loadingDock.result() } fun part2(input: String, instructions: Instructions): String { var loadingDock = LoadingDock(input) instructions.instructions.forEach { instruction -> loadingDock.execute2(instruction) } return loadingDock.result() } // test if implementation meets criteria from the description, like: val testInput = readChunk("Day05_test").split("\n\n") var instructions = Instructions(testInput[1]) check(part1(testInput[0], instructions) == "CMZ" ) check(part2(testInput[0], instructions) == "MCD" ) val input = readChunk("Day05").split("\n\n") instructions = Instructions(input[1]) println(part1(input[0], instructions)) println(part2(input[0], instructions)) }
0
Kotlin
0
0
c2f8ca8447c9663c0ce3efbec8e57070d90a8996
4,599
2022-advent
Apache License 2.0
leetcode/src/offer/middle/Offer34.kt
zhangweizhe
387,808,774
false
null
package offer.middle import linkedlist.TreeNode import java.util.* import kotlin.collections.ArrayList fun main() { // 剑指 Offer 34. 二叉树中和为某一值的路径 // https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/ } private fun pathSum(root: TreeNode?, target: Int): List<List<Int>> { val result = ArrayList<ArrayList<Int>>() val path = LinkedList<Int>() dfs(root, target, result, path) return result } private fun dfs(root: TreeNode?, target: Int, result: ArrayList<ArrayList<Int>>, path: LinkedList<Int>) { if (root == null) { return } path.offer(root.`val`) // 题目要求是从根节点到叶子节点,所以加上 root.left == null && root.right == null 的判断 if (root.`val` == target && root.left == null && root.right == null) { result.add(ArrayList(path)) } dfs(root.left, target - root.`val`, result, path) dfs(root.right, target - root.`val`, result, path) path.pollLast() }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,016
kotlin-study
MIT License
src/main/kotlin/aoc2015/day03_spherical_houses/SphericalHouses.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2015.day03_spherical_houses import geom2d.Point import geom2d.toDir import kotlin.streams.toList fun main() { util.solve(2565, ::partOne) util.solve(2639, ::partTwo) } private fun String.toDirList() = this .chars() .mapToObj { it.toChar().toDir() } .toList() fun partOne(input: String): Int { val origin = Point.ORIGIN val points = mutableSetOf(origin) input.toDirList() .fold(origin) { curr, dir -> val next = curr.step(dir) points += next next } return points.size } fun partTwo(input: String): Int { val origin = Point.ORIGIN val points = mutableSetOf(origin) input.toDirList() .foldIndexed(Pair(origin, origin)) { i, (s, rs), dir -> if (i % 2 == 0) { val next = s.step(dir) points += next Pair(next, rs) } else { val next = rs.step(dir) points += next Pair(s, next) } } return points.size }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
1,064
aoc-2021
MIT License
src/leetcodeProblem/leetcode/editor/en/ReverseWordsInAStringIii.kt
faniabdullah
382,893,751
false
null
//Given a string s, reverse the order of characters in each word within a //sentence while still preserving whitespace and initial word order. // // // Example 1: // Input: s = "Let's take LeetCode contest" //Output: "s'teL ekat edoCteeL tsetnoc" // Example 2: // Input: s = "<NAME>" //Output: "doG gniD" // // // Constraints: // // // 1 <= s.length <= 5 * 10⁴ // s contains printable ASCII characters. // s does not contain any leading or trailing spaces. // There is at least one word in s. // All the words in s are separated by a single space. // // Related Topics Two Pointers String 👍 1910 👎 121 package leetcodeProblem.leetcode.editor.en class ReverseWordsInAStringIii { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun reverseWords(s: String): String { var s = s.toCharArray() var left = 0 var right = 1 while (right < s.size) { if (s[right].isWhitespace() && !s[right - 1].isWhitespace() && right > 1 || right == s.lastIndex && right > 1) { var tempLeft = left var tempRight = right - 1 while (tempLeft < tempRight) { val temp = s[tempRight] s[tempRight] = s[tempLeft] s[tempLeft] = temp tempLeft++ tempRight-- } left = right + 1 right++ } else if (s[right].isWhitespace() && s[right - 1].isWhitespace()) { left = right + 1 right++ } else { right++ } } return String(s) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() { ReverseWordsInAStringIii.Solution().reverseWords("Let's take LeetCode contest") }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,096
dsa-kotlin
MIT License
common/src/commonMain/kotlin/data/Ratings.kt
DennisTsar
555,073,105
false
{"Kotlin": 31172}
package data typealias Ratings = List<List<Int>> class RatingStats( val ratings: List<Double>, val numResponses: Int, ) // returns list of (# of 1s, # of 2s, ... # of 5s) for each question // note that entries must have scores.size>=100 - maybe throw error? // ***IMPORTANT NOTE*** By default, don't give ratings for question index 7 - as it's mostly irrelevant fun List<Entry>.getTotalRatings(excludeQuestion7: Boolean = true): Ratings { return map { entry -> // group by question (there are 10 nums in table per question) // + we only care about first 5 nums per Q (the actual ratings) which are all int amounts entry.scores.chunked(10) .map { it.subList(0, 5).map(Double::toInt) } .run { if (excludeQuestion7) (subList(0, 7) + subList(8, 10)) else this } }.combine() } fun Collection<Ratings>.combine(): Ratings { return reduce { accByQuestion, responsesByQ -> // nums from each entry get zipped with each other, by question accByQuestion.zip(responsesByQ) { accRatings, ratings -> accRatings.zip(ratings, Int::plus) } } } fun List<Int>.getRatingStats(): Pair<Double, Int> { val numResponses = sum() val ave = mapIndexed { index, num -> (index + 1) * num }.sum().toDouble() / numResponses return ave.roundToDecimal(2) to numResponses } fun List<Int>.getRatingAve(): Double = getRatingStats().first fun Ratings.getAvesAndTotal(): RatingStats { // list of aves per question + ave # of responses return RatingStats(ratings = map { it.getRatingAve() }, numResponses = map { it.sum() }.average().toInt()) }
0
Kotlin
0
4
8ed0afdf5f1024bb8c56398fad049eb512dc8398
1,647
RU-SIRS
MIT License
src/main/kotlin/com/sk/set29/2975. Maximum Square Area by Removing Fences From a Field.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set29 import kotlin.math.abs class Solution2975 { fun maximizeSquareArea( m: Int, n: Int, hFences: IntArray, vFences: IntArray ): Int { vFences.sort() hFences.sort() val X = mutableListOf<Int>() X.add(0) for(x in vFences) X.add(x-1) X.add(n-1) val Y = mutableListOf<Int>() Y.add(m-1) for(i in hFences.reversed()) { Y.add(i-1) } Y.add(0) Y.reverse() var ans = 0 for(x in X.indices) { for(y in Y.indices) { // x,y is starting point var i = x var j = y while(i < X.size && j < Y.size) { val width = X[i] - X[x] val height = Y[j] - Y[y] if(width == height) { ans = maxOf(ans, width * height) } when { width < height && i < X.size-1 -> i++ height < width && j < Y.size-1 -> j++ else -> { i++ j++ } } } } } return if(ans == 0) -1 else ans } fun maximizeSquareArea2( m: Int, n: Int, hFences: IntArray, vFences: IntArray ): Int { var ans = 0L val mod: Long = 1000_000_007 val stripe = mutableSetOf<Int>() val horizontal = IntArray(hFences.size+2) hFences.copyInto(horizontal, 0, 0, hFences.size) horizontal[hFences.size] = 1 horizontal[hFences.size+1] = m val vertical = IntArray(vFences.size+2) vFences.copyInto(vertical, 0, 0, vFences.size) vertical[vFences.size] = 1 vertical[vFences.size+1] = n for (i in horizontal.indices) { for (j in horizontal.indices) { if (i != j) stripe.add(abs(horizontal[i] - horizontal[j])) } } for (i in vertical.indices) { for (j in vertical.indices) { if (stripe.contains(abs(vertical[i] - vertical[j]))) { ans = maxOf(ans, abs(vertical[i] - vertical[j]).toLong()) } } } return if (ans == 0L) -1 else (ans * ans % mod).toInt() } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,385
leetcode-kotlin
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2021/Day9.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.mul import java.awt.Color import java.awt.image.BufferedImage import java.io.File import javax.imageio.ImageIO /** * --- Day 9: Smoke Basin --- * https://adventofcode.com/2021/day/9 */ class Day9 : Solver { override fun solve(lines: List<String>): Result { val input = PuzzleInput(lines) var partA = 0 for (x in 0 until input.width) { for (y in 0 until input.height) { val pos = XY(x, y) val elevation = input.height(pos) val adjacent = pos.adjacent().map { input.height(it) }.toSet() if (elevation < adjacent.min()!!) { partA += elevation + 1 } } } // Calculate which positions flow directly into which other. val flownInto = mutableMapOf<XY, MutableSet<XY>>() for (x in 0 until input.width) { for (y in 0 until input.height) { val pos = XY(x, y) flownInto[pos] = mutableSetOf() val elevation = input.height(pos) val checkCandidate = { p: XY -> val neighbor = input.height(p) if (neighbor in (elevation + 1)..8) flownInto[pos]!!.add(p) } pos.adjacent().forEach { checkCandidate(it) } } } // Group basins together by recursively combining flows. val flownIntoResult = flownInto.keys.associateWith { allThatFlowInto(it, flownInto) } // Take top 3 sizes and multiply them together. val partB = flownIntoResult.map { it.value.size }.sortedDescending().take(3).mul() writeImage(input, flownIntoResult) return Result("$partA", "$partB") } /** Recursively get a complete list of all that flows into 'pos'. */ private fun allThatFlowInto(pos: XY, flownInto: Map<XY, MutableSet<XY>>): MutableSet<XY> { // First add itself, then recursively everything else that flows into it. val result = mutableSetOf(pos) for (flowsInto in flownInto[pos]!!) { result.addAll(allThatFlowInto(flowsInto, flownInto)) } return result } // Just for fun... private fun writeImage(puzzle: PuzzleInput, basins: Map<XY, Set<XY>>) { val winningPositions = basins.map { it.value }.sortedByDescending { it.size }.take(3).flatten().toSet() val img = BufferedImage(puzzle.width, puzzle.height, BufferedImage.TYPE_INT_RGB) for (x in 0 until puzzle.width) { for (y in 0 until puzzle.height) { val hue = if (winningPositions.contains(XY(x, y))) 1f else 0.5f img.setRGB(x, y, Color.HSBtoRGB(hue, 1f, 1f - puzzle.height(XY(x, y)) / 9f)) } } val file = File("Day9.png") println(file.absolutePath) ImageIO.write(img, "png", file) } } private data class XY(val x: Int, val y: Int) private fun XY.adjacent() = setOf(XY(x - 1, y), XY(x + 1, y), XY(x, y + 1), XY(x, y - 1)) private class PuzzleInput(lines_: List<String>) { val lines = lines_ val width = lines[0].length val height = lines.size fun height(pos: XY): Int { if (pos.x < 0 || pos.x >= width || pos.y < 0 || pos.y >= height) return Int.MAX_VALUE return lines[pos.y][pos.x].toString().toInt() } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,140
euler
Apache License 2.0
solutions/aockt/y2015/Y2015D11.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2015 import io.github.jadarma.aockt.core.Solution object Y2015D11 : Solution { // Predicates for a valid password private val illegalCharacterRule = Regex("""[iol]""") private val doublePairRule = Regex("""(.)\1(?!.*\1.*$).*(.)\2""") private val passwordValidationRules: List<(String) -> Boolean> = listOf( { !it.contains(illegalCharacterRule) }, { it.contains(doublePairRule) }, { it.windowed(3).any { c -> c[0] + 1 == c[1] && c[1] + 1 == c[2] } }, ) /** Returns the next password by incrementing and handling letter overflows. */ private fun String.incrementPassword(): String { val chars = toCharArray() for (i in chars.indices.reversed()) { chars[i] = if (chars[i] == 'z') 'a' else chars[i] + 1 if (chars[i] != 'a') break } return String(chars) } /** Generates valid passwords in ascending order starting from the [seed], but excluding it even if valid. */ private fun passwordSequence(seed: String) = generateSequence(seed) { it.incrementPassword() } .drop(1) .filter { candidate -> passwordValidationRules.all { rule -> rule(candidate) } } override fun partOne(input: String) = passwordSequence(input).first() override fun partTwo(input: String) = passwordSequence(input).drop(1).first() }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
1,378
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/com/nibado/projects/advent/y2017/Day14.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.* import com.nibado.projects.advent.Point object Day14 : Day { private val rows = (0..127).map { "amgozmfv-$it" } private val square : List<String> by lazy { rows.map { hash(it) }.map { toBinary(it) } } override fun part1() = square.sumBy { it.count { it == '1' } }.toString() override fun part2(): String { val points = (0 .. 127).flatMap { x -> (0 .. 127 ).map { y -> Point(x, y) } }.toMutableSet() val visited = points.filter { square[it.y][it.x] == '0'}.toMutableSet() points.removeAll(visited) var count = 0 while(!points.isEmpty()) { count++ fill(visited, points, points.first()) } return count.toString() } private fun fill(visited: MutableSet<Point>, points: MutableSet<Point>, current: Point) { visited += current points -= current current.neighborsHv().filter { points.contains(it) }.forEach { fill(visited, points, it) } } private fun hash(input: String): String { val chars = input.toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23) return (0..15).map { Day10.knot(chars, 64).subList(it * 16, it * 16 + 16) }.map { xor(it) }.toHex() } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,301
adventofcode
MIT License
Hangman/getRoundResultsFunction/src/main/kotlin/jetbrains/kotlin/course/hangman/Main.kt
jetbrains-academy
504,249,857
false
{"Kotlin": 1108971}
package jetbrains.kotlin.course.hangman // You will use this function later fun getGameRules(wordLength: Int, maxAttemptsCount: Int) = "Welcome to the game!$newLineSymbol$newLineSymbol" + "In this game, you need to guess the word made by the computer.$newLineSymbol" + "The hidden word will appear as a sequence of underscores, one underscore means one letter.$newLineSymbol" + "You have $maxAttemptsCount attempts to guess the word.$newLineSymbol" + "All words are English words, consisting of $wordLength letters.$newLineSymbol" + "Each attempt you should enter any one letter,$newLineSymbol" + "if it is in the hidden word, all matches will be guessed.$newLineSymbol$newLineSymbol" + "" + "For example, if the word \"CAT\" was guessed, \"_ _ _\" will be displayed first, " + "since the word has 3 letters.$newLineSymbol" + "If you enter the letter A, you will see \"_ A _\" and so on.$newLineSymbol$newLineSymbol" + "" + "Good luck in the game!" // You will use this function later fun isWon(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = complete && attempts <= maxAttemptsCount // You will use this function later fun isLost(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = !complete && attempts > maxAttemptsCount fun deleteSeparator(guess: String) = guess.replace(separator, "") fun isComplete(secret: String, currentGuess: String) = secret == deleteSeparator(currentGuess) fun generateNewUserWord(secret: String, guess: Char, currentUserWord: String): String { var newUserWord = "" for (i in secret.indices) { newUserWord += if (secret[i] == guess) { "${secret[i]}$separator" } else { "${currentUserWord[i * 2]}$separator" } } // Just newUserWord will be ok for the tests return newUserWord.removeSuffix(separator) } fun generateSecret() = words.random() fun getHiddenSecret(wordLength: Int) = List(wordLength) { underscore }.joinToString(separator) fun isCorrectInput(userInput: String): Boolean { if (userInput.length != 1) { println("The length of your guess should be 1! Try again!") return false } if (!userInput[0].isLetter()) { println("You should input only English letters! Try again!") return false } return true } fun safeUserInput(): Char { var guess: String var isCorrect: Boolean do { println("Please input your guess.") guess = safeReadLine() isCorrect = isCorrectInput(guess) } while (!isCorrect) return guess.uppercase()[0] } fun getRoundResults(secret: String, guess: Char, currentUserWord: String): String { if (guess !in secret) { println("Sorry, the secret does not contain the symbol: $guess. The current word is $currentUserWord") return currentUserWord } val newUserWord = generateNewUserWord(secret, guess, currentUserWord) println("Great! This letter is in the word! The current word is $newUserWord") return newUserWord } fun main() { // Uncomment this code on the last step of the game // println(getGameRules(wordLength, maxAttemptsCount)) // playGame(generateSecret(), maxAttemptsCount) }
14
Kotlin
1
6
bc82aaa180fbd589b98779009ca7d4439a72d5e5
3,270
kotlin-onboarding-introduction
MIT License
src/main/kotlin/days/Day12.kt
hughjdavey
225,440,374
false
null
package days import kotlin.math.abs class Day12 : Day(12) { private fun moonPositions() = inputList.map { it.replace(Regex("[<>=xyz ]"), "") }.map { val (x, y, z) = it.split(",").map { it.toInt() } Coord3D(x, y, z) } override fun partOne(): Any { val moonTracker = MoonTracker(moonPositions()) moonTracker.simulate(1000) return moonTracker.totalEnergy() } override fun partTwo(): Any { val moonTracker = MoonTracker(moonPositions()) return moonTracker.firstRepeat() } data class Coord3D(var x: Int, var y: Int, var z: Int) { fun addAll(other: Coord3D) { this.x += other.x this.y += other.y this.z += other.z } fun absSum(): Int = abs(x) + abs(y) + abs(z) } data class Moon(var position: Coord3D, var velocity: Coord3D = Coord3D(0, 0, 0)) { fun totalEnergy(): Int = potentialEnergy() * kineticEnergy() private fun potentialEnergy(): Int = position.absSum() private fun kineticEnergy(): Int = velocity.absSum() } class MoonTracker(moonPositions: List<Coord3D>) { val moons = moonPositions.map { Moon(it) }.toMutableList() private var timeStep = 0 fun simulate(steps: Int, debug: Boolean = false) { if (debug) printState() while (timeStep < steps) { step() if (debug) { printState() System.err.println() } } } fun step() { // update velocity by applying gravity for (i in moons) { for (j in moons) { if (i === j) { continue } if (i.position.x < j.position.x) { i.velocity.x++ } else if (i.position.x > j.position.x) { i.velocity.x-- } if (i.position.y < j.position.y) { i.velocity.y++ } else if (i.position.y > j.position.y) { i.velocity.y-- } if (i.position.z < j.position.z) { i.velocity.z++ } else if (i.position.z > j.position.z) { i.velocity.z-- } } } // update position by applying velocity moons.forEach { it.position.addAll(it.velocity) } timeStep += 1 } fun totalEnergy(): Int { return moons.map { it.totalEnergy() }.sum() } fun firstRepeat(): Long { val (initialXPos, initialYPos, initialZPos) = listOf(xPos(), yPos(), zPos()) val (initialXVel, initialYVel, initialZVel) = listOf(xVel(), yVel(), zVel()) var (xCycleStep, yCycleStep, zCycleStep) = listOf(-1, -1, -1) var steps = 0 while (xCycleStep == -1 || yCycleStep == -1 || zCycleStep == -1) { steps++ step() when { xCycleStep == -1 && initialXPos == xPos() && initialXVel == xVel() -> xCycleStep = steps yCycleStep == -1 && initialYPos == yPos() && initialYVel == yVel() -> yCycleStep = steps zCycleStep == -1 && initialZPos == zPos() && initialZVel == zVel() -> zCycleStep = steps } } return lcm(xCycleStep.toLong(), lcm(yCycleStep.toLong(), zCycleStep.toLong())) } private fun printState() { System.err.println("After $timeStep steps:") moons.forEach { System.err.println(it) } } private fun xPos() = moons.map { it.position.x + 0 } private fun yPos() = moons.map { it.position.y + 0 } private fun zPos() = moons.map { it.position.z + 0 } private fun xVel() = moons.map { it.velocity.x + 0 } private fun yVel() = moons.map { it.velocity.y + 0 } private fun zVel() = moons.map { it.velocity.z + 0 } companion object { private fun lcm(x: Long, y: Long): Long { var a = x var b = y while (a != 0L) { a = (b % a).also { b = a } } return x / b * y } } } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
4,166
aoc-2019
Creative Commons Zero v1.0 Universal
common/search/src/main/kotlin/com/curtislb/adventofcode/common/search/FindSum.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.common.search /** * Returns a list of [minSize] or more contiguous values in the iterable that sum to [targetSum], * or `null` if are no such values. * * @throws IllegalArgumentException If [targetSum] or [minSize] is negative, or a negative value is * encountered during iteration. */ fun Iterable<Long>.findNonNegativeSubarraySum(targetSum: Long, minSize: Int = 0): List<Long>? { require(targetSum >= 0L) { "Target sum must be non-negative: $targetSum" } require(minSize >= 0L) { "Minimum size must be non-negative: $minSize" } // Empty subarray has a sum of 0 if (targetSum == 0L && minSize == 0) { return emptyList() } // Use a resizing window to scan for a subarray that sums to the target val deque = ArrayDeque<Long>() var total = 0L for (value in this) { require(value >= 0L) { "Each value must be non-negative: $value" } // Add value to the end of the window total += value deque.addLast(value) // Remove values from the start of the window (as needed) while (total > targetSum) { total -= deque.removeFirst() } // Check if the target sum is reached if (total == targetSum && deque.size >= minSize) { return deque.toList() } } // No subarray found return null } /** * Returns any two values in the iterable that sum to [targetSum], or `null` if there are no such * values. */ fun Iterable<Int>.findPairSum(targetSum: Int): Pair<Int, Int>? { // Iterate while keeping track of previously seen values val prevValues = mutableSetOf<Int>() for (value in this) { // Check if this and any previous value sum to the target val remainder = targetSum - value if (remainder in prevValues) { return Pair(remainder, value) } prevValues.add(value) } // No pair found return null } /** * Returns any two values in the iterable that sum to [targetSum], or `null` if there are no such * values. */ fun Iterable<Long>.findPairSum(targetSum: Long): Pair<Long, Long>? { // Iterate while keeping track of previously seen values val prevValues = mutableSetOf<Long>() for (value in this) { // Check if this and any previous value sum to the target val remainder = targetSum - value if (remainder in prevValues) { return Pair(remainder, value) } prevValues.add(value) } // No pair found return null } /** * Returns any three values in the iterable that sum to [targetSum], or `null` if there are no such * values. */ fun Iterable<Int>.findTripleSum(targetSum: Int): Triple<Int, Int, Int>? { // Sort the values into a list val sortedValues = sorted() // Fix each first value and search for more values to the right of it for (i in 0..(sortedValues.lastIndex - 2)) { // Find target sum for the second and third values val value1 = sortedValues[i] val remainder = targetSum - value1 // Search for second and third values that sum to remainder var j = i + 1 var k = sortedValues.lastIndex while (j < k) { val value2 = sortedValues[j] val value3 = sortedValues[k] val twoThreeSum = value2 + value3 when { twoThreeSum < remainder -> j++ twoThreeSum > remainder -> k-- else -> return Triple(value1, value2, value3) } } } // No triple found return null } /** * Returns any three values in the iterable that sum to [targetSum], or `null` if there are no such * values. */ fun Iterable<Long>.findTripleSum(targetSum: Long): Triple<Long, Long, Long>? { // Sort the values into a list val sortedValues = sorted() // Fix first value and search for more values to the right for (i in 0..(sortedValues.lastIndex - 2)) { // Find target sum for the second and third values val value1 = sortedValues[i] val remainder = targetSum - value1 // Search for second and third values that sum to remainder var j = i + 1 var k = sortedValues.lastIndex while (j < k) { val value2 = sortedValues[j] val value3 = sortedValues[k] val twoThreeSum = value2 + value3 when { twoThreeSum < remainder -> j++ twoThreeSum > remainder -> k-- else -> return Triple(value1, value2, value3) } } } // No triple found return null }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
4,658
AdventOfCode
MIT License
src/Day10.kt
dizney
572,581,781
false
{"Kotlin": 105380}
object Day10 { const val EXPECTED_PART1_CHECK_ANSWER = 13140 const val EXPECTED_PART2_CHECK_ANSWER = 1 val CYCLE_PROBE_POINTS = listOf(20, 60, 100, 140, 180, 220) const val CRT_LINE_WIDTH = 40 } sealed class CpuInstruction(val cycles: Int) class Noop : CpuInstruction(1) class AddX(val arg: Int) : CpuInstruction(2) class Cpu(val instructions: List<CpuInstruction>) : ClockListener { private var instructionPointer: Int = 0 private var instructionCyclesDone: Int = 0 private val x: MutableList<Int> = mutableListOf(1) fun isDone() = instructionPointer >= instructions.size fun xAtCycle(cycle: Int) = x[cycle - 1] fun x() = x.last() override fun tickStart(cycle: Int) { // NOOP } override fun tickEnd(cycle: Int) { instructionCyclesDone++ val currentXValue = if (x.isEmpty()) 1 else x.last() when (val currentInstruction = instructions[instructionPointer]) { is Noop -> { x.add(currentXValue) instructionPointer++ instructionCyclesDone = 0 } is AddX -> { if (currentInstruction.cycles == instructionCyclesDone) { x.addAll(listOf(currentXValue, currentXValue + currentInstruction.arg)) instructionPointer++ instructionCyclesDone = 0 } } } } } class Crt(private val cpu: Cpu) : ClockListener { override fun tickStart(cycle: Int) { val crtPos = cycle - 1 val lineNumber = crtPos / Day10.CRT_LINE_WIDTH val positionInLine = crtPos - lineNumber * Day10.CRT_LINE_WIDTH print(if (positionInLine in (cpu.x() - 1)..(cpu.x() + 1)) "#" else ".") if (crtPos > 0 && cycle % Day10.CRT_LINE_WIDTH == 0) println() } override fun tickEnd(cycle: Int) { // NOOP } } interface ClockListener { fun tickStart(cycle: Int) fun tickEnd(cycle: Int) } fun main() { fun List<String>.parseInstructions(): List<CpuInstruction> = map { it.split(" ") }.map { when (it[0]) { "noop" -> Noop() "addx" -> AddX(it[1].toInt()) else -> error("Unknown operation ${it[0]}") } } fun part1(input: List<String>): Int { val cpu = Cpu(input.parseInstructions()) var cycle = 1 while (!cpu.isDone()) { cpu.tickStart(cycle) cpu.tickEnd(cycle) cycle++ } return Day10.CYCLE_PROBE_POINTS.sumOf { cpu.xAtCycle(it) * it } } fun part2(input: List<String>): Int { println("\n\n") val cpu = Cpu(input.parseInstructions()) val crt = Crt(cpu) var cycle = 1 while (!cpu.isDone()) { cpu.tickStart(cycle) crt.tickStart(cycle) cpu.tickEnd(cycle) crt.tickEnd(cycle) cycle++ } return 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == Day10.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" } check(part2(testInput) == Day10.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f684a4e78adf77514717d64b2a0e22e9bea56b98
3,374
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/Day11.kt
clechasseur
267,632,210
false
null
object Day11 { private val input = IsolatedArea(listOf( Floor(setOf( InterestingObject("thulium", ObjectType.GENERATOR), InterestingObject("thulium", ObjectType.MICROCHIP), InterestingObject("plutonium", ObjectType.GENERATOR), InterestingObject("strontium", ObjectType.GENERATOR) )), Floor(setOf( InterestingObject("plutonium", ObjectType.MICROCHIP), InterestingObject("strontium", ObjectType.MICROCHIP) )), Floor(setOf( InterestingObject("promethium", ObjectType.GENERATOR), InterestingObject("promethium", ObjectType.MICROCHIP), InterestingObject("ruthenium", ObjectType.GENERATOR), InterestingObject("ruthenium", ObjectType.MICROCHIP) )), Floor(emptySet()) ), elevatorFloorIdx = 0) fun part1(): Int = countSteps(input) fun part2(): Int = countSteps( IsolatedArea(listOf( Floor(input.floors[0].objects + setOf( InterestingObject("elerium", ObjectType.GENERATOR), InterestingObject("elerium", ObjectType.MICROCHIP), InterestingObject("dilithium", ObjectType.GENERATOR), InterestingObject("dilithium", ObjectType.MICROCHIP) )), input.floors[1], input.floors[2], input.floors[3] ), elevatorFloorIdx = input.elevatorFloorIdx) ) private fun countSteps(initialState: IsolatedArea): Int { var steps = 0 var states = setOf(initialState) var seenStates = emptySet<Int>() while (states.none { it.finished }) { states = states.asSequence().flatMap { nextSteps(it) }.filterNot { it.hashCode() in seenStates }.toSet() seenStates = seenStates + states.map { it.hashCode() } require(states.isNotEmpty()) { "No way to get to the final state" } steps++ } return steps } private fun nextSteps(state: IsolatedArea): Sequence<IsolatedArea> = sequence { val curFloorIdx = state.elevatorFloorIdx when (curFloorIdx) { state.floors.indices.first -> listOf(state.floors.indices.first + 1) state.floors.indices.last -> listOf(state.floors.indices.last - 1) else -> listOf(curFloorIdx - 1, curFloorIdx + 1) }.forEach { destFloorIdx -> state.floors[curFloorIdx].objects.forEach { obj -> val newFloors = state.floors.toMutableList() newFloors[curFloorIdx] = Floor(newFloors[curFloorIdx].objects - obj) newFloors[destFloorIdx] = Floor(newFloors[destFloorIdx].objects + obj) val newState = IsolatedArea(newFloors, destFloorIdx) if (newState.valid) { yield(newState) } } state.floors[curFloorIdx].objects.forEachIndexed { idx1, obj1 -> state.floors[curFloorIdx].objects.drop(idx1 + 1).forEach { obj2 -> val newFloors = state.floors.toMutableList() newFloors[curFloorIdx] = Floor(newFloors[curFloorIdx].objects - setOf(obj1, obj2)) newFloors[destFloorIdx] = Floor(newFloors[destFloorIdx].objects + setOf(obj1, obj2)) val newState = IsolatedArea(newFloors, destFloorIdx) if (newState.valid) { yield(newState) } } } } } private enum class ObjectType(val id: String) { GENERATOR("G"), MICROCHIP("M"), } private data class InterestingObject(val element: String, val type: ObjectType) { override fun toString(): String = "${element[0].toUpperCase()}${element[1]}${type.id}" } private data class Floor(val objects: Set<InterestingObject>) { val valid: Boolean get() = !(objects.any { it.type == ObjectType.GENERATOR } && objects.any { microchip -> microchip.type == ObjectType.MICROCHIP && objects.none { generator -> generator.type == ObjectType.GENERATOR && generator.element == microchip.element } }) override fun toString(): String = "[${objects.joinToString(",")}]" } private data class IsolatedArea(val floors: List<Floor>, val elevatorFloorIdx: Int) { init { require(floors.size == 4) { "Isolated area needs to have 4 floors" } require(elevatorFloorIdx in floors.indices) { "Elevator needs to be on a valid floor" } } val valid: Boolean get() = floors.all { it.valid } val finished: Boolean get() = floors.dropLast(1).all { it.objects.isEmpty() } && elevatorFloorIdx == floors.indices.last override fun toString(): String = "{[" + floors.mapIndexed { i, f -> "$i${if (i == elevatorFloorIdx) "*" else ""}: $f" }.joinToString(",") + "]}" } }
0
Kotlin
0
0
120795d90c47e80bfa2346bd6ab19ab6b7054167
5,033
adventofcode2016
MIT License
src/main/kotlin/me/grison/aoc/Graphs.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc import util.CYAN import java.util.* import java.util.function.Predicate import kotlin.collections.ArrayDeque import kotlin.collections.set import kotlin.math.pow typealias Graph<T> = MutableMap<T, MutableList<T>> fun <T> List<Pair<T, T>>.toGraph() = graph(this) fun <T> graph(edges: List<Pair<T, T>>): Graph<T> { val graph = mutableMapOf<T, MutableList<T>>() for ((a, b) in edges) { if (a !in graph) graph[a] = mutableListOf() if (b !in graph) graph[b] = mutableListOf() graph[a]!!.add(b) graph[b]!!.add(a) } return graph } fun <T> List<Pair<T, T>>.toDirectedGraph() = directedGraph(this) fun <T> directedGraph(edges: List<Pair<T, T>>): Graph<T> { val graph = mutableMapOf<T, MutableList<T>>() for ((a, b) in edges) { if (a !in graph) graph[a] = mutableListOf() graph[a]!!.add(b) } return graph } /* find the shortest path between two nodes a and b, returns -1 if no connection found */ fun <T> Graph<T>.shortestPath(a: T, b: T): Pair<Int, List<T>> { val visited = mutableSetOf(a) val queue = ArrayDeque<Triple<T, Int, MutableList<T>>>() queue.addLast(Triple(a, 0, mutableListOf(a))) while (queue.size > 0) { val (node, distance, path) = queue.shift() if (b == node) return p(distance, path) for (neighbor in (this[node] ?: listOf())) { if (neighbor !in visited) { visited.add(neighbor) val newPath = path.toMutableList() + neighbor val t = Triple(neighbor, distance + 1, newPath) queue.addLast(t) } } } return p(-1, listOf()) } fun <T> Graph<T>.hasPath(source: T, destination: T): Boolean { bfsIterator(source).let { while (it.hasNext()) { if (it.next() == destination) return true } return false } } fun <T> Graph<T>.depthFirst(root: T, visitor: (T) -> Unit) { val stack = Stack<T>() stack.push(root) val visited = mutableSetOf<T>() while (!stack.isEmpty()) { val current = stack.pop() if (current !in visited) { visited.add(current) visitor(current) for (neighbor in this[current]!!) { if (neighbor !in visited) { stack.push(neighbor) } } } } } fun <T> Graph<T>.dfsIterator(source: T): Iterator<T> { val stack = Stack<T>() stack.push(source) val graph = this val visited = mutableSetOf<T>() return object : Iterator<T> { override fun hasNext(): Boolean { if (stack.isEmpty()) return false while (stack.isNotEmpty() && stack.last() in visited) { stack.pop() } return stack.isNotEmpty() } override fun next(): T { val current = stack.pop() visited.add(current) for (neighbor in graph[current]!!) { if (neighbor !in visited) { stack.push(neighbor) } } return current } } } fun <T> Graph<T>.breadthFirst(source: T, visitor: (T) -> Unit) { val queue = ArrayDeque<T>() queue.add(source) val visited = mutableSetOf<T>() while (!queue.isEmpty()) { val current = queue.shift() if (current !in visited) { visited.add(current) visitor(current) for (neighbor in this[current]!!) { if (neighbor !in visited) { queue.add(neighbor) } } } } } fun <T> Graph<T>.bfsIterator(source: T): Iterator<T> { val queue = ArrayDeque<T>() queue.add(source) val graph = this val visited = mutableSetOf<T>() return object : Iterator<T> { override fun hasNext(): Boolean { if (queue.isEmpty()) return false while (queue.isNotEmpty() && queue.first() in visited) { queue.shift() } return queue.isNotEmpty() } override fun next(): T { val current = queue.shift() visited.add(current) for (neighbor in graph[current]!!) { if (neighbor !in visited) { queue.add(neighbor) } } return current } } } fun <T> Graph<T>.connectedComponentsCount(): Int { fun explore(graph: Graph<T>, current: T, visited: MutableSet<T>): Boolean { if (current in visited) return false visited.add(current) for (neighbor in graph[current]!!) { explore(graph, neighbor, visited) } return true } val visited = mutableSetOf<T>() var count = 0 for (node in this.keys) { if (explore(this, node, visited)) count += 1 } return count } fun <T> Graph<T>.largestComponent(): Int { return sizedComponent(0) { a, b -> kotlin.math.max(a, b) } } fun <T> Graph<T>.smallestComponent(): Int { return sizedComponent(Int.MAX_VALUE) { a, b -> kotlin.math.min(a, b) } } private fun <T> Graph<T>.sizedComponent(default: Int, choser: (Int, Int) -> Int): Int { fun explore(graph: Graph<T>, current: T, visited: MutableSet<T>): Int { if (current in visited) return 0 visited.add(current) var size = 1 for (neighbor in graph[current]!!) { size += explore(graph, neighbor, visited) } return size } val visited = mutableSetOf<T>() var sizeval = default for (node in this.keys) { val size = explore(this, node, visited) sizeval = choser(size, sizeval) // if (size > longest) longest = size } return sizeval } fun <T> Grid<T>.allInDirection(pos: Pair<Int, Int>, dir: Pair<Int, Int>) : List<Pair<Int, Int>> { var cursor = pos val list = mutableListOf<Pair<Int, Int>>() while (true) { cursor += dir if (cursor !in this) { break } list.add(cursor) } return list } fun <T> Grid<T>.islandCount(symbol: T, dimensions: Pair<Int, Int>): Int { fun explore(grid: Grid<T>, pos: Position, visited: MutableSet<Position>): Boolean { if (!pos.within(0, 0, dimensions.first, dimensions.second)) return false if (grid.getValue(pos) != symbol) return false if (pos in visited) return false visited.add(pos) explore(grid, pos.above(), visited) // above explore(grid, pos.below(), visited) // below explore(grid, pos.left(), visited) // left explore(grid, pos.right(), visited) // right return true } val visited = mutableSetOf<Position>() var count = 0 gridPositions(dimensions).forEach { pos -> if (explore(this, pos, visited)) count++ } return count } fun <T> Grid<T>.minimumIsland(symbol: T, dimensions: Pair<Int, Int>) = minMaxIsland(symbol, dimensions).first fun <T> Grid<T>.maximumIsland(symbol: T, dimensions: Pair<Int, Int>) = minMaxIsland(symbol, dimensions).second private fun <T> Grid<T>.minMaxIsland(symbol: T, dimensions: Pair<Int, Int>): Pair<Int, Int> { fun explore(grid: Grid<T>, pos: Position, visited: MutableSet<Position>): Int { if (!pos.within(0, 0, dimensions.first, dimensions.second)) return 0 if (grid.getValue(pos) != symbol) return 0 if (pos in visited) return 0 visited.add(pos) return 1 + explore(grid, pos.above(), visited) + explore(grid, pos.below(), visited) + explore(grid, pos.left(), visited) + explore(grid, pos.right(), visited) } val visited = mutableSetOf<Position>() var minSize = Int.MAX_VALUE var maxSize = 0 gridPositions(dimensions).forEach { pos -> explore(this, pos, visited).let { size -> if (size in 1 until minSize) minSize = size if (size > maxSize) maxSize = size } } return p(minSize, maxSize) } fun <T> Grid<T>.hasPath(source: Position, destination: Position, traversable: Predicate<T>): Boolean { bfsIterator(source, traversable).let { while (it.hasNext()) if (it.next().first == destination) return true return false } } fun <T> Grid<T>.shortestPath(a: Position, b: Position, traversable: Predicate<T>): Pair<Int, List<Position>> { val visited = mutableSetOf(a) val queue = ArrayDeque<Triple<Position, Int, MutableList<Position>>>() queue.addLast(Triple(a, 0, mutableListOf(a))) val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second while (queue.size > 0) { val (node, distance, path) = queue.shift() if (b == node) return p(distance, path) node.directions().forEach { neighbor -> if (neighbor.within(0, 0, yMax, xMax) && neighbor !in visited && traversable.test(this[neighbor]!!) ) { visited.add(neighbor) val newPath = path.toMutableList() + neighbor val t = Triple(neighbor, distance + 1, newPath) queue.addLast(t) } } } return p(-1, listOf()) } fun <T> Grid<T>.breadthFirst( source: Position, traversable: Predicate<T>, visitor: (position: Position, value: T) -> Boolean ) { val queue = ArrayDeque<Position>() queue.add(source) val visited = mutableSetOf<Position>() val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second while (!queue.isEmpty()) { val current = queue.shift() if (current !in visited) { visited.add(current) //this.print(visited) if (visitor(current, this[current]!!)) { return } current.directions().forEach { neighbor -> if (neighbor.within(0, 0, yMax, xMax) && neighbor !in visited && traversable.test(this[neighbor]!!) ) { queue.add(neighbor) } } } } } fun <T> Grid<T>.bfsIterator(source: Position, traversable: Predicate<T>): Iterator<Pair<Position, T>> { val queue = ArrayDeque<Position>() queue.add(source) val visited = mutableSetOf<Position>() val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second val graph = this return object : Iterator<Pair<Position, T>> { override fun hasNext(): Boolean { if (queue.isEmpty()) return false while (queue.isNotEmpty() && queue.first() in visited) { queue.shift() } return queue.isNotEmpty() } override fun next(): Pair<Position, T> { val current = queue.shift() visited.add(current) current.directions().forEach { neighbor -> if (neighbor.within(0, 0, yMax, xMax) && neighbor !in visited && traversable.test(graph[neighbor]!!) ) { queue.add(neighbor) } } return p(current, graph[current]!!) } } } fun <T> Grid<T>.print(visited: Set<Position> = setOf(), path: List<Position> = listOf()) { val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second for (i in 0..yMax) { for (j in 0..xMax) { if (p(i, j) in path) { print("${CYAN}${this[p(i,j)]}\u001B[0m") } else if (p(i, j) in visited) { print("\u001B[35m${this[p(i,j)]}\u001B[0m") } else { print(this[p(i, j)]) } } println() } println() } fun <T> Grid<T>.string(visited: Set<Position> = setOf()): String { val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second val buffer = StringBuffer() for (i in 0..yMax) { for (j in 0..xMax) { if (p(i, j) in visited) { buffer.append("\u001B[35mx\u001B[0m") } else { buffer.append(this[p(i, j)]) } } buffer.append("\n") } return buffer.toString() } data class Path( val grid: Grid<*>, val position: Position, val distance: Int, val path: List<Position>, val destination: Position, val type: DistanceType = DistanceType.MANHATTAN ) : Comparable<Path> { override fun compareTo(other: Path): Int { return (distance + type.distance(grid, position, destination)) .compareTo(other.distance + type.distance(grid, other.position, destination)) } } enum class DistanceType { MANHATTAN { override fun distance(grid: Grid<*>, a: Position, b: Position): Double { return a.manhattan(b).toDouble() } }, EUCLIDEAN { override fun distance(grid: Grid<*>, a: Position, b: Position): Double { return kotlin.math.sqrt( (a.first - b.first).toDouble().pow(2.0) + (a.second - b.second).toDouble().pow(2.0) ) } }, LOWEST_VALUE_NEIGHBOR { override fun distance(grid: Grid<*>, a: Position, b: Position): Double { @Suppress("UNCHECKED_CAST") val g = grid as Grid<Int> return g[b]!!.toDouble() } }; abstract fun distance(grid: Grid<*>, a: Position, b: Position): Double } fun <T> Grid<T>.aStar( a: Position, b: Position, type: DistanceType = DistanceType.MANHATTAN, traversable: Predicate<T> ): Pair<Int, List<Position>> { val visited = mutableSetOf(a) val queue = PriorityQueue<Path>() queue.add(Path(this, a, 0, listOf(a), b)) val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second while (queue.size > 0) { this.print(visited) val (_, node, distance, path, _) = queue.poll() if (b == node) return p(distance, path) node.directions().forEach { neighbor -> if (neighbor.within(0, 0, yMax, xMax) && neighbor !in visited && traversable.test(this[neighbor]!!) ) { visited.add(neighbor) val newPath = path.toMutableList() + neighbor queue.add(Path(this, neighbor, distance + 1, newPath, b, type)) } } } return p(-1, listOf()) } fun <T> Grid<T>.dimensions() = p(keys.maxByOrNull { it.first }!!.first, keys.maxByOrNull { it.second }!!.second) fun <T> Grid<T>.allPositions(dimensions: Pair<Int, Int> = dimensions()) = gridPositions(keys.maxByOrNull { it.first }!!.first + 1, keys.maxByOrNull { it.second }!!.second + 1) fun Grid<Int>.shortestPath( start: Position, end: Position, type: DistanceType = DistanceType.EUCLIDEAN, traversable: (original: Pair<Position, Int>, neighbor: Pair<Position, Int>) -> Boolean = { _,_ -> true } ): Pair<Int, List<Position>> { val visited = mutableSetOf(start) val queue = PriorityQueue<Path>() queue.add(Path(this, start, 0, listOf(start), end)) val yMax = keys.maxByOrNull { it.first }!!.first val xMax = keys.maxByOrNull { it.second }!!.second while (queue.size > 0) { val (_, node, value, path, _) = queue.poll() if (end == node) { // this.print(visited, path) return p(value, path) } listOf(node + p(-1,0), node + p(1,0), node + p(0, -1), node + p(0,1)).forEach { neighbor -> if (neighbor.within(0, 0, yMax, xMax) && neighbor !in visited && traversable.invoke(p(node, this[node]!!), p(neighbor, this[neighbor]!!)) ) { visited.add(neighbor) val newPath = path.toMutableList() + neighbor queue.add(Path(this, neighbor, this[neighbor]!! + value, newPath, end, type)) } } } return p(-1, listOf()) }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
16,196
advent-of-code
Creative Commons Zero v1.0 Universal
test-case-factory/src/main/java/com/barteklipinski/testcasefactory/CombinationsBuilder.kt
blipinsk
439,698,827
false
{"Kotlin": 159143}
package com.barteklipinski.testcasefactory interface CombinationsBuilder<X, I : Combination> { val acceptedValues: List<X> val combinations: List<I> } // "Next" builder holds previous combinations. internal interface NextCombinationsBuilder<T : Combination> { val previousCombinations: List<T> } private fun <X, I : Combination, R : Combination> CombinationsBuilder<X, I>.combineWith( previousCombinations: List<R>, combinationBuilder: (R, X) -> I, ): List<I> = previousCombinations.flatMap { previousCombination -> acceptedValues.map { newValue -> combinationBuilder(previousCombination, newValue) } } data class CombinationsBuilder1<A>( override val acceptedValues: List<A>, override val combinations: List<Combination1<A>> = acceptedValues.map { Combination1(it) }, ) : CombinationsBuilder<A, Combination1<A>> class CombinationsBuilder2<A, B>( override val acceptedValues: List<B>, override val previousCombinations: List<Combination1<A>>, ) : CombinationsBuilder<B, Combination2<A, B>>, NextCombinationsBuilder<Combination1<A>> { override val combinations: List<Combination2<A, B>> = combineWith(previousCombinations) { (a), b -> Combination2(a, b) } } class CombinationsBuilder3<A, B, C>( override val acceptedValues: List<C>, override val previousCombinations: List<Combination2<A, B>>, ) : CombinationsBuilder<C, Combination3<A, B, C>>, NextCombinationsBuilder<Combination2<A, B>> { override val combinations: List<Combination3<A, B, C>> = combineWith(previousCombinations) { (a, b), c -> Combination3(a, b, c) } } class CombinationsBuilder4<A, B, C, D>( override val acceptedValues: List<D>, override val previousCombinations: List<Combination3<A, B, C>> ) : CombinationsBuilder<D, Combination4<A, B, C, D>>, NextCombinationsBuilder<Combination3<A, B, C>> { override val combinations: List<Combination4<A, B, C, D>> = combineWith(previousCombinations) { (a, b, c), d -> Combination4(a, b, c, d) } } class CombinationsBuilder5<A, B, C, D, E>( override val acceptedValues: List<E>, override val previousCombinations: List<Combination4<A, B, C, D>> ) : CombinationsBuilder<E, Combination5<A, B, C, D, E>>, NextCombinationsBuilder<Combination4<A, B, C, D>> { override val combinations: List<Combination5<A, B, C, D, E>> = combineWith(previousCombinations) { (a, b, c, d), e -> Combination5(a, b, c, d, e) } } class CombinationsBuilder6<A, B, C, D, E, F>( override val acceptedValues: List<F>, override val previousCombinations: List<Combination5<A, B, C, D, E>> ) : CombinationsBuilder<F, Combination6<A, B, C, D, E, F>>, NextCombinationsBuilder<Combination5<A, B, C, D, E>> { override val combinations: List<Combination6<A, B, C, D, E, F>> = combineWith(previousCombinations) { (a, b, c, d, e), f -> Combination6(a, b, c, d, e, f) } } class CombinationsBuilder7<A, B, C, D, E, F, G>( override val acceptedValues: List<G>, override val previousCombinations: List<Combination6<A, B, C, D, E, F>> ) : CombinationsBuilder<G, Combination7<A, B, C, D, E, F, G>>, NextCombinationsBuilder<Combination6<A, B, C, D, E, F>> { override val combinations: List<Combination7<A, B, C, D, E, F, G>> = combineWith(previousCombinations) { (a, b, c, d, e, f), g -> Combination7(a, b, c, d, e, f, g) } } class CombinationsBuilder8<A, B, C, D, E, F, G, H>( override val acceptedValues: List<H>, override val previousCombinations: List<Combination7<A, B, C, D, E, F, G>> ) : CombinationsBuilder<H, Combination8<A, B, C, D, E, F, G, H>>, NextCombinationsBuilder<Combination7<A, B, C, D, E, F, G>> { override val combinations: List<Combination8<A, B, C, D, E, F, G, H>> = combineWith(previousCombinations) { (a, b, c, d, e, f, g), h -> Combination8(a, b, c, d, e, f, g, h) } } class CombinationsBuilder9<A, B, C, D, E, F, G, H, I>( override val acceptedValues: List<I>, override val previousCombinations: List<Combination8<A, B, C, D, E, F, G, H>> ) : CombinationsBuilder<I, Combination9<A, B, C, D, E, F, G, H, I>>, NextCombinationsBuilder<Combination8<A, B, C, D, E, F, G, H>> { override val combinations: List<Combination9<A, B, C, D, E, F, G, H, I>> = combineWith(previousCombinations) { (a, b, c, d, e, f, g, h), i -> Combination9(a, b, c, d, e, f, g, h, i) } } class CombinationsBuilderN( override val acceptedValues: List<Any>, override val previousCombinations: List<CombinationN>, ) : CombinationsBuilder<Any, CombinationN>, NextCombinationsBuilder<CombinationN> { override val combinations: List<CombinationN> = previousCombinations.flatMap { acceptedValues.map { itNext -> CombinationN(it.values + itNext) } } }
0
Kotlin
0
2
9820d6ed81cfa9cd595a45cd0c600afe89d2d6e1
4,875
test-case-factory
Apache License 2.0
src/main/kotlin/nl/hannahsten/utensils/math/matrix/MatrixFunctions.kt
Hannah-Sten
115,186,492
false
{"Kotlin": 239636, "Java": 25985}
package nl.hannahsten.utensils.math.matrix import kotlin.math.sqrt /** * Returns a new matrix where each element is mapped to another element. * The transformation function also contains the row and column index of the elements. * * The resulting matrix carries over the major of the original matrix. * * @param transform * **`element`**: * The element that is being mapped. * **`vectorIndex`:** * The index of the vector the element is in. * When in [Major.ROW] major, this is the row index. * When in [Major.COLUMN] major, this is the column index. * **`elementIndex`**: * The index of the element within the vector. * When in [Major.ROW] major, this is the column index. * When in [Major.COLUMN] major, this is the row index. */ inline fun <T> Matrix<T>.mapElementsIndexed(transform: (element: T, vectorIndex: Int, elementIndex: Int) -> T): Matrix<T> { // Empty matrix. if (size == 0) { return this } // There is at least 1 vector. val vectorSize = getVector(0).size // Iterate over all vectors. val resultVectors = ArrayList<Vector<T>>(vectors()) for ((vectorIndex, vector) in this.withIndex()) { val elements = ArrayList<T>(vectorSize) for (elementIndex in 0 until vector.size) { elements += transform(vector[elementIndex], vectorIndex, elementIndex) } resultVectors += elements.toVector(operations) } return resultVectors.toMatrix(operations) } /** * Returns a new matrix where each elements is mapped to another element. * * The resulting matrix carries over the major of the original matrix. */ inline fun <T> Matrix<T>.mapElements(transform: (element: T) -> T) = mapElementsIndexed { element, _, _ -> transform(element) } /** * Returns a new matrix where each vector is mapped to another vector. * * The resulting matrix carries over the major of the original matrix. */ inline fun <T> Matrix<T>.mapVectors(transform: (vector: Vector<T>) -> Vector<T>) = map { transform(it) }.toMatrix(operations) /** * Returns a new matrix where each vector is mapped to another vector. * The transformation also contains the vector index. * When in [Major.ROW] major, this is the row index, and when in [Major.COLUMN] major, this is the column index. * * The resulting matrix carries over the major of the original matrix. */ inline fun <T> Matrix<T>.mapVectorsIndexed(transform: (vectorIndex: Int, vector: Vector<T>) -> Vector<T>) = mapIndexed { index, vector -> transform(index, vector) }.toMatrix(operations) /** * Returns a new vector where each element is mapped to another element. */ inline fun <T> Vector<T>.mapElements(transform: (element: T) -> T): Vector<T> = map { transform(it) }.toVector(operations) /** * Returns a new vector where each element is mapped to another element. * The transformation also contains the element index. */ inline fun <T> Vector<T>.mapElementsIndexed(transform: (index: Int, element: T) -> T): Vector<T> = mapIndexed { index, element -> transform(index, element) }.toVector(operations) /** * Calculates the euclidean between two vectors. * * @throws IllegalArgumentException * */ fun <T> Vector<T>.distanceTo(other: Vector<T>): Double { checkDimensions(size, other.size) { "Vectors must have the same size" } var squaredSum = 0.0 for (i in 0 until size) { val difference = operations.subtract(this[i], other[i]) val square = operations.multiply(difference, difference) squaredSum += operations.toDouble(square) } return sqrt(squaredSum) }
0
Kotlin
0
4
f8aab17e5107272c0e7b6fa3ddc67df4281b6cf6
3,649
Utensils
MIT License
src/Day09.kt
acunap
573,116,784
false
{"Kotlin": 23918}
import kotlin.math.abs import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { fun part1(input: List<String>) : Int { var head = Pair(0,0) var tail = Pair(0, 0) val tailHistory = mutableSetOf(tail) fun moveTail() { if (abs(head.first - tail.first) > 1 || abs(head.second - tail.second) > 1) { val first = (head.first - tail.first).let { when { it > 0 -> 1 it < 0 -> -1 else -> 0 } } val second = (head.second - tail.second).let { when { it > 0 -> 1 it < 0 -> -1 else -> 0 } } tail = tail.first + first to tail.second + second tailHistory.add(tail) } } input.map { it.split(" ") } .map { it[0] to it[1].toInt() } .forEach { when (it.first) { "R" -> { for (i in 0 until it.second) { head = head.first to head.second + 1 moveTail() } } "U" -> { for (i in 0 until it.second) { head = head.first + 1 to head.second moveTail() } } "L" -> { for (i in 0 until it.second) { head = head.first to head.second - 1 moveTail() } } "D" -> { for (i in 0 until it.second) { head = head.first - 1 to head.second moveTail() } } } } return tailHistory.size } fun part2(input: List<String>) : Int { var knots = (0..9).map { 0 to 0 }.toMutableList() val tailHistory = mutableSetOf(knots.last()) fun moveTail() { for (i in 1 until knots.size) { val current = knots[i] val previous = knots[i - 1] if (abs(previous.first - current.first) > 1 || abs(previous.second - current.second) > 1) { val first = (previous.first - current.first).let { when { it > 0 -> 1 it < 0 -> -1 else -> 0 } } val second = (previous.second - current.second).let { when { it > 0 -> 1 it < 0 -> -1 else -> 0 } } knots = knots.filterIndexed { index, _ -> index != i }.toMutableList() knots.add(i, current.first + first to current.second + second) if (i == knots.lastIndex) { tailHistory.add(current.first + first to current.second + second) } } } } input.map { it.split(" ") } .map { it[0] to it[1].toInt() } .forEach { when (it.first) { "R" -> { for (i in 0 until it.second) { val head = knots.first() knots = knots.drop(1).toMutableList() knots.add(0, head.first to head.second + 1) moveTail() } } "U" -> { for (i in 0 until it.second) { val head = knots.first() knots = knots.drop(1).toMutableList() knots.add(0, head.first + 1 to head.second) moveTail() } } "L" -> { for (i in 0 until it.second) { val head = knots.first() knots = knots.drop(1).toMutableList() knots.add(0, head.first to head.second - 1) moveTail() } } "D" -> { for (i in 0 until it.second) { val head = knots.first() knots = knots.drop(1).toMutableList() knots.add(0, head.first - 1 to head.second) moveTail() } } } } return tailHistory.size } val time = measureTime { val input = readLines("Day09") println(part1(input)) println(part2(input)) } println("Real data time $time") val timeTest = measureTime { check(part1(readLines("Day09_test")) == 13) check(part2(readLines("Day09_2_test")) == 36) } println("Test data time $timeTest.") }
0
Kotlin
0
0
f06f9b409885dd0df78f16dcc1e9a3e90151abe1
5,515
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/github/lawseff/aoc2023/substring/NumberBuilder.kt
lawseff
573,226,851
false
{"Kotlin": 37196}
package io.github.lawseff.aoc2023.substring /** * Class for building numbers from digits, that are contained in a string input */ class NumberBuilder { companion object { private val DIGITS_BY_WORDS = mapOf( "zero" to 0, "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) // Matches any digit from [0-9] and digits spelled out with letters. private const val DIGIT = "\\d|zero|one|two|three|four|five|six|seven|eight|nine" // Matches a substring starting with a digit and ending with a digit. // Captures only the first digit (group 1) and the last digit (group 2, if present). private val MATCHER = "($DIGIT)(?:.*($DIGIT))?".toRegex() } /** * Returns a number, consisting of the first digit and the last digit of a [String] value. If * the value contains only one digit, it is considered both as the first and the last. * * @param input string value to build a number from * @return two-digit number from the first and the last digit occurrence */ fun buildFromFirstLastDigit(input: String): Int { val firstDigit = input.first { it.isDigit() } val lastDigit = input.last { it.isDigit() } return "$firstDigit$lastDigit".toInt() } /** * *Alpha-digit* is a digit, written either numerically (0-9) or with lowercase letters * ("zero", "one", etc.). * * Returns a number, consisting of the first *alpha-digit* and the *last alpha-digit* of a * [String] value. The result contains only numerical digits. If the value contains only one * *alpha-digit*, it is considered both as the first and the last. * * @param input string value to build a number from * @return two-digit number from the first and the last alpha-digit occurrence */ fun buildFromFirstLastAlphaDigit(input: String): Int { val matchResult = MATCHER.find(input) ?: throw NoSuchElementException() // captured groups start with 1; 0 is the entire match val firstDigit = parseAlphaDigit(matchResult.groupValues[1]) val lastDigit = if (matchResult.groupValues[2].isNotEmpty()) { parseAlphaDigit(matchResult.groupValues[2]) } else { firstDigit } return "$firstDigit$lastDigit".toInt() } private fun parseAlphaDigit(alphaDigit: String): Int { return if (alphaDigit.length == 1) { alphaDigit.toInt() } else { DIGITS_BY_WORDS[alphaDigit] ?: throw IllegalArgumentException() } } }
0
Kotlin
0
0
b60ab611aec7bb332b8aa918aa7c23a43a3e61c8
2,760
advent-of-code-2023
MIT License
src/Day06.kt
ThijsBoehme
572,628,902
false
{"Kotlin": 16547}
fun main() { fun findMarker(input: String, markerSize: Int): Int { val marker = input.windowed(markerSize) .first { chunk -> chunk.toSet().size == markerSize } return input.indexOf(marker) + markerSize } fun part1(input: String): Int { return findMarker(input, 4) } fun part2(input: String): Int { return findMarker(input, 14) } // test if implementation meets criteria from the description, like: check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
707e96ec77972145fd050f5c6de352cb92c55937
1,168
Advent-of-Code-2022
Apache License 2.0
src/main/java/dev/haenara/mailprogramming/solution/y2019/m12/d08/Solution191208.kt
HaenaraShin
226,032,186
false
null
import dev.haenara.mailprogramming.solution.Solution /** * 매일프로그래밍 2019. 12. 08 * 피보나치 배열은 0과 1로 시작하며, 다음 피보나치 수는 바로 앞의 두 피보나치 수의 합이 된다. * 정수 N이 주어지면, N보다 작은 모든 짝수 피보나치 수의 합을 구하여라. * Fibonacci sequence starts with 0 and 1 where each fibonacci number is a sum of two previous fibonacci numbers. * Given an integer N, find the sum of all even fibonacci numbers. * * Input: N = 12 * Output: 10 // 0, 1, 2, 3, 5, 8 중 짝수인 2 + 8 = 10. * * 풀이 : * 재귀로 풀수도 있으나, 성능을 고려하여 반복문을 이용하여 풀었다. * 피보나치 수열의 합이 주어진 수보다 작은지 확인하여 짝수면 누적한다. */ class Solution191208: Solution<Long, Long> { override fun solution(max: Long) : Long { var evenSum = 0L var `F(n-2)` = 0L var `F(n-1)` = 1L var `F(n)` = `F(n-1)` + `F(n-2)` while (`F(n)` < max ) { if (`F(n)` % 2L == 0L) { evenSum += `F(n)` } `F(n-2)` = `F(n-1)` `F(n-1)` = `F(n)` `F(n)` = `F(n-1)` + `F(n-2)` } return evenSum } }
0
Kotlin
0
7
b5e50907b8a7af5db2055a99461bff9cc0268293
1,273
MailProgramming
MIT License
src/main/kotlin/me/peckb/aoc/_2022/calendar/day18/Day18.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2022.calendar.day18 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import me.peckb.aoc.pathing.GenericIntDijkstra class Day18 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::cubeLocation) { input -> val cubes = hashSetOf<CubeLocation>() input.forEach { cube -> cubes.add(cube) } cubes.sumOf { cube -> cube.neighborCubes().count { !cubes.contains(it) } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::cubeLocation) { input -> val cubes = hashSetOf<CubeLocation>() var min = Int.MAX_VALUE var max = Int.MIN_VALUE input.forEach { cube -> cubes.add(cube) min = minOf(min, cube.x, cube.y, cube.z) max = maxOf(max, cube.x, cube.y, cube.z) } // add buffer min-- max++ val pocketCubes = mutableSetOf<CubeLocation>() val outerAir = mutableSetOf<CubeLocation>() val solver = CubeDijkstra() cubes.forEach { cube -> cube.neighborCubes() .map { it.withCubes(cubes).withBounds(min, max) } .filter { !cubes.contains(it) } .filter { !outerAir.contains(it) } .filter { !pocketCubes.contains(it) } .forEach { unseenAirCube -> val airNeighbors = solver.solve(unseenAirCube).keys val outsideAir = airNeighbors.any { it.touchesTheEdge() } if (outsideAir) { outerAir.addAll(airNeighbors) } else { pocketCubes.addAll(airNeighbors) } } } outerAir.sumOf { airCube -> airCube.neighborCubes().count { cubes.contains(it) } } } private fun cubeLocation(line: String) : CubeLocation { return line.split(",").map { it.toInt() }.let { (x, y, z) -> CubeLocation(x, y, z) } } data class CubeLocation(val x: Int, val y: Int, val z: Int) : GenericIntDijkstra.DijkstraNode<CubeLocation> { private var min: Int = Int.MAX_VALUE private var max: Int = Int.MIN_VALUE private lateinit var cubes: HashSet<CubeLocation> fun withCubes(cubes: HashSet<CubeLocation>) = apply { this.cubes = cubes } fun withBounds(min: Int, max: Int) = apply { this.min = min this.max = max } override fun neighbors(): Map<CubeLocation, Int> { return neighborCubes() .map { it.withCubes(cubes).withBounds(min, max) } .filter { it.x in (min..max) && it.y in (min..max) && it.z in (min..max) } .filter { !cubes.contains(it) }.associateWith { 1 } } fun neighborCubes(): List<CubeLocation> { val front = CubeLocation(x, y, z + 1) val back = CubeLocation(x, y, z - 1) val up = CubeLocation(x, y + 1, z) val down = CubeLocation(x, y - 1, z) val right = CubeLocation(x + 1, y, z) val left = CubeLocation(x - 1, y, z) return listOf(front, back, up, down, right, left) } fun touchesTheEdge(): Boolean { return x == min || y == min || z == min || x == max || y == max || z == max } } class CubeDijkstra : GenericIntDijkstra<CubeLocation>() }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
3,178
advent-of-code
MIT License
src/main/App.kt
neelkamath
187,355,278
false
null
package com.neelkamath.seeds private fun prompt(message: String) = print(message).run { readLine()!! } private fun promptSize(type: String): Int { val input = prompt("Enter the number of $type (\"r\" for random): ") if (input == "r") return 100 val num = input.toIntOrNull() ?: promptSize(type) return if (num > 0) num else promptSize(type) } private enum class SeedType { SUPPLIED, RANDOM } private tailrec fun promptSeedType(): SeedType = when (prompt("Enter \"s\" to supply a seed (\"r\" for random): ")) { "s" -> SeedType.SUPPLIED "r" -> SeedType.RANDOM else -> promptSeedType() } private fun isValidGrid(grid: String, columns: Int) = grid.isNotEmpty() && grid.length % columns == 0 && grid.all { it in listOf('A', 'D') } private tailrec fun promptSeed(columns: Int): String { val grid = prompt( """ Enter the seed using "A" for alive cells, and "D" for dead ones (e.g., "ADDADD" has two rows if you specified the seed should have three columns earlier): """.trimStart().replace(Regex("""\s+"""), " ") ) return if (isValidGrid(grid, columns)) grid else promptSeed(columns) } private fun createGrid(grid: String, columns: Int) = grid.map { if (it == 'A') Cell.ALIVE else Cell.DEAD }.chunked(columns).map { it.toMutableList() } fun main() { Player( when (promptSeedType()) { SeedType.SUPPLIED -> { val columns = promptSize("columns") Seeds(createGrid(promptSeed(columns), columns)) } SeedType.RANDOM -> Seeds(promptSize("rows"), promptSize("columns")) } ) }
0
Kotlin
1
0
c01db90c48be43173084ba5b29d6f3470179ff7d
1,639
seeds
MIT License
src/Day06b.kt
mlidal
572,869,919
false
{"Kotlin": 20582}
fun main() { fun part1(input: String): Int { var chars = mutableListOf<Char>() input.forEachIndexed { index, char -> if (!chars.contains(char)) { chars.add(char) if (chars.size == 4) { return index + 1 } } else { val index = chars.indexOf(char) chars = chars.subList(index + 1, chars.size) chars.add(char) } } return input.length } fun part2(input: String): Int { var chars = mutableListOf<Char>() input.forEachIndexed { index, char -> if (!chars.contains(char)) { chars.add(char) if (chars.size == 14) { return index + 1 } } else { val index = chars.indexOf(char) chars = chars.subList(index + 1, chars.size) chars.add(char) } } return input.length } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput.first()) == 7) check(part2(testInput.first()) == 19) val input = readInput("Day06") println(part1(input.first())) println(part2(input.first())) }
0
Kotlin
0
0
bea7801ed5398dcf86a82b633a011397a154a53d
1,348
AdventOfCode2022
Apache License 2.0
y2015/src/main/kotlin/adventofcode/y2015/Day07.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2015 import adventofcode.io.AdventSolution object Day07 : AdventSolution(2015, 7, "Some Assembly Required") { override fun solvePartOne(input: String) = WireMap(input.lines()).evaluate("a").toString() override fun solvePartTwo(input: String): String { val result = WireMap(input.lines()).evaluate("a").toString() val amendedInput = "$input\n$result -> b" return solvePartOne(amendedInput) } } private class WireMap(instructions: List<String>) { private val wireValueMap: MutableMap<String, Int> = mutableMapOf() private val wireConnectionMap: Map<String, () -> Int> = instructions.associate(this::parseInstruction) private fun parseInstruction(string: String) = string.split(" ").let { cmd -> when (cmd[1]) { "AND" -> cmd[4] to { evaluate(cmd[0]) and evaluate(cmd[2]) } "OR" -> cmd[4] to { evaluate(cmd[0]) or evaluate(cmd[2]) } "LSHIFT" -> cmd[4] to { evaluate(cmd[0]) shl evaluate(cmd[2]) } "RSHIFT" -> cmd[4] to { evaluate(cmd[0]) ushr evaluate(cmd[2]) } "->" -> cmd[2] to { evaluate(cmd[0]) } else -> cmd[3] to { evaluate(cmd[1]).inv() } } } fun evaluate(wire: String): Int = wire.toIntOrNull() ?: wireValueMap.getOrPut(wire) { wireConnectionMap.getValue(wire)() } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,237
advent-of-code
MIT License
src/Day06.kt
hiteshchalise
572,795,242
false
{"Kotlin": 10694}
fun main() { fun part1(input: List<String>): Int { val windowSize = 4 val signal = input[0] val windowsOfFourSignals = signal.windowed(windowSize, 1, false) val indexOfFirst = windowsOfFourSignals.indexOfFirst { val setOfCharacter = it.toCharArray().toSet() setOfCharacter.size == it.length } return indexOfFirst + windowSize } fun part2(input: List<String>): Int { val windowSize = 14 val signal = input[0] val windowsOfFourSignals = signal.windowed(windowSize, 1, false) val indexOfFirst = windowsOfFourSignals.indexOfFirst { val setOfCharacter = it.toCharArray().toSet() setOfCharacter.size == it.length } return indexOfFirst + windowSize } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 10) check(part2(testInput) == 29) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e4d66d8d1f686570355b63fce29c0ecae7a3e915
1,084
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/NextPermutation.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.extensions.swap /** * Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. * If such arrangement is not possible, it must rearrange it as the lowest possible order (sorted in ascending order). * The replacement must be in-place and use only constant extra memory. */ fun IntArray.nextPermutation() { val n = this.size if (n < 2) return var index = n - 1 while (index > 0) { if (this[index - 1] < this[index]) { break } index-- } if (index == 0) { reverseSort(0, n - 1) return } else { val value = this[index - 1] var j = n - 1 while (j > index) { if (this[j] > value) break j-- } swap(j, index - 1) reverseSort(index, n - 1) } } private fun IntArray.reverseSort(start: Int, end: Int) { var i = start var j = end while (i < j) swap(i++, j--) }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,655
kotlab
Apache License 2.0
ahp-base/src/test/kotlin/PMIgenerator.kt
sbigaret
164,424,298
true
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
import org.xmcda.* import org.xmcda.converters.v2_v3.XMCDAConverter import org.xmcda.parsers.xml.xmcda_v3.XMCDAParser import org.xmcda.utils.Coord import org.xmcda.utils.Matrix import java.io.File fun crt(id: String, name: String) = Criterion(id, name) fun alt(id: String, name: String) = Alternative(id).also { it.setName(name) } infix fun <T, V> Pair<T, T>.has(ratio: V) = Triple(first, second, ratio) fun Criterion.matrix( alternatives: List<Alternative>, vararg comparisons: Triple<Alternative, Alternative, Int> ): AlternativesMatrix<Int> { val childrenCount = alternatives.size validateSize(comparisons, childrenCount) return AlternativesMatrix<Int>().also { it.applyMatrixValues(this, comparisons) { id() } } } private fun validateSize(comparisons: Array<out Triple<*, *, Int>>, childrenCount: Int) { require(comparisons.size == (childrenCount * childrenCount - childrenCount) / 2) { "wrong values count" } } fun CriterionHierarchyNode.mat( vararg comparisons: Triple<CriterionHierarchyNode, CriterionHierarchyNode, Int> ): CriteriaMatrix<Int> = matrix(*comparisons.map { it.first.criterion to it.second.criterion has it.third }.toTypedArray()) fun CriterionHierarchyNode.matrix( vararg comparisons: Triple<Criterion, Criterion, Int> ): CriteriaMatrix<Int> { val childrenCount = children.size require(comparisons.size == (childrenCount * childrenCount - childrenCount) / 2) { "wrong values count" } return CriteriaMatrix<Int>().also { it.applyMatrixValues(criterion, comparisons) { id() } } } private fun <T, V : Comparable<V>> Matrix<T, V>.applyMatrixValues(criterion: Criterion, comparisons: Array<out Triple<T, T, V>>, id: T.() -> String) { setName(criterion.name()) setId(criterion.id()) comparisons.sortWith(compareBy({ it.first.id() }, { it.second.id() }, { it.third })) comparisons.toList() .windowed(2) .forEach { (c1, c2) -> require(c1.first != c2.first || c1.second != c2.second) { "same comparison multiple times, [$c1, $c2]" } } comparisons.forEach { require(it.first != it.second) { "cannot repeat values: $it" } } comparisons.forEach { (c1, c2, value) -> set(Coord(c1, c2), QualifiedValues(QualifiedValue(value))) } } fun hierarchyNode(criterion: Criterion, vararg nodes: Criterion) = CriterionHierarchyNode(criterion).also { nodes.forEach { node -> it.addChild(node) } } fun hierarchyNode(criterion: Criterion, vararg nodes: CriterionHierarchyNode) = CriterionHierarchyNode(criterion).also { nodes.forEach { node -> it.addChild(node) } } fun <T> Criterion.matrix(alternatives: List<Alternative>, vararg value: T) where T : Number, T : Comparable<T> { require(value.size == alternatives.size * alternatives.size) { "wrong size" } val alts = alternatives .zip(value.toList().chunked(alternatives.size)) .flatMap { (a1, vals) -> alternatives.zip(vals) .map { (a2, v) -> a1 to a2 has v } } alts.map { } } fun main() { val teamCom = crt("teamCom", "Team Commitment") val orgCom = crt("orgCom", "Organizational Commitment") val pmCom = crt("pmCom", "Project Manager Commitment") val scCom = hierarchyNode( crt("scCom", "Stakeholders Commitment"), teamCom, orgCom, pmCom ) val scComMat = scCom.matrix( teamCom to orgCom has 3, pmCom to teamCom has 5, pmCom to orgCom has 9 ) val roi = crt("roi", "Return on Investment") val profit = crt("profit", "Profit") val npv = crt("npv", "Net Present Value") val fin = hierarchyNode( crt("fin", "Financial"), roi, profit, npv ) val finMat = fin.matrix( profit to roi has 5, npv to profit has 1, npv to roi has 5 ) val iacim = crt("iacim", "Imp. Ability to Compete in International Markets") val iip = crt("iip", "Imp. Internal Process") val ir = crt("ir", "Imp. Reputation") val str = hierarchyNode( crt("str", "Strategic"), iacim, iip, ir ) val strMat = str.matrix( iacim to iip has 7, iacim to ir has 3, ir to iip has 5 ) val lr = crt("lr", "Lower Risk for the Organization") val ur = crt("ur", "Urgency") val itk = crt("itk", "Internal Technical Knowledge") val oc = hierarchyNode( crt("oc", "Other Criteria"), lr, ur, itk ) val ocMat = oc.matrix( lr to ur has 5, itk to lr has 3, itk to ur has 7 ) val goal = hierarchyNode( crt("root", "Goal: ACME Project selection"), scCom, fin, str, oc ) val goalMat = goal.mat( scCom to oc has 1, fin to scCom has 5, fin to str has 1, fin to oc has 5, str to scCom has 9, str to oc has 5 ) val nOffice = alt("no", "New Office") val erp = alt("erp", "ERP impl.") val chOff = alt("chOff", "Chinese Office") val iProd = alt("iProd", "Intern. Product") val itOuts = alt("itOuts", "IT Outsourc.") val locCamp = alt("locCamp", "Local Campaign") val alternatives = listOf(nOffice, erp, chOff, iProd, itOuts, locCamp) val teamComMat = teamCom.matrix( alternatives, nOffice to erp has 5, nOffice to chOff has 3, nOffice to itOuts has 9, nOffice to locCamp has 7, erp to itOuts has 1, chOff to erp has 5, chOff to itOuts has 7, chOff to locCamp has 3, iProd to nOffice has 3, iProd to erp has 7, iProd to chOff has 3, iProd to itOuts has 5, iProd to locCamp has 5, locCamp to erp has 3, locCamp to itOuts has 3 ) val orgComMat = orgCom.matrix( alternatives, nOffice to erp has 3, nOffice to itOuts has 5, nOffice to locCamp has 3, erp to itOuts has 1, chOff to nOffice has 9, chOff to erp has 9, chOff to iProd has 3, chOff to itOuts has 7, chOff to locCamp has 7, iProd to nOffice has 5, iProd to erp has 7, iProd to itOuts has 9, iProd to locCamp has 7, locCamp to erp has 3, locCamp to itOuts has 3 ) val pmComMat = pmCom.matrix( alternatives, nOffice to erp has 7, nOffice to itOuts has 5, nOffice to locCamp has 3, erp to itOuts has 3, chOff to nOffice has 3, chOff to erp has 9, chOff to iProd has 1, chOff to itOuts has 7, chOff to locCamp has 7, iProd to nOffice has 3, iProd to erp has 7, iProd to itOuts has 7, iProd to locCamp has 9, locCamp to erp has 3, locCamp to itOuts has 5 ) val roiMat = roi.matrix( alternatives, erp to nOffice has 3, chOff to nOffice has 7, chOff to erp has 9, chOff to itOuts has 7, chOff to locCamp has 5, iProd to nOffice has 9, iProd to erp has 9, iProd to chOff has 3, iProd to itOuts has 7, iProd to locCamp has 5, itOuts to nOffice has 3, itOuts to erp has 3, locCamp to nOffice has 3, locCamp to erp has 3, locCamp to itOuts has 3 ) val profitMat = profit.matrix( alternatives, nOffice to erp has 1, chOff to nOffice has 7, chOff to erp has 7, chOff to itOuts has 7, chOff to locCamp has 5, iProd to nOffice has 9, iProd to erp has 9, iProd to chOff has 3, iProd to itOuts has 9, iProd to locCamp has 5, itOuts to nOffice has 5, itOuts to erp has 3, locCamp to nOffice has 3, locCamp to erp has 5, locCamp to itOuts has 3 ) val npvMat = npv.matrix( alternatives, erp to nOffice has 3, erp to itOuts has 1, chOff to nOffice has 5, chOff to erp has 5, chOff to itOuts has 5, chOff to locCamp has 3, iProd to nOffice has 7, iProd to erp has 7, iProd to chOff has 3, iProd to itOuts has 5, iProd to locCamp has 7, itOuts to nOffice has 3, locCamp to nOffice has 3, locCamp to erp has 3, locCamp to itOuts has 3 ) val iacimMat = iacim.matrix( alternatives, nOffice to erp has 3, nOffice to itOuts has 5, nOffice to locCamp has 5, erp to locCamp has 3, chOff to nOffice has 9, chOff to erp has 9, chOff to iProd has 1, chOff to itOuts has 9, chOff to locCamp has 9, iProd to nOffice has 7, iProd to erp has 9, iProd to itOuts has 9, iProd to locCamp has 9, itOuts to erp has 3, itOuts to locCamp has 3 ) val iipMat = iip.matrix( alternatives, nOffice to chOff has 3, nOffice to iProd has 5, nOffice to itOuts has 1, nOffice to locCamp has 7, erp to nOffice has 5, erp to chOff has 7, erp to iProd has 7, erp to itOuts has 1, erp to locCamp has 7, chOff to iProd has 1, chOff to locCamp has 1, itOuts to chOff has 7, itOuts to iProd has 7, itOuts to locCamp has 7, locCamp to iProd has 3 ) val irMat = ir.matrix( alternatives, nOffice to itOuts has 3, erp to nOffice has 3, erp to itOuts has 5, chOff to nOffice has 7, chOff to erp has 9, chOff to iProd has 3, chOff to itOuts has 7, chOff to locCamp has 1, iProd to nOffice has 5, iProd to erp has 5, iProd to itOuts has 7, locCamp to nOffice has 7, locCamp to erp has 7, locCamp to iProd has 3, locCamp to itOuts has 9 ) val lrMat = lr.matrix( alternatives, nOffice to erp has 5, nOffice to chOff has 7, nOffice to iProd has 3, nOffice to itOuts has 5, nOffice to locCamp has 1, erp to chOff has 5, erp to iProd has 3, erp to itOuts has 3, iProd to chOff has 3, iProd to itOuts has 5, itOuts to chOff has 3, locCamp to erp has 7, locCamp to chOff has 9, locCamp to iProd has 7, locCamp to itOuts has 9 ) val urMat = ur.matrix( alternatives, nOffice to itOuts has 3, nOffice to locCamp has 1, erp to nOffice has 3, erp to itOuts has 3, erp to locCamp has 3, chOff to nOffice has 5, chOff to erp has 7, chOff to itOuts has 5, chOff to locCamp has 7, iProd to nOffice has 7, iProd to erp has 9, iProd to chOff has 3, iProd to itOuts has 7, iProd to locCamp has 7, locCamp to itOuts has 3 ) val itkMat = itk.matrix( alternatives, nOffice to erp has 9, nOffice to chOff has 9, nOffice to iProd has 9, nOffice to itOuts has 9, nOffice to locCamp has 3, chOff to erp has 3, chOff to iProd has 3, chOff to itOuts has 1, iProd to erp has 3, itOuts to erp has 5, itOuts to iProd has 3, locCamp to erp has 9, locCamp to chOff has 9, locCamp to iProd has 9, locCamp to itOuts has 9 ) val altXmcda = XMCDA().also { it.alternatives.addAll(alternatives) } val hierarchy = XMCDA().also { it.criteriaHierarchiesList.add(CriteriaHierarchy().apply { addRoot(goal) }) } val criteria = XMCDA().also { val criteria = listOf( goal, scCom, fin, str, oc, teamCom, orgCom, pmCom, roi, profit, npv, iacim, iip, ir, lr, ur, itk ).map { if (it is CriterionHierarchyNode) it.criterion else it } as List<Criterion> it.criteria.addAll(criteria) } val criteriaComp = XMCDA().also { it.criteriaMatricesList.addAll(listOf(goalMat, scComMat, finMat, strMat, ocMat)) } val altComp = XMCDA().also { it.alternativesMatricesList.addAll( listOf( teamComMat, orgComMat, pmComMat, roiMat, profitMat, npvMat, iacimMat, iipMat, irMat, lrMat, urMat, itkMat ) ) } val results = mapOf( "alternatives" to altXmcda, "criteria" to criteria, "criteria_comparisons" to criteriaComp, "hierarchy" to hierarchy, "preference" to altComp ) val v2Mapping = mapOf( "alternatives" to "alternatives", "criteria" to "criteria", "criteria_comparisons" to "criteriaComparisons", "hierarchy" to "hierarchy", "preference" to "alternativesComparisons" ) val v3Mapping = mapOf( "alternatives" to "alternatives", "criteria" to "criteria", "criteria_comparisons" to "criteriaMatrix", "hierarchy" to "criteriaHierarchy", "preference" to "alternativesMatrix" ) writeV2("./ahp/tests/in4.v2", results, v2Mapping) writeV3("./ahp/tests/in4.v3", results, v3Mapping) } private fun writeV2(outFile: String, v3Results: Map<String, XMCDA>, tags: Map<String, String>) { val parent = File(outFile).also { it.deleteRecursively() it.mkdirs() } for (outputName in v3Results.keys) { val outputFile = File(parent, "$outputName.xml") val v2Results = requireNotNull(XMCDAConverter.convertTo_v2(v3Results[outputName])) { "Conversion from v3 to v2 returned a null value" } org.xmcda.parsers.xml.xmcda_v2.XMCDAParser.writeXMCDA(v2Results, outputFile, tags[outputName]) } } private fun writeV3(outFile: String, x_results: Map<String, XMCDA>, tags: Map<String, String>) { val parser = XMCDAParser() val parent = File(outFile).also { it.deleteRecursively() it.mkdirs() } x_results.keys.forEach { key -> val outputFile = File(parent, "$key.xml") parser.writeXMCDA(x_results[key], outputFile, tags[key]) } }
0
Kotlin
0
0
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
15,519
DecisionDeck
MIT License
src/main/java/ReplaceCharactersWithBiggerAscii.kt
ShabanKamell
342,007,920
false
null
/* Given a string str consisting of lowercase letters only and an integer k, the task is to replace every character of the given string by character whose ASCII value is k times more than it. If ASCII value exceeds ‘z’, then start checking from ‘a’ in a cyclic manner. Examples: Input: str = “abc”, k = 2 Output: cde a is moved by 2 times which results in character c b is moved by 2 times which results in character d c is moved by 2 times which results in character e Input: str = “abc”, k = 28 Output: cde a is moved 25 times, z is reached. Then 26th character will be a, 27-th b and 28-th c. b is moved 24 times, z is reached. 28-th is d. b is moved 23 times, z is reached. 28-th is e. */ object ReplaceCharactersWithBiggerAscii { private fun replace(input: String, _k: Int) { var k = _k var result = "" for (element in input) { val ascii = element.toInt() val duplicate = k if (ascii + k > 122) { k -= 122 - ascii k %= 26 result += (96 + k).toChar() } else { result += (ascii + k).toChar() } k = duplicate } println(result) } @JvmStatic fun main(args: Array<String>) { replace("abc", 2) // cde replace("abc", 28) // cde replace("def", 3) // ghi } } /* Time Complexity: O(N), where N is the length of the string. What is the disadvantage of using the ASCII value of the letters to solve this problem? It's easier to use ASCII for two reasons: 1 - We need to check if the next character exceeds 'z' or not. In this case, we'll check using (ascii + k > 122). 2 - We can get the the next char with simple operations: (96 + k).toChar(), (ascii + k).toChar(). */
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
1,813
CodingChallenges
Apache License 2.0
src/aoc2022/day01/Day01.kt
svilen-ivanov
572,637,864
false
{"Kotlin": 53827}
@file:Suppress("UnstableApiUsage") package aoc2022.day01 import com.google.common.collect.MinMaxPriorityQueue import readInput import java.util.* import kotlin.Comparator fun main() { fun part1(input: List<String>): Int { var max = Int.MIN_VALUE var elf = 1 var i = 1 var sum = 0 for (line in input) { if (line != "") { sum += line.toInt() } else { if (sum > max) { elf = i max = sum } else if (sum == max) { error("sum == max") } sum = 0 i++ } } println("elf $elf, max $max") check(max == 68923) return elf } fun part2(input: List<String>): Int { data class ElfCalories(val elf: Int, val cal: Int) val topElves: Queue<ElfCalories> = MinMaxPriorityQueue .orderedBy(Comparator<ElfCalories> { o1, o2 -> o1.cal.compareTo(o2.cal) }.reversed()) .maximumSize(3) .create() var i = 1 var sum = 0 for (line in input) { if (line != "") { sum += line.toInt() } else { val elfCalories = ElfCalories(i, sum) topElves.add(elfCalories) sum = 0 i++ } } val sumTop3 = topElves.sumOf(ElfCalories::cal) println("sumTop3 $sumTop3") println("sumTop1 ${topElves.peek()}") check(sumTop3 == 200044) return sumTop3 } // test if implementation meets criteria from the description, like: val testInput = readInput("day01/day01") part1(testInput) part2(testInput) }
0
Kotlin
0
0
456bedb4d1082890d78490d3b730b2bb45913fe9
1,784
aoc-2022
Apache License 2.0
src/problems/61-RotateRight.kt
w1374720640
352,006,409
false
null
package problems import base.ListNode import base.createListNode import base.toIntArray /** * 61. 旋转链表 https://leetcode-cn.com/problems/rotate-list/ * 给你一个链表的头节点head,旋转链表,将链表每个节点向右移动k个位置。 * * 解:旋转链表操作等价于将链表最后k个元素删除,并拼接到链表头部, * 对于长度小于k的链表,k等于k除以size的余数 * 从头节点开始遍历,记录节点总数、倒数第k+1个节点和最后一个节点, * 到链表结尾时,若节点总数大于k,使用临时变量记录倒数k+1个节点的下一个节点,作为返回值, * 将k+1个节点的next指针置空,最后一个节点的next指针指向head,返回保存的临时节点, * 若节点总数等于k,则直接返回head节点, * 若节点总数小于k,对k重新赋值为k除以size的余数,从头重新遍历 */ fun rotateRight(head: ListNode?, k: Int): ListNode? { if (k == 0 || head == null) return head var i = k var size = 1 var lastK1: ListNode = head var last: ListNode = head while (true) { val next = last.next if (next == null) { when { size == i -> return head size > i -> { val temp = lastK1.next!! lastK1.next = null last.next = head return temp } else -> { i = i % size // 这里一开始没有考虑到,可以直接返回 if (i == 0) return head size = 1 lastK1 = head last = head } } } else { size++ last = next if (size - i > 1) { lastK1 = lastK1.next!! } } } } private fun checkRotateRight(input: IntArray, k: Int, expect: IntArray) { check(rotateRight(input.createListNode(), k).toIntArray().contentEquals(expect)) } fun main() { checkRotateRight(intArrayOf(1, 2, 3, 4, 5), 2, intArrayOf(4, 5, 1, 2, 3)) checkRotateRight(intArrayOf(0, 1, 2), 1, intArrayOf(2, 0, 1)) checkRotateRight(intArrayOf(0, 1, 2), 2, intArrayOf(1, 2, 0)) checkRotateRight(intArrayOf(0, 1, 2), 3, intArrayOf(0, 1, 2)) checkRotateRight(intArrayOf(0, 1, 2), 4, intArrayOf(2, 0, 1)) checkRotateRight(intArrayOf(1), 2, intArrayOf(1)) println("check succeed.") }
0
Kotlin
0
0
21c96a75d13030009943474e2495f1fc5a7716ad
2,517
LeetCode
MIT License
aoc21/day_03/main.kt
viktormalik
436,281,279
false
{"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796}
import java.io.File fun List<String>.mcb(i: Int) = if (this.filter { it[i] == '1' }.count() >= this.size / 2) '1' else '0' fun main() { val nums = File("input").readLines() val gamma = nums[0].withIndex().map { (i, _) -> nums.mcb(i) }.joinToString("") val epsilon = gamma.map { if (it == '1') '0' else '1' }.joinToString("") val first = gamma.toInt(radix = 2) * epsilon.toInt(radix = 2) println("First: $first") val o2 = (0..nums[0].length - 1).fold(nums) { n, i -> n.filter { it[i] == n.mcb(i) } }[0] val co2 = (0..nums[0].length - 1).fold(nums) { n, i -> n.filter { n.size == 1 || it[i] != n.mcb(i) } }[0] val second = o2.toInt(radix = 2) * co2.toInt(radix = 2) println("Second: $second") }
0
Rust
1
0
f47ef85393d395710ce113708117fd33082bab30
763
advent-of-code
MIT License
src/Day13.kt
vitind
578,020,578
false
{"Kotlin": 60987}
fun main() { fun removeOuterSquareBrackets(line: String) : String { val sb = StringBuilder(line) val openSquareBracketIndex = sb.indexOfFirst { it.equals('[') } sb.replace(openSquareBracketIndex, openSquareBracketIndex + 1, "") val closeSquareBracketIndex = sb.indexOfLast { it.equals(']') } sb.replace(closeSquareBracketIndex, closeSquareBracketIndex + 1, "") return sb.toString() } fun itemizeList(line: String) : ArrayList<String> { val itemList = arrayListOf<String>() // This will skip square brackets in chunks var squareBracketCount = 0 // Increments when it sees '[' and decrements when it sees ']' val valueString = StringBuilder() val strippedLine = removeOuterSquareBrackets(line) strippedLine.forEach { ch -> if (ch.equals(',')) { if (squareBracketCount == 0) { itemList.add(valueString.toString()) valueString.clear() } else { valueString.append(ch) } } else if (ch.equals('[')) { squareBracketCount += 1 valueString.append(ch) } else if (ch.equals(']')) { squareBracketCount -= 1 valueString.append(ch) } else { valueString.append(ch) } } itemList.add(valueString.toString()) return itemList } fun comparePackets(leftItems: ArrayList<String>, rightItems: ArrayList<String>) : Boolean? { // println("Comparing ${leftItems} Size: ${leftItems.size} to ${rightItems} Size: ${rightItems.size}") while (leftItems.isNotEmpty() || rightItems.isNotEmpty()) { val leftItem = if (leftItems.isNotEmpty()) leftItems.removeFirst() else "" val rightItem = if (rightItems.isNotEmpty()) rightItems.removeFirst() else "" if (leftItem == "") { // println("Left side smaller -> true") return true } if (rightItem == "") { // println("Right side smaller -> false") return false } if (leftItem.isNotEmpty() && leftItem[0] == '[' && rightItem.isNotEmpty() && rightItem[0] == '[') { val isStillValid = comparePackets(itemizeList(leftItem), itemizeList(rightItem)) isStillValid?.let { return it } } else if (leftItem.isNotEmpty() && leftItem[0] == '[') { val isStillValid = comparePackets(itemizeList(leftItem), itemizeList('[' + rightItem + ']')) isStillValid?.let { return it } } else if (rightItem.isNotEmpty() && rightItem[0] == '[') { val isStillValid = comparePackets(itemizeList('[' + leftItem + ']'), itemizeList(rightItem)) isStillValid?.let { return it } } else { // Start the comparison val leftItemValue = leftItem.toInt() val rightItemValue = rightItem.toInt() // println("Comparing ${leftItemValue} to ${rightItemValue}") if (leftItemValue < rightItemValue) { // println("Left item smaller -> true") return true } else if (leftItemValue > rightItemValue) { // println("Right item smaller -> false") return false } } } return null } fun part1(input: List<String>): Int { var lineCount = 0 var pairIndex = 1 var pairIndexTotal = 0 var leftLine: String = "" var rightLine: String = "" input.forEach { if (lineCount == 0) { leftLine = it } else if (lineCount == 1) { rightLine = it } if (lineCount == 2) { // Should hit empty line val result = comparePackets(itemizeList(leftLine), itemizeList(rightLine)) result?.let { if (result) { pairIndexTotal += pairIndex } } leftLine = "" rightLine = "" lineCount = 0 pairIndex += 1 } else { lineCount += 1 } } return pairIndexTotal } fun part2(input: List<String>): Int { // Remove empty lines val updatedInput = input.filter { it.isNotEmpty() }.toMutableList() updatedInput.add("[[2]]") updatedInput.add("[[6]]") updatedInput.sortWith(comparator = { a, b -> val isValid = comparePackets(itemizeList(a), itemizeList(b)) if (isValid!!) 1 else -1 }) updatedInput.reverse() // Display the lines // updatedInput.forEach { println(it) } val dividerPacketIndex1 = (updatedInput.indexOfFirst { it == "[[2]]" } + 1) val dividerPacketIndex2 = (updatedInput.indexOfFirst { it == "[[6]]" } + 1) return dividerPacketIndex1 * dividerPacketIndex2 } val input = readInput("Day13") part1(input).println() part2(input).println() }
0
Kotlin
0
0
2698c65af0acd1fce51525737ab50f225d6502d1
5,293
aoc2022
Apache License 2.0
src/main/kotlin/days/y2019/Day04/day05.kt
jewell-lgtm
569,792,185
false
{"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123}
package days.y2019.Day04 import days.Day public class Day04 : Day(2019, 4) { override fun partOne(input: String): Any { val (start, end) = input.split("-").map { it.toInt() } return (start..end).count { it.isValid() } } override fun partTwo(input: String): Any { val (start, end) = input.split("-").map { it.toInt() } return (start..end).filter { it.isValid() }.count { it.isValid2() } } } private fun Int.isValid2():Boolean = toString().isValid2() private fun Int.isValid(): Boolean = toString().isValid() fun String.isValid(): Boolean { if (length != 6) return false if (toCharArray().sorted().joinToString("") != this) return false return hasDoubleChar() } fun String.isValid2(): Boolean { val groupsOfChars = toCharArray().groupBy { it } return groupsOfChars.any { it.value.size == 2 } } private fun String.hasDoubleChar(): Boolean { var lastChar = ' ' for (char in this) { if (char == lastChar) return true lastChar = char } return false }
0
Kotlin
0
0
b274e43441b4ddb163c509ed14944902c2b011ab
1,058
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/d13_TransparentOrigami/TransparentOrigami.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d13_TransparentOrigami import util.Coord import util.Input import util.Output import kotlin.math.abs fun main() { Output.day(13, "Transparent Origami") val startTime = Output.startTime() val input = Input.parseLines(filename = "/input/d13_fold_instructions.txt") var page = input.dropLastWhile { it.isNotBlank() }.dropLast(1).map { val c = it.split(",") Coord(x = c[0].toInt(), y = c[1].toInt()) } var instructions = input.takeLastWhile { it.isNotBlank() }.map { Pair( it[it.indexOf("=") - 1], it.slice(it.indexOf("=") + 1 until it.length).toInt() ) } // fold once page = page.foldBy(instructions[0].first, instructions[0].second) val firstFoldResult = page.size instructions = instructions.drop(1) // finish folding instructions.forEach { page.foldBy(it.first, it.second) } Output.part(1, "Points after First Fold", firstFoldResult) Output.part(2, "Code", "") page.print() Output.executionTime(startTime) } /** * Fold page by axis and line/column */ fun List<Coord>.foldBy(axis: Char, foldLine: Int): List<Coord> { val flippers = if (axis == 'x') filter { it.x > foldLine } else filter { it.y > foldLine } flippers.forEach { if (axis == 'x') it.x = abs(it.x - (foldLine * 2)) else it.y = abs(it.y - (foldLine * 2)) } return this.distinct() } fun List<Coord>.print() { println() val width = maxOf { it.x } val height = maxOf { it.y } val p = Array(size = height + 1) { Array(size = width + 1) { ' ' } } forEach { p[it.y][it.x] = '%' } p.forEach { x -> x.forEach { print(it) } println() } println() }
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
1,789
advent-of-code-2021
MIT License
src/Day14.kt
HaydenMeloche
572,788,925
false
{"Kotlin": 25699}
import java.lang.Integer.max import java.lang.Integer.min fun main() { val input = readInput("Day14test") infix fun Int.range(i: Int) = min(this, i)..max(this, i) val rock = input.flatMap { row -> row.split(" -> ", ",").map(String::toInt).windowed(4, 2).flatMap { (x1, y1, x2, y2) -> if (x1 == x2) (y1 range y2).map { Pair(x1, it) } else (x1 range x2).map { Pair(it, y1) } } }.toSet() val maxY = rock.maxOf { it.second } val source = Pair(500, 0) fun Pair<Int, Int>.flowTo() = let { (x, y) -> sequenceOf(x to y + 1, x - 1 to y + 1, x + 1 to y + 1) } .filterNot { it in rock || it.second >= maxY + 2 } val stableSand = mutableSetOf<Pair<Int, Int>>() var reachedFloor = false var s: Pair<Int, Int> = source while (source !in stableSand) { s = s.flowTo().firstOrNull { it !in stableSand } ?: source.also { stableSand += s } if (s.second == maxY + 1 && !reachedFloor) println(stableSand.size).also { reachedFloor = true } } println(stableSand.size) }
0
Kotlin
0
1
1a7e13cb525bb19cc9ff4eba40d03669dc301fb9
1,056
advent-of-code-kotlin-2022
Apache License 2.0
2016/src/main/kotlin/com/koenv/adventofcode/Day1.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day1 { fun getBlocksAway(input: String): Int { var heading: Int = 0 // heading North, positive is clockwise // store our coordinates var x: Int = 0 var y: Int = 0 input.split(",").map(String::trim).forEach { heading = getNewHeading(heading, it[0]) val blocks = it.substring(1).toInt() val (xDiff, yDiff) = getXYDiff(heading, blocks) x += xDiff y += yDiff } // the total distance is away is just the total x + total y distance return Math.abs(x) + Math.abs(y) } fun getFirstLocationVisitedTwice(input: String): Int { var heading: Int = 0 // heading North, positive is clockwise // store our coordinates var x: Int = 0 var y: Int = 0 val visitedLocations = mutableListOf<Pair<Int, Int>>() input.split(",").map(String::trim).forEach { heading = getNewHeading(heading, it[0]) val blocks = it.substring(1).toInt() var (xDiff, yDiff) = getXYDiff(heading, blocks) while (Math.abs(xDiff) > 0) { val sign = Integer.signum(xDiff) xDiff -= sign x += sign val location = x to y if (location in visitedLocations) { // the total distance is away is just the total x + total y distance return Math.abs(x) + Math.abs(y) } visitedLocations.add(x to y) } while (Math.abs(yDiff) > 0) { val sign = Integer.signum(yDiff) yDiff -= sign y += sign val location = x to y if (location in visitedLocations) { // the total distance is away is just the total x + total y distance return Math.abs(x) + Math.abs(y) } visitedLocations.add(x to y) } } throw IllegalStateException("There were no locations that were visited twice") } fun getNewHeading(oldHeading: Int, direction: Char): Int { var newHeading = oldHeading newHeading += when (direction) { 'R' -> 90 'L' -> -90 else -> throw IllegalStateException("Direction is $direction") } // make sure we are in the range -360 to 360 newHeading = newHeading.mod(360) // and we don't want negative headings if (newHeading < 0) { newHeading += 360 } return newHeading } fun getXYDiff(heading: Int, blocks: Int): Pair<Int, Int> { when (heading) { 0 -> return 0 to -blocks 90 -> return blocks to 0 180 -> return 0 to blocks 270 -> return -blocks to 0 else -> throw IllegalStateException("Heading is $heading") } } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
2,996
AdventOfCode-Solutions-Kotlin
MIT License
src/main/kotlin/org/kotrix/matrix/MatrixExponentialPrototype.kt
JarnaChao09
285,169,397
false
{"Kotlin": 446442, "Jupyter Notebook": 26378}
package org.kotrix.matrix import org.kotrix.utils.by import kotlin.math.abs /** * @param current the current resultant matrix in the series * @param previous the previous resultant matrix in the series * * @return true if the matrices have converged based on a tolerance */ private fun checkForConvergence(current: DoubleMatrix, previous: DoubleMatrix, tolerance: Double = 1e-15): Boolean { var ret = true // change to addIndexed (if added) for (r in 0 until current.rowLength) { for (c in 0 until current.colLength) { ret = ret && abs(current[r, c] - previous[r, c]) < tolerance } } return ret } operator fun DoubleMatrix.div(n: Double): DoubleMatrix = DoubleMatrix(this.shape) { r, c -> this[r, c] / n } fun DoubleMatrix.pow(rhs: Int): DoubleMatrix { return if (rhs == 0) { DoubleMatrix.identity(this.rowLength) } else { var ret = DoubleMatrix(this) for (i in 0 until rhs - 1) { ret = this matMult ret } ret } } fun expm(m: DoubleMatrix, tolerance: Double = 1e-15): DoubleMatrix { fun DoubleMatrix.correctZerosForTolerance(tol: Double) { for (r in 0 until this.rowLength) { for (c in 0 until this.colLength) { this[r, c] = if(abs(this[r, c]) < tol) 0.0 else this[r, c] } } } require(m.isSquare()) { "Matrix exponentiation only operates on square matrices" } var curr = DoubleMatrix.zeros(m.shape) var prev = DoubleMatrix.zeros(m.shape) val factorial = mutableListOf<Double>() var i = 0 while (i == 0 || !checkForConvergence(curr, prev, tolerance)) { factorial += if (i == 0) 1.0 else i.toDouble() * factorial[i - 1] prev = curr curr = curr + (m.pow(i) / factorial[i]) curr.correctZerosForTolerance(tolerance) i++ } return curr } fun main() { val t = DoubleMatrix.of(2 by 2, 0.0, -kotlin.math.PI, kotlin.math.PI, 0.0) val t1 = DoubleMatrix.of(3 by 3, 3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0, 5.0) println("$t\n${expm(t)}\n") println("$t1\n${expm(t1)}") }
0
Kotlin
1
5
c5bb19457142ce1f3260e8fed5041a4d0c77fb14
2,165
Kotrix
MIT License
src/main/kotlin/com/colinodell/advent2016/Day15.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day15(input: List<String>) { private val discs = input.map { Disc.fromString(it) } fun solvePart1() = solve(false) fun solvePart2() = solve(true) private fun solve(withExtraDisc: Boolean): Int { val discs = if (withExtraDisc) this.discs.plus(Disc(this.discs.size + 1, 11, 0)) else this.discs return (0..Int.MAX_VALUE).first { time -> discs.all { it.isOpen(time) } } } private data class Disc(val offset: Int, val positions: Int, val initialPosition: Int) { fun isOpen(time: Int) = (time + offset + initialPosition) % positions == 0 companion object { fun fromString(s: String): Disc { Regex("Disc #(\\d+) has (\\d+) positions; at time=0, it is at position (\\d+).").matchEntire(s)!!.let { val (offset, positions, initialPosition) = it.groupValues.drop(1).map { it.toInt() } return Disc(offset, positions, initialPosition) } } } } }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,061
advent-2016
Apache License 2.0
src/Day17.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
import java.util.* fun main() { val testInput = readInput("Day17_test")[0] check(part1(testInput) == 3068) check(part2(testInput) == 1514285714288L) val input = readInput("Day17")[0] println(part1(input)) println(part2(input)) } private const val PART1_ROCKS_COUNT = 2022 private const val PART2_ROCKS_COUNT = 1_000_000_000_000L private fun part1(input: String): Int { val shifter = Shifter(input) val cave = LinkedList<Int>() val generator = RockGenerator() repeat(PART1_ROCKS_COUNT) { val rock = generator.nextRock() cave.fall(rock, shifter) } return cave.size } private const val PATTERN_SIZE = 20 private fun part2(input: String): Long { val shifter = Shifter(input) val cave = LinkedList<Int>() val generator = RockGenerator() var pattern: List<Int>? = null var patternFoundIteration = 0L var patternFoundCaveSize = 0 var skippedCaveSize = 0L var count = PART2_ROCKS_COUNT while (count > 0) { val rock = generator.nextRock() cave.fall(rock, shifter) --count //State of the cave repeats iteratively. Find this repetition and use it to skip the huge amount of calculations if (pattern == null) { //Try to find pattern val index = cave.findPattern(PATTERN_SIZE) if (index >= 0) { pattern = cave.takeLast(PATTERN_SIZE) patternFoundIteration = count patternFoundCaveSize = cave.size } } else { //Wait for the next repetition of the pattern if (cave.subList(cave.size - PATTERN_SIZE, cave.size) == pattern) { val rocksPerIteration = patternFoundIteration - count val caveIncreasePerIteration = cave.size - patternFoundCaveSize val skippedIterations = count / rocksPerIteration skippedCaveSize = skippedIterations * caveIncreasePerIteration count %= rocksPerIteration } } } return skippedCaveSize + cave.size } private fun List<Int>.findPattern(patternSize: Int): Int { if (this.size < 2 * patternSize) { return -1 } val tail = this.subList(this.size - patternSize, this.size) for (i in (this.size - patternSize) downTo patternSize) { if (tail == this.subList(i - patternSize, i)) { return i } } return -1 } private fun LinkedList<Int>.fall(rock: IntArray, shifter: Shifter) { val caveRows = IntArray(rock.size) //First 4 shifts happen before rock will rich the most top row of the cave repeat(4) { shifter.next().invoke(rock, caveRows) } var bottom = this.lastIndex while (true) { if (bottom == -1) { break } for (i in caveRows.lastIndex downTo 1) { caveRows[i] = caveRows[i - 1] } caveRows[0] = this[bottom] val canFall = rock.foldIndexed(true) { i, acc, value -> acc && (value and caveRows[i] == 0) } if (canFall) { --bottom } else { break } shifter.next().invoke(rock, caveRows) } rock.forEachIndexed { i, value -> if ((bottom + i + 1) in this.indices) { this[bottom + i + 1] = this[bottom + i + 1] or value } else { this.addLast(value) } } } private const val LEFT_BORDER = 0b1000000 private const val RIGHT_BORDER = 0b0000001 class Shifter(private val pattern: String) { private var current: Int = 0 private val left: (IntArray, IntArray) -> Unit = { rock, caveRows -> val canShift = rock.foldIndexed(true) { i, acc, value -> acc && ((value and LEFT_BORDER) == 0) && ((value shl 1) and caveRows[i] == 0) } if (canShift) { rock.forEachIndexed { i, value -> rock[i] = value shl 1 } } } private val right: (IntArray, IntArray) -> Unit = { rock, caveRows -> val canShift = rock.foldIndexed(true) { i, acc, value -> acc && (value and RIGHT_BORDER == 0) && ((value shr 1) and caveRows[i] == 0) } if (canShift) { rock.forEachIndexed { i, value -> rock[i] = value shr 1 } } } fun next(): (IntArray, IntArray) -> Unit { return (if (pattern[current] == '<') left else right).also { current = (current + 1) % pattern.length } } } private class RockGenerator { private var i = 0 val rocks = listOf( intArrayOf( 0b0011110, ), intArrayOf( 0b0001000, 0b0011100, 0b0001000, ), intArrayOf( 0b0011100, 0b0000100, 0b0000100, ), intArrayOf( 0b0010000, 0b0010000, 0b0010000, 0b0010000, ), intArrayOf( 0b0011000, 0b0011000, ), ) fun nextRock(): IntArray { return rocks[i].copyOf().also { i = (i + 1) % rocks.size } } }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
5,143
AOC2022
Apache License 2.0
src/main/kotlin/Main.kt
Trilgon
484,536,097
false
{"Kotlin": 2146}
import java.util.* fun main(args: Array<String>) { val input: StringBuilder = StringBuilder("10.3 + -2") val queueNumbers: Queue<Double> = LinkedList<Double>() val queueActions: Queue<Char> = LinkedList<Char>() println('\"' + input.toString() + '\"') prepareIn(input, queueNumbers, queueActions) calculateIn(queueNumbers, queueActions) } fun prepareIn(input: StringBuilder, queueNumbers: Queue<Double>, queueActions: Queue<Char>) { var numDetected = false var startIndex = 0 val trimmedIn = input.filter { !it.isWhitespace() } for (i in 0..trimmedIn.lastIndex) { when { trimmedIn[i].isDigit() && !numDetected -> { startIndex = i numDetected = true } !trimmedIn[i].isDigit() && numDetected && trimmedIn[i] != '.' -> { queueNumbers.add(trimmedIn.substring(startIndex, i).toDouble()) queueActions.add(trimmedIn[i]) numDetected = false } !trimmedIn[i].isDigit() && !numDetected && trimmedIn[i] == '-' -> { startIndex = i numDetected = true } } } if (numDetected) { queueNumbers.add(trimmedIn.substring(startIndex..trimmedIn.lastIndex).toDouble()) } println(queueNumbers) println(queueActions) } fun calculateIn(queueNumbers: Queue<Double>, queueActions: Queue<Char>) { var action: Char var result = queueNumbers.poll() var operand: Double while (!queueNumbers.isEmpty()) { operand = queueNumbers.poll() action = queueActions.poll() when (action) { '-' -> result -= operand '+' -> result += operand '*' -> result *= operand '/' -> result /= operand '%' -> result = result % operand * -1.0 } } var pointNum = 8.3 println("pointNum = " + pointNum) println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum) println("result = " + result) println(if(result.compareTo(result.toInt()) == 0) result.toInt() else result) }
0
Kotlin
0
0
8273ff6e20072015b01a1b8ba3432b8e17728601
2,146
LearningKotlin
MIT License
day3/day3/src/main/kotlin/Day13.kt
teemu-rossi
437,894,529
false
{"Kotlin": 28815, "Rust": 4678}
data class PointI(val x: Int, val y: Int) fun main(args: Array<String>) { val values = generateSequence(::readLine) .mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } } .toList() val coords = values .filter { it.contains(",") } .map { val (x, y) = it.split(",") PointI(x.toInt(), y.toInt()) } val folds = mutableListOf<(PointI) -> PointI>() values .filter { it.contains("=") } .forEach { val (a, b) = it.split("=") val axis = a.last() val coord = b.toInt() if (axis == 'x') { folds += { point -> point.copy(x = if (point.x > coord) 2 * coord - point.x else point.x) } } else if (axis == 'y') { folds += { point -> point.copy(y = if (point.y > coord) 2 * coord - point.y else point.y) } } } val foldedCoords1 = coords.map { point -> folds.take(1).fold(point) { i, p -> p(i) } }.toSet() println("foldedCoords1.size=${foldedCoords1.size}") val foldedCoords2 = coords.map { point -> folds.fold(point) { i, p -> p(i) } }.toSet() println("foldedCoords2.size=${foldedCoords2.size}") for (y in 0..foldedCoords2.maxOf { it.y }) { println(buildString { for (x in 0..foldedCoords2.maxOf { it.x }) { if (PointI(x, y) in foldedCoords2) append("#") else append(".") } }) } }
0
Kotlin
0
0
16fe605f26632ac2e134ad4bcf42f4ed13b9cf03
1,482
AdventOfCode
MIT License
src/main/kotlin/g0301_0400/s0373_find_k_pairs_with_smallest_sums/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0373_find_k_pairs_with_smallest_sums // #Medium #Array #Heap_Priority_Queue #2022_11_22_Time_1809_ms_(80.95%)_Space_119.1_MB_(66.67%) import java.util.PriorityQueue import kotlin.collections.ArrayList class Solution { private class Node(index: Int, num1: Int, num2: Int) { var sum: Long var al: MutableList<Int> var index: Int init { sum = num1.toLong() + num2.toLong() al = ArrayList() al.add(num1) al.add(num2) this.index = index } } fun kSmallestPairs(nums1: IntArray, nums2: IntArray, k: Int): List<List<Int>> { val queue = PriorityQueue { a: Node, b: Node -> if (a.sum < b.sum) -1 else 1 } val res: MutableList<List<Int>> = ArrayList() run { var i = 0 while (i < nums1.size && i < k) { queue.add(Node(0, nums1[i], nums2[0])) i++ } } var i = 1 while (i <= k && queue.isNotEmpty()) { val cur = queue.poll() res.add(cur.al) val next = cur.index val lastNum1 = cur.al[0] if (next + 1 < nums2.size) { queue.add(Node(next + 1, lastNum1, nums2[next + 1])) } i++ } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,350
LeetCode-in-Kotlin
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day17/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day17 import de.skyrising.aoc.* import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap import kotlin.math.max private fun collides(rock: List<Vec2i>, pos: Vec2i, landed: Set<Vec2i>): Boolean { for (p in rock) { val p1 = p + pos if (p1.x < 0 || p1.x >= 7 || p1.y < 0 || p1 in landed) return true } return false } private fun printPit(landed: Set<Vec2i>, moving: Collection<Vec2i>? = null) { if (landed.isEmpty() && moving.isNullOrEmpty()) return var bbox = landed.boundingBox().expand(Vec2i(0, 0)).expand(Vec2i(6, 0)) if (!moving.isNullOrEmpty()) bbox = bbox.expand(moving.boundingBox()) val grid = bbox.charGrid { '.' } grid[landed] = '#' if (moving != null) grid[moving] = '@' for (i in grid.height - 1 downTo 0) { print('|') for (j in 0 until grid.width) { print(grid[j + grid.offset.x, i + grid.offset.y]) } println('|') } println("+" + "-".repeat(grid.width) + "+") } private val rocks = listOf( CharGrid(4, 1, "####".toCharArray()), CharGrid(3, 3, ".#.###.#.".toCharArray()), CharGrid(3, 3, "###..#..#".toCharArray()), CharGrid(1, 4, "####".toCharArray()), CharGrid(2, 2, "####".toCharArray()), ).map { it.where { c -> c == '#' } } private fun dropRocks(input: PuzzleInput, rockCount: Long): Long { data class Key(val rock: Int, val move: Int, val window: Set<Vec2i>) val seen = Object2LongOpenHashMap<Key>() seen.defaultReturnValue(-1) val heights = IntArrayList() val height = IntArray(7) val moves = input.chars.mapNotNull { when (it) { '>' -> 1 '<' -> -1 else -> null } } val landed = mutableSetOf<Vec2i>() var step = 0 for (i in 0 until rockCount) { val rock = rocks[(i % rocks.size).toInt()] var pos = Vec2i(2, 3 + (landed.maxOfOrNull { it.y }?:-1) + 1) while (true) { val side = Vec2i(pos.x + moves[step++ % moves.size], pos.y) if (!collides(rock, side, landed)) pos = side val down = Vec2i(pos.x, pos.y - 1) if (collides(rock, down, landed)) break pos = down } for (p in rock) { landed.add(p + pos) height[p.x + pos.x] = max(height[p.x + pos.x], p.y + pos.y) } val maxHeight = height.max() heights.add(maxHeight) val window = landed.filter { it.y in maxHeight - 9 .. maxHeight }.map { Vec2i(it.x, it.y - maxHeight) }.toSet() val key = Key((i % rocks.size).toInt(), step % moves.size, window) val prev = seen.put(key, i) if (prev >= 0) { val cycleLength = i - prev val cycleHeight = maxHeight - heights.getInt(prev.toInt()) val cyclesRemaining = (rockCount - i - 1) / cycleLength val offset = (rockCount - i - 1) % cycleLength val remainderHeight = heights.getInt((prev + offset).toInt()) - heights.getInt(prev.toInt()) input.log("Cycle detected at rock $i step $step ($prev -> $i) length: $cycleLength height: $cycleHeight cycles remaining: $cyclesRemaining offset: $offset remainder height: $remainderHeight") return maxHeight + cycleHeight * cyclesRemaining + remainderHeight + 1L } //printPit(landed) } //printPit(landed) return height.max() + 1L } val test = TestInput(">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>") @PuzzleName("Pyroclastic Flow") fun PuzzleInput.part1() = dropRocks(this, 2022) fun PuzzleInput.part2() = dropRocks(this, 1000000000000L)
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
3,639
aoc
MIT License
src/Day06.kt
mcdimus
572,064,601
false
{"Kotlin": 32343}
import util.readInput fun main() { fun part1(input: List<String>) = findLastIndexOfUniqueCharsSequence(input[0], 4) fun part2(input: List<String>) = findLastIndexOfUniqueCharsSequence(input[0], 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 10) check(part2(testInput) == 29) val input = readInput("Day06") println(part1(input)) println(part2(input)) } private fun findLastIndexOfUniqueCharsSequence(str: String, sequenceSize: Int) = str.indices .firstOrNull { i -> hasUniqueSequenceStartingFromIndexOfSize(str, i, sequenceSize) } ?.plus(sequenceSize) ?: -1 private fun hasUniqueSequenceStartingFromIndexOfSize(str: String, i: Int, size: Int) = str.substring(i, i + size).toSet().size == size
0
Kotlin
0
0
dfa9cfda6626b0ee65014db73a388748b2319ed1
842
aoc-2022
Apache License 2.0
year2015/src/main/kotlin/net/olegg/aoc/year2015/day16/Day16.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2015.day16 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2015.DayOf2015 /** * See [Year 2015, Day 16](https://adventofcode.com/2015/day/16) */ object Day16 : DayOf2015(16) { private val PATTERN = "^Sue (\\d+): (.*)$".toRegex() private val ANIMAL = "([a-z]+): (\\d+)".toRegex() private val SUES = lines .mapNotNull { line -> PATTERN.matchEntire(line)?.let { match -> val index = match.groupValues[1].toInt() val animals = match.groupValues[2] val own = ANIMAL.findAll(animals).associate { val (animal, count) = it.destructured animal to count.toInt() } return@let index to own } } private val FOOTPRINT = mapOf( "children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1, ) override fun first(): Any? { return SUES .first { sue -> sue.second.all { it.value == FOOTPRINT[it.key] } } .first } override fun second(): Any? { return SUES .first { (_, own) -> own.all { (key, value) -> val footprintValue = FOOTPRINT[key] ?: 0 when (key) { "cats", "trees" -> value > footprintValue "pomeranians", "goldfish" -> value < footprintValue else -> value == footprintValue } } } .first } } fun main() = SomeDay.mainify(Day16)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,520
adventofcode
MIT License
src/Day01.kt
RichardLiba
572,867,612
false
{"Kotlin": 16347}
import java.lang.Integer.max fun main() { fun part1(input: List<String>): Int { var caloriesForElf = 0 val caloriesByElves: MutableList<Int> = mutableListOf() var max = 0 input.forEach { if (it.isEmpty() || it.toIntOrNull() == null) { // next elf max = max(max, caloriesForElf) caloriesByElves.add(caloriesForElf) caloriesForElf = 0 } else { // add up calories caloriesForElf += it.toInt() } } return max } fun part2(input: List<String>): Int { var caloriesForElf = 0 val caloriesByElves: MutableList<Int> = mutableListOf() input.forEach { if (it.isEmpty() || it.toIntOrNull() == null) { // next elf caloriesByElves.add(caloriesForElf) caloriesForElf = 0 } else { // add up calories caloriesForElf += it.toInt() } } return caloriesByElves.sortedDescending().take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6a0b6b91b5fb25b8ae9309b8e819320ac70616ed
1,219
aoc-2022-in-kotlin
Apache License 2.0
baparker/10/main.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File val OPENERS = listOf('(', '[', '{', '<') val CLOSERS = listOf(')', ']', '}', '>') val PENALTIES = listOf(3, 57, 1197, 25137) val GOOD_VALUES = listOf(1, 2, 3, 4) fun parseLineAndFindFirstError(line: String): Int { val openerStack: MutableList<Char> = mutableListOf() line.forEach { if (OPENERS.contains(it)) { openerStack.add(it) } else { val prev = openerStack.last() val openerIndex = OPENERS.indexOf(prev) val closerIndex = CLOSERS.indexOf(it) if (closerIndex != openerIndex) { val closerValue = PENALTIES.get(closerIndex) return closerValue } else { openerStack.removeLast() } } } return 0 } fun parseLineAndComplete(line: String): Long { val openerStack: MutableList<Char> = mutableListOf() line.forEach { if (OPENERS.contains(it)) { openerStack.add(it) } else { val prev = openerStack.last() if (CLOSERS.indexOf(it) != OPENERS.indexOf(prev)) { return 0 } else { openerStack.removeLast() } } } return openerStack.reversed().fold(0) { sum, opener -> val openerIndex = OPENERS.indexOf(opener) (sum * 5) + GOOD_VALUES.get(openerIndex) } } fun main() { var errorCounter = 0 var pointsList: MutableList<Long> = mutableListOf() File("input.txt").forEachLine { errorCounter += parseLineAndFindFirstError(it) val linePoints = parseLineAndComplete(it) if (linePoints > 0) pointsList.add(linePoints) } println(errorCounter) println(pointsList.sorted().get((pointsList.size - 1) / 2).toBigDecimal().toPlainString()) }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
1,811
advent-of-code-2021
MIT License
src/main/kotlin/g1701_1800/s1733_minimum_number_of_people_to_teach/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1733_minimum_number_of_people_to_teach // #Medium #Array #Greedy #2023_06_16_Time_580_ms_(100.00%)_Space_57.1_MB_(100.00%) class Solution { fun minimumTeachings(n: Int, languages: Array<IntArray>, friendships: Array<IntArray>): Int { val m: Int = languages.size val speak: Array<BooleanArray> = Array(m + 1) { BooleanArray(n + 1) } val teach: Array<BooleanArray> = Array(m + 1) { BooleanArray(n + 1) } for (user in 0 until m) { val userLanguages: IntArray = languages[user] for (userLanguage: Int in userLanguages) { speak[user + 1][userLanguage] = true } } val listToTeach: MutableList<IntArray> = ArrayList() for (friend: IntArray in friendships) { val userA: Int = friend[0] val userB: Int = friend[1] var hasCommonLanguage = false for (language in 1..n) { if (speak[userA][language] && speak[userB][language]) { hasCommonLanguage = true break } } if (!hasCommonLanguage) { for (language in 1..n) { if (!speak[userA][language]) { teach[userA][language] = true } if (!speak[userB][language]) { teach[userB][language] = true } } listToTeach.add(friend) } } var minLanguage: Int = Int.MAX_VALUE var languageToTeach = 0 for (language in 1..n) { var count = 0 for (user in 1..m) { if (teach[user][language]) { count++ } } if (count < minLanguage) { minLanguage = count languageToTeach = language } } val setToTeach: MutableSet<Int> = HashSet() for (friend: IntArray in listToTeach) { val userA: Int = friend[0] val userB: Int = friend[1] if (!speak[userA][languageToTeach]) { setToTeach.add(userA) } if (!speak[userB][languageToTeach]) { setToTeach.add(userB) } } return setToTeach.size } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,379
LeetCode-in-Kotlin
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions35.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import kotlin.math.min fun test35() { printlnResult(arrayOf("23:50", "23:59", "00:00")) printlnResult(arrayOf("20:50", "23:59", "21:38", "19:23", "18:47", "22:16")) } /** * Questions 35: Give a group of time, find the smallest time difference */ private fun Array<String>.smallestDifference(): Int { require(size > 1) { "The size of time array can't less than 2" } val timeArray = BooleanArray(1440) forEach { val timeIndex = it.timeIndex if (timeArray[timeIndex]) return 0 timeArray[timeIndex] = true } var start = 0 while (!timeArray[start]) start++ val first = start var end = start + 1 var last = end var diff = Int.MAX_VALUE while (end < timeArray.size) { while (end < timeArray.size && !timeArray[end]) end++ if (end < timeArray.size) { val newDiff = end - start if (newDiff < diff) diff = newDiff last = end start = end++ } } return min(diff, first + timeArray.size - last) } private val String.timeIndex: Int get() = substring(0, 2).toInt() * 60 + substring(3, 5).toInt() private fun printlnResult(times: Array<String>) = println("The smallest time difference in ${times.toList()} is ${times.smallestDifference()}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,382
Algorithm
Apache License 2.0
src/days/Day05.kt
EnergyFusion
572,490,067
false
{"Kotlin": 48323}
import java.io.BufferedReader fun main() { val day = 5 fun buildStacks(map: List<String>): List<ArrayDeque<Char>> { val numberOfColumns = map.last().trim().last().toString().toInt() val stacks = List(numberOfColumns) { ArrayDeque<Char>() } map.dropLast(1).reversed().forEach { line -> line.chunked(4).forEachIndexed { i, item -> if (item.isNotBlank()) { stacks[i].addLast(item[1]) } } } return stacks } fun performMove1(stacks: List<ArrayDeque<Char>>, numOfElements: Int, fromIndex: Int, toIndex: Int) { var numOfE = numOfElements while (numOfE > 0) { val element = stacks[fromIndex].removeLast() stacks[toIndex].addLast(element) numOfE-- } } fun part1(inputReader: BufferedReader): String { var message = "" inputReader.useLines { val (map, moves) = it.partition { line -> line.matches("^[0-9 ]+$".toRegex()) || line.matches("^[A-Z \\[\\]]+$".toRegex()) } val stacks = buildStacks(map) // println(columns) moves.drop(1).forEach { line -> val elements = line.split(" ") var numOfElements = elements[1].toInt() val fromIndex = elements[3].toInt() - 1 val toIndex = elements[5].toInt() - 1 performMove1(stacks, numOfElements, fromIndex, toIndex) } // println(columns) message = String(stacks.map { it.removeLast() }.toCharArray()) // println(message) } return message } fun performMove2(stacks: MutableList<ArrayDeque<Char>>, numOfElements: Int, fromIndex: Int, toIndex: Int) { val stack = stacks[fromIndex] stacks[fromIndex] = ArrayDeque(stack.subList(0, stack.size - numOfElements)) stacks[toIndex].addAll(stack.subList(stack.size - numOfElements, stack.size)) } fun part2(inputReader: BufferedReader): String { var message = "" inputReader.useLines { val (map, moves) = it.partition { line -> line.matches("^[0-9 ]+$".toRegex()) || line.matches("^[A-Z \\[\\]]+$".toRegex()) } val stacks = buildStacks(map).toMutableList() // println(columns) moves.drop(1).forEach { line -> val elements = line.split(" ") var numOfElements = elements[1].toInt() val fromIndex = elements[3].toInt() - 1 val toIndex = elements[5].toInt() - 1 performMove2(stacks, numOfElements, fromIndex, toIndex) } println(stacks) message = String(stacks.map { it.removeLast() }.toCharArray()) // println(message) } return message } val testInputReader = readBufferedInput("tests/Day%02d".format(day)) // check(part1(testInputReader) == "CMZ") check(part2(testInputReader) == "MCD") val input = readBufferedInput("input/Day%02d".format(day)) // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
06fb8085a8b1838289a4e1599e2135cb5e28c1bf
3,219
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/day18.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
import java.util.ArrayDeque class Day18 : Solvable("18") { override fun solveA(input: List<String>): String { return input .map { SnailFishNumber.fromString(it) } .reduce { l, r -> l + r } .magnitude() .toString() } override fun solveB(input: List<String>): String { return input .map { input .filter { o -> it != o } .map { o -> (SnailFishNumber.fromString(it) + SnailFishNumber.fromString(o)) .magnitude() } .max() ?: 0 } .max() .toString() } } abstract class SnailFishNumber(var parent: PairNumber?, var depth: Int = 0) { abstract fun explode(): Boolean abstract fun split(): Boolean abstract fun magnitude(): Int fun reduce() { while (explode() || split()) {} } operator fun plus(other: SnailFishNumber): SnailFishNumber = PairNumber(this, other).also { it.initializeDepth() it.reduce() } abstract fun addToLeftRegularNumber(value: Int, child: PairNumber?) abstract fun addToRightRegularNumber(value: Int, child: PairNumber?) abstract fun initializeDepth(depth: Int = 0) companion object { fun fromString(s: String): SnailFishNumber { val numbers = ArrayDeque<SnailFishNumber>() s.forEach { if (it.isDigit()) { numbers.addLast(RegularNumber(it.toInt() - 48)) } else if (it == ']') { val right = numbers.removeLast() val left = numbers.removeLast() numbers.addLast(PairNumber(left, right)) } } return numbers.removeLast() } } } class PairNumber(var left: SnailFishNumber, var right: SnailFishNumber) : SnailFishNumber(null) { init { left.parent = this right.parent = this } override fun explode(): Boolean { if (depth == 4) { parent?.childExploded(this) return true } else { return left.explode() || right.explode() } } override fun split() = left.split() || right.split() override fun magnitude() = 3 * left.magnitude() + 2 * right.magnitude() fun childExploded(child: PairNumber) { val zero = RegularNumber(0).also { it.depth = depth + 1 it.parent = this } if (child == left) { left = zero parent?.addToLeftRegularNumber((child.left as RegularNumber).number, this) right.addToLeftRegularNumber((child.right as RegularNumber).number, null) } else { right = zero left.addToRightRegularNumber((child.left as RegularNumber).number, null) parent?.addToRightRegularNumber((child.right as RegularNumber).number, this) } } fun childSplit(child: RegularNumber) { val l = child.number / 2 val r = child.number - l val pair = PairNumber(RegularNumber(l), RegularNumber(r)).also { it.depth = depth + 1 it.parent = this } if (child == left) left = pair else if (child == right) right = pair } override fun addToLeftRegularNumber(value: Int, child: PairNumber?) { if (child == null) left.addToLeftRegularNumber(value, null) else if (child == left) parent?.addToLeftRegularNumber(value, this) else if (child == right) left.addToRightRegularNumber(value, null) } override fun addToRightRegularNumber(value: Int, child: PairNumber?) { if (child == null) right.addToRightRegularNumber(value, null) else if (child == left) right.addToLeftRegularNumber(value, null) else if (child == right) parent?.addToRightRegularNumber(value, this) } override fun initializeDepth(depth: Int) { this.depth = depth left.initializeDepth(depth + 1) right.initializeDepth(depth + 1) } } class RegularNumber(var number: Int) : SnailFishNumber(null) { override fun explode() = false override fun split(): Boolean { if (number >= 10) { parent?.childSplit(this) return true } return false } override fun magnitude() = number override fun addToLeftRegularNumber(value: Int, child: PairNumber?) { number += value } override fun addToRightRegularNumber(value: Int, child: PairNumber?) { number += value } override fun initializeDepth(depth: Int) { this.depth = depth } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
4,958
AdventOfCode
Creative Commons Zero v1.0 Universal
src/Day07.kt
arturkowalczyk300
573,084,149
false
{"Kotlin": 31119}
//region data classes enum class PROMPT_TYPE { COMMAND_CD_ROOT, //move to root COMMAND_CD_LOWER_LEVEL, //lower level, means deeper in file structure COMMAND_CD_UPPER_LEVEL, //upper level means returning closer to the root of file system COMMAND_LS } abstract class FileSystemElement(var size: Int, var nodeName: String, var parent: FileSystemElement?) { protected val children: MutableList<FileSystemElement> = mutableListOf() fun calculateSize(): Int { var sum = 0 children.forEach { sum += it.calculateSize() } if (children.isEmpty()) sum += this.size this.size = sum return sum } fun getChildrenReadOnly(): List<FileSystemElement> = children.toList() fun addFile(file: File) { children.add(file) size += file.size } fun addDirectory(dir: Directory) { children.add(dir) } fun getFlatten(): List<FileSystemElement> { val mutableList = mutableListOf<FileSystemElement>() children.forEach { if (it is Directory) mutableList.addAll(it.getFlatten()) mutableList.add(it) } return mutableList.toList() } } class Root() : FileSystemElement(0, "/", null) { } class File(size: Int, nodeName: String, parent: FileSystemElement?) : FileSystemElement(size, nodeName, parent) { } class Directory(size: Int, nodeName: String, parent: FileSystemElement?) : FileSystemElement(size, nodeName, parent) { } class PromptCommand( val promptType: PROMPT_TYPE, var additionalInfo: List<String>? = null ) { } //endregion fun main() { //region create list of commands fun createListOfCommands(input: List<String>): List<PromptCommand> { //1. convert list of strings to one string var val sb = StringBuilder() input.forEach { sb.append(it + "\n") } val str = sb.toString() //2. split prompt commands var promptLines = str.split("$").toMutableList() //2.1 remove empty elements promptLines.removeAll { it == "" } //2.2 remove spaces on beginning for (i in 0 until promptLines.size) { promptLines[i] = promptLines[i].removePrefix(" ") } //3. create list of prompts val listOfCommands = mutableListOf<PromptCommand>() promptLines.forEach { val cmd = it.substring(0, 2) if (it.substring(0, 2) == "ls") { var additionalInfo = it.lines().drop(1).dropLastWhile { line -> line == "" } listOfCommands.add(PromptCommand((PROMPT_TYPE.COMMAND_LS), additionalInfo)) } else { val cdCommand = it.substring(0, 5) when (cdCommand) { "cd /", "cd /\n" -> listOfCommands.add(PromptCommand((PROMPT_TYPE.COMMAND_CD_ROOT))) "cd .." -> listOfCommands.add(PromptCommand((PROMPT_TYPE.COMMAND_CD_UPPER_LEVEL))) else -> { val obj = PromptCommand((PROMPT_TYPE.COMMAND_CD_LOWER_LEVEL)) obj.additionalInfo = listOf<String>(it.split(" ")[1].replace("\n", "")) listOfCommands.add(obj) } } } } return listOfCommands } //endregion //region file system checker (iterate and collect information about it) fun createFileStructureMap(listOfCommands: List<PromptCommand>): MutableList<FileSystemElement> { val fileSystemStructure: MutableList<FileSystemElement> = mutableListOf() //4. handle this list and create map of files var currentLevelOfIndent = 0 var currentElement: FileSystemElement? = null listOfCommands.forEach { prompt -> when (prompt.promptType) { PROMPT_TYPE.COMMAND_CD_ROOT -> { val el = Root() fileSystemStructure.add(el) currentElement = el } PROMPT_TYPE.COMMAND_CD_UPPER_LEVEL -> { currentElement = currentElement!!.parent } PROMPT_TYPE.COMMAND_CD_LOWER_LEVEL -> { val prevCurrentElement = currentElement val name = prompt.additionalInfo!![0] currentElement = currentElement!!.getChildrenReadOnly().find { it.nodeName == name } if (currentElement == null) { val el = Directory(0, name, prevCurrentElement) prevCurrentElement!!.addDirectory(el) currentElement = el } currentLevelOfIndent++ } PROMPT_TYPE.COMMAND_LS -> { //println("doing listing in node with name=${currentElement!!.nodeName}") prompt.additionalInfo!!.forEach { nodeString -> if (!nodeString.contains("dir")) //node is a file { val grp = nodeString.split(" ") val size = grp[0].toInt() val name = grp[1] //println("fullString=${nodeString}, size=${size}, name=${name}") currentElement!!.addFile(File(size, name, currentElement)) } else {//directory val name = nodeString.split(" ")[1] currentElement!!.addDirectory(Directory(0, name, currentElement)) } } } } } return fileSystemStructure } fun findSizeOfDirectoryWhichDeletionWillGiveMoreSpace(dirList: List<Directory>, neededSpace: Int): Int { val found = dirList.find { it.size >= neededSpace } return found!!.size } //endregion fun part1(input: List<String>): Int { val commandsList = createListOfCommands(input) val fileStructure = createFileStructureMap(commandsList) val flatten = fileStructure[0].getFlatten() fileStructure[0].calculateSize() var size = flatten.sumOf { if (it is Directory && it.size < 100000) it.size else 0 } return size } fun part2(input: List<String>): Int { val commandsList = createListOfCommands(input) val fileStructure = createFileStructureMap(commandsList) val flatten = fileStructure[0].getFlatten() fileStructure[0].calculateSize() //get list of dirs, sorted val directories = flatten.map { if (it is Directory) it else null }.filterNotNull() .toMutableList().apply { add(Directory(fileStructure[0].size, fileStructure[0].nodeName, null))//add / directory } .sortedBy { it.size } val totalSize = 70000000 val currentlyUsedSpace = fileStructure[0].size //currently used space val freeSpace = totalSize - currentlyUsedSpace val neededSpace = 30000000 - freeSpace return findSizeOfDirectoryWhichDeletionWillGiveMoreSpace(directories, neededSpace) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) check(part2(testInput) == 24933642) println(part2(input)) }
0
Kotlin
0
0
69a51e6f0437f5bc2cdf909919c26276317b396d
7,675
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/g1401_1500/s1498_number_of_subsequences_that_satisfy_the_given_sum_condition/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1498_number_of_subsequences_that_satisfy_the_given_sum_condition // #Medium #Array #Sorting #Binary_Search #Two_Pointers #Binary_Search_II_Day_15 // #2023_06_13_Time_487_ms_(97.89%)_Space_52.4_MB_(100.00%) class Solution { fun numSubseq(nums: IntArray, target: Int): Int { // sorted array will be used to perform binary search nums.sort() val mod = 1000000007 // powOf2[i] means (2^i) % mod val powOf2 = IntArray(nums.size) powOf2[0] = 1 for (i in 1 until nums.size) { powOf2[i] = powOf2[i - 1] * 2 % mod } var res = 0 var left = 0 var right = nums.size - 1 while (left <= right) { if (nums[left] + nums[right] > target) { // nums[right] which is macimum is too big so decrease it right-- } else { // every number between right and left be either picked or not picked // so that is why pow(2, right - left) essentially res = (res + powOf2[right - left]) % mod // increment left to find next set of min and max left++ } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,238
LeetCode-in-Kotlin
MIT License
src/main/kotlin/solutions/Day08.kt
chutchinson
573,586,343
false
{"Kotlin": 21958}
typealias Ray = Sequence<Int> class Day08 : Solver { override fun solve (input: Sequence<String>) { val heights = input.map { it.map { it.digitToInt() }}.flatten().toList() val grid = Grid(heights) println(first(grid)) println(second(grid)) } fun first (grid: Grid): Int { return grid.map { x, y -> grid .scan(x, y).any { it.all { it < grid.height(x, y) }} } .filter { it } .count() } fun second (grid: Grid): Int { return grid.map { x, y -> grid .scan(x, y) .map { it.takeUntil { it >= grid.height(x, y)}.count() } .reduce { score, h -> score * h } } .maxOf { it } } } class Grid { val field: List<Int> val size: Int constructor (field: List<Int>) { this.field = field this.size = Math.sqrt(field.size.toDouble()).toInt() } fun height (x: Int, y: Int): Int = field[y * size + x] fun raycast (fromX: Int, fromY: Int, toX: Int, toY: Int, dx: Int, dy: Int): Ray { return sequence { var x = fromX var y = fromY while (x != toX || y != toY) { yield(height(x, y)) x += dx y += dy } } } fun <T> map (fn: (x: Int, y: Int) -> T): Sequence<T> = sequence { for (y in 0..size-1) { for (x in 0..size-1) { yield(fn(x, y)) } } } fun scan (x: Int, y: Int) = sequence { yield(raycast(x, y - 1, x, -1, 0, -1)) // up yield(raycast(x - 1, y, -1, y, -1, 0)) // left yield(raycast(x, y + 1, x, size, 0, 1)) // down yield(raycast(x + 1, y, size, y, 1, 0)) // right } }
0
Kotlin
0
0
5076dcb5aab4adced40adbc64ab26b9b5fdd2a67
1,810
advent-of-code-2022
MIT License
src/main/kotlin/de/pgebert/aoc/days/Day05.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day import kotlin.math.max import kotlin.math.min class Day05(input: String? = null) : Day(5, "If You Give A Seed A Fertilizer", input) { private val SEEDS_PREFIX = "seeds:" override fun partOne(): Long = with(inputList.iterator()) { var value = next().removePrefix(SEEDS_PREFIX).split(" ").mapNotNull { it.toLongOrNull() }.min() for (line in this) { if (line.isBlank() || line.first().isLetter()) continue val (dstStart, srcStart, length) = line.split(" ").map { it.toLong() } if (value in srcStart..<srcStart + length) { value = dstStart + value - srcStart jumpToNextMapping() } } return value } private fun Iterator<String>.jumpToNextMapping() { while (hasNext()) { val line = next() if (line.isNotBlank() && line.first().isLetter()) break } } override fun partTwo(): Long = with(inputList.iterator()) { var unprocessed = next().removePrefix(SEEDS_PREFIX).split(" ") .mapNotNull { it.toLongOrNull() } .windowed(2, 2) .map { (a, b) -> a..<a + b } var mapped = mutableListOf<LongRange>() for (line in this) { if (line.isBlank()) continue if (line.first().isLetter()) { unprocessed += mapped mapped = mutableListOf() continue } val (dstStart, srcStart, length) = line.split(" ").map { it.toLong() } unprocessed = buildList { unprocessed.forEach { range -> val iMin = max(range.first, srcStart) val iMax = min(range.last, srcStart + length - 1) val intersection = dstStart + iMin - srcStart..dstStart + iMax - srcStart if (!intersection.isEmpty()) { when { iMin > range.first -> add(range.first..<iMin) iMax < range.last -> add(iMax + 1..<range.last) } mapped.add(intersection) } else { add(range) } } } } return (unprocessed + mapped).map { it.first }.min() } }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
2,418
advent-of-code-2023
MIT License
2022/Day18.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { data class Point3( val x: Int, val y: Int, val z: Int, ) { fun sides() = listOf( Point3(x+1, y, z), Point3(x-1, y, z), Point3(x, y+1, z), Point3(x, y-1, z), Point3(x, y, z+1), Point3(x, y, z-1), ) } val input = readInput("Day18").map { line -> line.split(",").map { it.toInt() }.let { Point3(it[0], it[1], it[2]) } }.toSet() var res1 = 0 for (p0 in input) { for (p1 in p0.sides()) { if (!input.contains(p1)) res1++ } } println(res1) val queue = ArrayDeque(listOf(Point3(0,0,0))) val visited = HashSet<Point3>() var res2 = 0 while (queue.isNotEmpty() && queue.size < 200_000) { val p1 = queue.removeFirst() for (p2 in p1.sides()) { if (visited.contains(p2)) continue if (input.contains(p2)) { res2 ++ continue } visited.add(p2) queue.addLast(p2) } } println(res2) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,086
advent-of-code-kotlin
Apache License 2.0
src/array/LeetCode283.kt
Alex-Linrk
180,918,573
false
null
package array /** * 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/move-zeroes 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ class LeetCode283 { fun moveZeroes(nums: IntArray): Unit { if (nums.isEmpty()) return val index = nums.lastIndex var count = 0 for (last in index downTo 0) { if (nums[last] != 0) continue for (swip in last until index - count) { nums[swip] = nums[swip + 1] } nums[nums.lastIndex - count] = 0 count++ } println(nums.toList()) } } fun main() { LeetCode283().moveZeroes(nums = intArrayOf(0, 1, 0, 3, 12)) LeetCode283().moveZeroes(nums = intArrayOf(0, 1,6,7,0,5,6, 0, 3, 12)) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,104
LeetCode
Apache License 2.0
src/Day18/day19.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day18 import readInput import java.util.Objects import kotlin.math.* class Coordinate(var x: Int, var y: Int, var z: Int) { override fun equals(other: Any?) = (other is Coordinate) && x == other.x && y == other.y && z == other.z override fun hashCode(): Int { return Objects.hash(x, y, z) } operator fun plus(coordinate: Coordinate): Coordinate { return Coordinate(x + coordinate.x, y + coordinate.y, z + coordinate.z) } } abstract class Block(var coordinate: Coordinate) { enum class Type { CUBE, OUTSIDE_AIR, INSIDE_AIR, UNKNOWN } abstract var type: Type } class OtherBlock(coordinate: Coordinate, override var type: Type): Block(coordinate) class Cube(coordinate: Coordinate): Block(coordinate) { var numSidesExposed = 6 fun calculateCubeAdded(otherCube: Cube) { if(otherCube.coordinate.x == coordinate.x && otherCube.coordinate.y == coordinate.y) { if (otherCube.coordinate.z == coordinate.z - 1) { numSidesExposed-- } else if (otherCube.coordinate.z == coordinate.z + 1) { numSidesExposed-- } } else if(otherCube.coordinate.x == coordinate.x && otherCube.coordinate.z == coordinate.z) { if (otherCube.coordinate.y == coordinate.y - 1) { numSidesExposed-- } else if (otherCube.coordinate.y == coordinate.y + 1) { numSidesExposed-- } } else if(otherCube.coordinate.y == coordinate.y && otherCube.coordinate.z == coordinate.z) { if (otherCube.coordinate.x == coordinate.x - 1) { numSidesExposed-- } else if (otherCube.coordinate.x == coordinate.x + 1) { numSidesExposed-- } } } override var type = Type.CUBE } class Lava() { var cubes = mutableListOf<Cube>() var coordinate_block = hashMapOf<Coordinate, Block>() var additionCoordinates = arrayOf(Coordinate(-1, 0, 0), Coordinate(1, 0, 0), Coordinate(0, -1, 0), Coordinate(0, 1, 0), Coordinate(0, 0, -1), Coordinate(0, 0, 1)) fun addCube(newCube: Cube) { for (cube in cubes) { cube.calculateCubeAdded(newCube) newCube.calculateCubeAdded(cube) } cubes.add(newCube) } fun processInput(input: List<String>) { for(x in 1 until 20) { for (y in 1 until 20) { for (z in 1 until 20) { val coordinate = Coordinate(x, y, z) coordinate_block[coordinate] = OtherBlock(coordinate, Block.Type.UNKNOWN) } } } for (row in input) { val rowSplit = row.split(",").map { it.toInt() } val coordinate = Coordinate(rowSplit[0], rowSplit[1], rowSplit[2]) val newCube = Cube(coordinate) coordinate_block[coordinate] = newCube addCube(newCube) } } fun identifyUnknownBlocks() { var blocksRemaining = coordinate_block.filter { it.value.type == Block.Type.UNKNOWN } while(blocksRemaining.isNotEmpty()) { var blockToIdentify = blocksRemaining.entries.first() identifyBlock(blockToIdentify.toPair()) blocksRemaining = coordinate_block.filter { it.value.type == Block.Type.UNKNOWN } } } fun identifyBlock(coordinate_block: Pair<Coordinate, Block>) { val searchedBlocks = hashMapOf<Coordinate, Block>(coordinate_block.first to coordinate_block.second) var result = identifyBlockRecursive(coordinate_block.second, searchedBlocks) for (block in searchedBlocks.values) { block.type = result } } fun identifyBlockRecursive(block: Block, searchedBlocks: HashMap<Coordinate, Block>): Block.Type { for (addedCoordinate in additionCoordinates) { val coordinate = block.coordinate + addedCoordinate if (!searchedBlocks.contains(coordinate)) { //this means the block is at the edge of the 20x20x20 cube, so it is air if (coordinate.x == 0 || coordinate.x == 20 || coordinate.y == 0 || coordinate.y == 20 || coordinate.z == 0 || coordinate.z == 20) { return Block.Type.OUTSIDE_AIR } val blockToSearch = coordinate_block[coordinate]!! when (blockToSearch.type) { Block.Type.CUBE -> continue Block.Type.OUTSIDE_AIR -> return Block.Type.OUTSIDE_AIR else -> {} } //is this block is unknown, identify it searchedBlocks[coordinate] = blockToSearch val blockType = identifyBlockRecursive(blockToSearch, searchedBlocks) when (blockType) { Block.Type.CUBE -> continue Block.Type.OUTSIDE_AIR -> return Block.Type.OUTSIDE_AIR else -> {} } } } return Block.Type.INSIDE_AIR } fun fillInInsideAir() { // for (z in 1..19) { // for(y in 1..19) { // for (x in 1..19) { // val coordinate = Coordinate(x, y, z) // when(coordinate_block[coordinate]!!.type) { // Block.Type.INSIDE_AIR -> print("O") // Block.Type.CUBE -> print("X") // Block.Type.OUTSIDE_AIR -> print(" ") // else -> {} // } // } // println() // } // println("---------------------") // } val blocksToFill = coordinate_block.filter { it.value.type == Block.Type.INSIDE_AIR } for (block in blocksToFill) { addCube(Cube(block.key)) } } } fun main() { fun part1(input: List<String>): Int { var lava = Lava() lava.processInput(input) return lava.cubes.sumOf { it.numSidesExposed } } fun part2(input: List<String>): Int { var lava = Lava() lava.processInput(input) lava.identifyUnknownBlocks() lava.fillInInsideAir() println(lava.coordinate_block.filter { it.value.type == Block.Type.OUTSIDE_AIR }.count()) return lava.cubes.sumOf { it.numSidesExposed } } // val testInput = readInput("Day18","Day18_test") // println(part1(testInput)) // check(part1(testInput) == 64) // println(part2(testInput)) // check(part2(testInput) == 58) val input = readInput("Day18","Day18") // println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
6,759
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/consuli/aoc/year2022/days/Day03.kt
ulischulte
572,773,554
false
{"Kotlin": 40404}
package de.consuli.aoc.year2022.days import de.consuli.aoc.common.Day class Day03 : Day(3, 2022) { override fun partOne(testInput: Boolean): Any { return getInput(testInput).sumOf { getPriorityForItemInBothCompartments(it) } } override fun partTwo(testInput: Boolean): Any { return getInput(testInput).windowed(3, 3).sumOf { rucksacks -> val commonItem = rucksacks[0].find { it in rucksacks[1] && it in rucksacks[2] } ?: ' ' getPriority(commonItem) } } private fun getPriorityForItemInBothCompartments(line: String): Int { val itemsInCompartment = line.length / 2 val itemsFirstCompartment = line.substring(0, itemsInCompartment) val itemsSecondCompartment = line.substring(itemsInCompartment, line.length) return getPriority(itemsFirstCompartment.find { it in itemsSecondCompartment } ?: ' ') } private fun getPriority(item: Char): Int { return if (item in 'a'..'z') item - 'a' + 1 else item - 'A' + 27 } }
0
Kotlin
0
2
21e92b96b7912ad35ecb2a5f2890582674a0dd6a
1,054
advent-of-code
Apache License 2.0
src/day6/Day06.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day6 import readInput private fun calculate(input: String, uniqueCharCount: Int): Int { val cache = hashMapOf<Char, Int>() for((index, item) in input.withIndex()) { if(cache.containsKey(item).not()) { cache.put(item, index) } else { val currentIndex = cache[item]!! + 1 val temp = HashMap(cache) for((item, index) in temp) { if(index < currentIndex) cache.remove(item) } cache[item] = index } if(cache.size == uniqueCharCount) return index + 1 } return - 1 } private fun part1(input: List<String>): Int { return calculate(input[0], 4) } private fun part2(input: List<String>): Int { return calculate(input[0], 14) } fun main() { val input = readInput("day6/input") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
881
aoc-2022
Apache License 2.0
src/array/LeetCode131.kt
Alex-Linrk
180,918,573
false
null
package array import kotlin.math.max /** * 分割回文串 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 返回 s 所有可能的分割方案。 示例: 输入: "aab" 输出: [ ["aa","b"], ["a","a","b"] ] */ class Solution131 { fun newPartition(s: String): List<List<String>> { var start = 1 var newList = mutableListOf<List<String>>() if (start == s.length) return mutableListOf(listOf(s)) while (start < s.length) { val begin = s.subSequence(0, start).toString() if (isSummery(begin)) { val end = s.subSequence(start, s.length).toString() val result = newPartition(end) result.forEach { item -> newList.add(listOf(begin, *item.toTypedArray())) } } start++ } if (isSummery(s)) { newList.add(listOf(s)) } return newList } fun partition(s: String): List<List<String>> { var res = spliteMoreOne(s) if (s.length > 1) res.add(listOf(s)) var newResult = mutableListOf<List<String>>() loop@ for (list in res) { for (str in list) { if (isSummery(str).not()) continue@loop } newResult.add(list) } return newResult } fun spliteAllByOne(s: String): List<List<String>> { if (s.isEmpty()) return emptyList() if (s.length == 1) return mutableListOf(listOf(s)) val result = mutableListOf<List<String>>() var start = 1 while (start < s.length) { val begin = s.subSequence(0, start).toString() val end = s.substring(start++, s.length) result.add(listOf(begin, end)) } return result } fun isSummery(str: String): Boolean { if (str.isEmpty() || str.length == 1) return true var start = 0 var end = str.lastIndex while (start <= end) { if (str[start++] != str[end--]) return false } return true } fun spliteMoreOne(s: String): MutableList<List<String>> { var maxSplit = s.length - 1 var temp = spliteAllByOne(s) var result = mutableListOf<List<String>>() result.addAll(temp) while (maxSplit > 1) { val newTemp = mutableListOf<List<String>>() temp.forEach { it -> if (it[it.lastIndex].length > 1) { val res = spliteAllByOne(it[it.lastIndex]) res.forEach { newResult -> val newList = mutableListOf<String>() newList.addAll(it.subList(0, it.lastIndex)) newList.addAll(newResult) newTemp.add(newList) } } } result.addAll(newTemp) temp = newTemp maxSplit-- } return result } } fun main() { val start = System.currentTimeMillis() println(Solution131().newPartition("amanaplanacanalpanama")) println(System.currentTimeMillis() - start) // println(Solution131().newPartition("amanaplanacanalpanama")) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
3,276
LeetCode
Apache License 2.0
src/main/Day03.kt
lifeofchrome
574,709,665
false
{"Kotlin": 19233}
package main import readInput fun main() { val input = readInput("Day03") val day3 = Day03(input) print("Part 1: ${day3.part1()}\n") print("Part 2: ${day3.part2()}") } class Day03(private val input: List<String>) { private fun itemToPriority(item: Char): Int { return when(item.code) { in 97..122 -> item.code - 96 in 65..90 -> (item.code - 64) + 26 else -> error("Invalid item: $item") } } fun part1(): Int { var prioritySum = 0 for(sack in input) { val left = sack.substring(0, sack.length / 2) val right = sack.substring(sack.length / 2) for(item in left) { if(item in right) { prioritySum += itemToPriority(item) break } } } return prioritySum } fun part2(): Int { var prioritySum = 0 for(group in input.chunked(3)) { for(item in group[0]) { if(item in group[1] && item in group[2]) { prioritySum += itemToPriority(item) break } } } return prioritySum } }
0
Kotlin
0
0
6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e
1,237
aoc2022
Apache License 2.0
src/main/java/com/booknara/problem/array/CheckIfTwoStringArraysAreEquivalentKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.array /** * 1662. Check If Two String Arrays are Equivalent (Easy) * https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/ */ class CheckIfTwoStringArraysAreEquivalentKt { // T:O(max(len(n), len(m)), S:O(1) fun arrayStringsAreEqual(word1: Array<String>, word2: Array<String>): Boolean { // input check, word1 >= 1, word2 >= 1 var strIdx1 = 0 var strIdx2 = 0 var charIdx1 = 0 var charIdx2 = 0 while (strIdx1 < word1.size && strIdx2 < word2.size) { // different if (word1[strIdx1][charIdx1] != word2[strIdx2][charIdx2]) return false // word1 if (charIdx1 == word1[strIdx1].length - 1) { charIdx1 = 0 strIdx1++ } else { charIdx1++ } // word2 if (charIdx2 == word2[strIdx2].length - 1) { charIdx2 = 0 strIdx2++ } else { charIdx2++ } } return strIdx1 == word1.size && strIdx2 == word2.size } // T:O(max(num(n), num(m))), S:O(max(len(n), len(m)) fun arrayStringsAreEqual1(word1: Array<String>, word2: Array<String>): Boolean { // input check, word1 >= 1, word2 >= 1 val builder1 = StringBuilder() for (i in 0 until word1.size) { builder1.append(word1[i]) } val builder2 = StringBuilder() for (i in 0 until word2.size) { builder2.append(word2[i]) } return builder1.toString() == builder2.toString() } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,450
playground
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem90/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem90 /** * LeetCode page: [90. Subsets II](https://leetcode.com/problems/subsets-ii/); */ class Solution { /* Complexity: * Time O(N * 2^N) and Space O(N * 2^N) where N is the size of nums; */ fun subsetsWithDup(nums: IntArray): List<List<Int>> { val countPerNum = getCountPerNum(nums) val subsets = mutableListOf(emptyList<Int>()) for (num in countPerNum.keys) { val countOfNum = checkNotNull(countPerNum[num]) updateSubsetsByNum(subsets, num, countOfNum) } return subsets } private fun getCountPerNum(nums: IntArray): Map<Int, Int> { val counts = hashMapOf<Int, Int>() for (num in nums) { counts[num] = counts.getOrDefault(num, 0) + 1 } return counts } private fun updateSubsetsByNum(subsets: MutableList<List<Int>>, num: Int, countOfNum: Int) { repeat(subsets.size) { index -> for (count in 1..countOfNum) { val newSubset = subsets[index].toMutableList() repeat(count) { newSubset.add(num) } subsets.add(newSubset) } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,203
hj-leetcode-kotlin
Apache License 2.0
src/Day09.kt
luiscobo
574,302,765
false
{"Kotlin": 19047}
import javax.swing.plaf.metal.MetalTabbedPaneUI import kotlin.math.abs import kotlin.math.sign typealias Position = Pair<Int, Int> // Para saber si las posiciones están cercanas fun touching(H: Position, T: Position): Boolean { return abs(H.first - T.first) <= 1 && abs(H.second - T.second) <= 1 } fun signo(x: Int) = when { x < 0 -> -1 x == 0 -> 0 else -> 1 } fun moveTail(H: Position, T: Position): Position { var (xh, yh) = H var (xt, yt) = T return (xt + signo(xh - xt)) to (yt + signo(yh - yt)) } fun getComponents(line: String): Pair<Char, Int> { return line[0] to line.substringAfter(' ').toInt() } fun move(H: Position, direction: Char): Position { return (H.first + when (direction) { 'R' -> 1 'L' -> -1 else -> 0 }) to (H.second + when (direction) { 'U' -> 1 'D' -> -1 else -> 0 }) } fun moveFirst(knots: MutableList<Position>, direction: Char) { knots[0] = move(knots[0], direction) } fun moveRest(knots: MutableList<Position>) { for (i in 1 .. 9) { if (!touching(knots[i-1], knots[i])) { knots[i] = moveTail(knots[i - 1], knots[i]) } else { break } } } fun clone(position: Position): Position = position.first to position.second fun main() { fun part1(input: List<String>): Int { var H: Position = 0 to 0 var T: Position = 0 to 0 val positions: MutableSet<Position> = mutableSetOf(clone(T)) for (line in input) { var (dir, args) = getComponents(line) repeat (args) { H = move(H, dir) if (!touching(H, T)) { T = moveTail(H, T) positions.add(clone(T)) } } } return positions.size } fun part2(input: List<String>): Int { val positions: MutableSet<Position> = mutableSetOf(0 to 0) val knots: MutableList<Position> = mutableListOf() for (i in 0 until 10) { knots.add(Pair(0, 0)) } for (line in input) { var (dir, args) = getComponents(line) repeat(args) { moveFirst(knots, dir) moveRest(knots) positions.add(clone(knots.last())) } } return positions.size } //----------------------------------------------------- val input = readInput("day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c764e5abca0ea40bca0b434bdf1ee2ded6458087
2,564
advent-of-code-2022
Apache License 2.0
src/test/kotlin/biz/koziolek/adventofcode/year2023/day02/Day2Test.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day02 import biz.koziolek.adventofcode.findInput import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test @Tag("2023") internal class Day2Test { private val sampleInput = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """.trimIndent().split("\n") @Test fun testParse() { val games = parseGames(sampleInput) assertEquals( listOf( Game(id = 1, sets = listOf( CubeSet(blue = 3, red = 4), CubeSet(red = 1, green = 2, blue = 6), CubeSet(green = 2), )), Game(id = 2, sets = listOf( CubeSet(blue = 1, green = 2), CubeSet(green = 3, blue = 4, red = 1), CubeSet(green = 1, blue = 1), )), Game(id = 3, sets = listOf( CubeSet(green = 8, blue = 6, red = 20), CubeSet(blue = 5, red = 4, green = 13), CubeSet(green = 5, red = 1), )), Game(id = 4, sets = listOf( CubeSet(green = 1, red = 3, blue = 6), CubeSet(green = 3, red = 6), CubeSet(green = 3, blue = 15, red = 14), )), Game(id = 5, sets = listOf( CubeSet(red = 6, blue = 1, green = 3), CubeSet(blue = 2, red = 1, green = 2), )), ), games ) } @Test fun testFindPossibleGames() { val games = parseGames(sampleInput) val possible = findPossibleGames(games, FULL_SET) assertEquals(listOf(1, 2, 5), possible.map { it.id }) assertEquals(8, sumGameIds(possible)) } @Test @Tag("answer") fun testAnswer1() { val input = findInput(object {}).bufferedReader().readLines() val games = parseGames(input) val possible = findPossibleGames(games, FULL_SET) assertEquals(2076, sumGameIds(possible)) } @Test fun testFindMinimSet() { val games = parseGames(sampleInput) assertEquals(CubeSet(red = 4, green = 2, blue = 6), games[0].minimumSet) assertEquals(CubeSet(red = 1, green = 3, blue = 4), games[1].minimumSet) assertEquals(CubeSet(red = 20, green = 13, blue = 6), games[2].minimumSet) assertEquals(CubeSet(red = 14, green = 3, blue = 15), games[3].minimumSet) assertEquals(CubeSet(red = 6, green = 3, blue = 2), games[4].minimumSet) assertTrue(games[0].isPossible(games[0].minimumSet)) assertTrue(games[1].isPossible(games[1].minimumSet)) assertTrue(games[2].isPossible(games[2].minimumSet)) assertTrue(games[3].isPossible(games[3].minimumSet)) assertTrue(games[4].isPossible(games[4].minimumSet)) } @Test fun testCubeSetPower() { val games = parseGames(sampleInput) assertEquals(48, games[0].minimumSet.power) assertEquals(12, games[1].minimumSet.power) assertEquals(1560, games[2].minimumSet.power) assertEquals(630, games[3].minimumSet.power) assertEquals(36, games[4].minimumSet.power) } @Test fun testSumPowersOfMinimumSets() { val games = parseGames(sampleInput) assertEquals(2286, sumPowersOfMinimumSets(games)) } @Test @Tag("answer") fun testAnswer2() { val input = findInput(object {}).bufferedReader().readLines() val games = parseGames(input) assertEquals(70950, sumPowersOfMinimumSets(games)) } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
4,026
advent-of-code
MIT License
src/2020/Day9_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File val input = ArrayList<Long>() File("input/2020/day9").forEachLine { input.add(it.toLong()) } val window = 25 input.forEachIndexed { i, current -> if (i >= window && !check(input.subList(i - window, i), current)) crack(current) } fun check(subList: List<Long>, current: Long): Boolean { val sums = HashSet<Long>() subList.forEach { a -> subList.forEach { b -> sums.add(a+b) } } return sums.contains(current) } fun crack(magic: Long) = input.subList(0,input.indexOf(magic)) .apply { forEachIndexed { start, _ -> var index = start var sum = 0L while (index < size && sum < magic) { sum += get(index) if (sum == magic) break else index++ } if (sum == magic) println("${(subList(start, index).min() ?: 0)+(subList(start, index).max() ?: 0)}") } }
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
912
adventofcode
MIT License
src/main/kotlin/kr/co/programmers/P42579.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers class P42579 { fun solution(genres: Array<String>, plays: IntArray): IntArray { // 해시 구조로 저장 // 장르 : [<인덱스, 재생 횟수>, ..., ...] val hash = mutableMapOf<String, MutableList<IntArray>>().apply { for (i in plays.indices) { val genre = genres[i] val play = plays[i] val data = intArrayOf(i, play) this[genre] = (this[genre] ?: mutableListOf()).apply { add(data) } } } // 장르의 총 재생 횟수로 내림차순 정렬 val sorted = hash.toList() .sortedWith(compareByDescending { it -> it.second.sumBy { it[1] } }) // 장르 내에서 재생 횟수로 내림차순 정렬 sorted.forEach { pair -> pair.second.sortByDescending { it[1] } } // 장르별 두 개씩 추출 var answer = mutableListOf<Int>() for (pair in sorted) { answer.addAll(pair.second.take(2).map { it[0] }) } return answer.toIntArray() } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,095
algorithm
MIT License
year2019/day20/maze/src/main/kotlin/com/curtislb/adventofcode/year2019/day20/maze/Maze.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2019.day20.maze import com.curtislb.adventofcode.common.collection.getOrNull import com.curtislb.adventofcode.common.grid.Grid import com.curtislb.adventofcode.common.geometry.Point import com.curtislb.adventofcode.common.graph.UnweightedGraph import com.curtislb.adventofcode.common.grid.forEachPointValue import com.curtislb.adventofcode.common.grid.mutableGridOf import com.curtislb.adventofcode.common.io.mapLines import com.curtislb.adventofcode.year2019.day20.maze.space.EmptySpace import com.curtislb.adventofcode.year2019.day20.maze.space.LabeledSpace import com.curtislb.adventofcode.year2019.day20.maze.space.Space import java.io.File /** * A maze containing labeled spaces that lead to other locations within or to additional recursive * copies of the maze. */ class Maze(private val grid: Grid<Space>, private val isRecursive: Boolean = false) { /** * A map from each label to the positions of spaces in the maze grid with that label. */ private val labeledSpaces: Map<String, List<Point>> = findLabeledSpaces(grid) /** * A graph with edges from each [Location] in the maze to its adjacent locations. */ private val locationGraph = object : UnweightedGraph<Location>() { override fun getNeighbors(node: Location): Iterable<Location> { val neighbors = mutableListOf<Location>() for (neighbor in node.point.cardinalNeighbors()) { if (grid.getOrNull(neighbor)?.isOccupiable == true) { neighbors.add(Location(neighbor, node.depth)) } } neighbors.addAll(getPortalLocations(node, isRecursive)) return neighbors } } /** * Returns the shortest distance through the maze from the space labeled [entranceLabel] to one * labeled [exitLabel]. * * If the maze is non-recursive, labeled spaces are treated as portals, which are adjacent to * all other spaces in the maze that share the same label. * * If the maze is recursive, labeled spaces are treated as entrances to or exits from recursive * copies of the maze. Labeled spaces in the interior (not outer edges) of the maze are adjacent * to other similarly labeled spaces in a copy of the maze one level deeper, and vice versa. In * this case, the function returns the shortest distance between the spaces labeled * [entranceLabel] and [exitLabel] within the original, outermost copy of the maze. */ fun findShortestDistance(entranceLabel: String, exitLabel: String): Long? { val entranceSpace = labeledSpaces[entranceLabel]?.first() ?: return null val source = Location(entranceSpace) return locationGraph.bfsDistance(source) { isLabeledExit(it, exitLabel) } } /** * Returns `true` if the given [location] is an exit with the given [exitLabel]. */ private fun isLabeledExit(location: Location, exitLabel: String): Boolean { if (location.depth != 0) { return false } val space = grid.getOrNull(location.point) return space is LabeledSpace && space.label == exitLabel } /** * Returns all locations within the maze that are adjacent to [location]. * * The parameter [isRecursive] indicates whether the maze is recursive, and causes the points * and depths of adjacent locations to be determined accordingly. * * @see [findShortestDistance] */ private fun getPortalLocations(location: Location, isRecursive: Boolean): List<Location> = if (isRecursive) { getRecursivePortalLocations(location) } else { getNonRecursivePortalLocations(location) } /** * Returns all locations within a recursive maze that are adjacent to [location]. * * @see [findShortestDistance] * @see [getPortalLocations] */ private fun getRecursivePortalLocations(location: Location): List<Location> { val space = grid.getOrNull(location.point) val isOuterPortal = isOuterPoint(location.point) return if (space !is LabeledSpace || (isOuterPortal && location.depth == 0)) { emptyList() } else { val newPoints = labeledSpaces[space.label] ?.filter { it != location.point } ?: emptyList() val newDepth = if (isOuterPortal) location.depth - 1 else location.depth + 1 newPoints.map { Location(it, newDepth) } } } /** * Returns all locations within a non-recursive maze that are adjacent to [location]. * * @see [findShortestDistance] * @see [getPortalLocations] */ private fun getNonRecursivePortalLocations(location: Location): List<Location> { return when (val space = grid.getOrNull(location.point)) { is LabeledSpace -> { val newPoints = labeledSpaces[space.label]?.filter { it != location.point } ?: emptyList() newPoints.map { Location(it) } } else -> emptyList() } } /** * Returns `true` if a given [point] in the maze is on an outer edge, or `false` otherwise. */ private fun isOuterPoint(point: Point): Boolean { val row = point.matrixRow val col = point.matrixCol return row == 0 || col == 0 || row == grid.lastRowIndex || col == grid.lastColumnIndex } companion object { /** * Returns a [Maze] with the layout read from the given [file]. */ fun fromFile(file: File, isRecursive: Boolean = false): Maze { val charRows = file.mapLines { it.trimEnd().toMutableList() } val spaceLabels = processLabels(charRows) val grid = createSpaceGrid(charRows, spaceLabels) return Maze(grid, isRecursive) } /** * Processes the given [charRows] (representing a maze) by removing all label characters, * and returns a map from each labeled point in the grid to its associated label. */ private fun processLabels(charRows: List<MutableList<Char>>): Map<Point, String> { val spaceLabels = mutableMapOf<Point, String>() // Search the grid for any characters that may be part of a label. charRows.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, char -> if (char.isLetter()) { var label: String? = null var position: Point? = null if (charRows.getOrNull(rowIndex + 1, colIndex)?.isLetter() == true) { // Read this vertical label from top to bottom. label = "${charRows[rowIndex][colIndex]}${charRows[rowIndex + 1][colIndex]}" // Check above and below the label for a non-empty space. val charAbove = charRows.getOrNull(rowIndex - 1, colIndex) position = if (charAbove != null && charAbove != EmptySpace.symbol) { Point.fromMatrixCoordinates(rowIndex - 1, colIndex) } else { Point.fromMatrixCoordinates(rowIndex + 2, colIndex) } // Remove the label characters from the grid. charRows[rowIndex][colIndex] = EmptySpace.symbol charRows[rowIndex + 1][colIndex] = EmptySpace.symbol } else if (charRows.getOrNull(rowIndex, colIndex + 1)?.isLetter() == true) { // Read this horizontal label from left to right. label = "${charRows[rowIndex][colIndex]}${charRows[rowIndex][colIndex + 1]}" // Check left and right of the label for a non-empty space val charLeft = charRows.getOrNull(rowIndex, colIndex - 1) position = if (charLeft != null && charLeft != EmptySpace.symbol) { Point.fromMatrixCoordinates(rowIndex, colIndex - 1) } else { Point.fromMatrixCoordinates(rowIndex, colIndex + 2) } // Remove the label characters from the grid. charRows[rowIndex][colIndex] = EmptySpace.symbol charRows[rowIndex][colIndex + 1] = EmptySpace.symbol } // Add a mapping for this label. if (label != null && position != null) { spaceLabels[position] = label } } } } return spaceLabels } /** * Returns a grid of spaces within a maze from the given [charRows] containing space symbols * and the map [spaceLabels], which maps points in [charRows] to their associated labels. * * The resulting grid is made as compact as possible, with empty spaces on the exterior of * the maze excluded. */ private fun createSpaceGrid( charRows: List<List<Char>>, spaceLabels: Map<Point, String> ): Grid<Space> { val fullGrid = charRows.mapIndexed { rowIndex, row -> row.mapIndexed { colIndex, char -> val space = Space.from(char) val label = spaceLabels[Point.fromMatrixCoordinates(rowIndex, colIndex)] if (label != null) LabeledSpace(space, label) else space } } return mutableGridOf<Space>().apply { for (rowIndex in 2..(fullGrid.lastIndex - 2)) { val fullRow = fullGrid[rowIndex] val compactRow = fullRow.subList(2, fullRow.size).dropLastWhile { it == EmptySpace } addRow(compactRow) } } } /** * Returns a map from each unique label in [grid] to the positions of all corresponding * labeled spaces. */ private fun findLabeledSpaces(grid: Grid<Space>): Map<String, List<Point>> { return mutableMapOf<String, MutableList<Point>>().apply { grid.forEachPointValue { point, space -> if (space is LabeledSpace) { getOrPut(space.label) { mutableListOf() }.add(point) } } } } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
10,870
AdventOfCode
MIT License
src/main/kotlin/adventofcode2020/Day16TicketTranslation.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2020 class Day17TickeTranslation data class CodeRange(val name: String, val firstRange: IntRange, val secondRange: IntRange) { fun isValidNumber(number: Int) = number in firstRange || number in secondRange } class TicketReader { val validRanges = mutableListOf<CodeRange>() val validTickets = mutableListOf<List<Int>>() // Input examples: // arrival track: 26-681 or 703-953 // class: 49-293 or 318-956 fun readRangeInput(input: String) { val rangeName = input.substringBefore(":") val firstInputRange = input.substringAfter(": ").substringBefore(" or").split("-") val secondInputRange = input.substringAfter("or ").split("-") val firstRange = IntRange(firstInputRange[0].toInt(), firstInputRange[1].toInt()) val secondRange = IntRange(secondInputRange[0].toInt(), secondInputRange[1].toInt()) validRanges.add(CodeRange(rangeName, firstRange, secondRange)) } fun validateNumber(number: Int): Boolean = (validRanges.any { range -> range.isValidNumber(number) }) fun validateTicket(ticket: String): Boolean { val numbers = ticket.split(",").map(String::toInt) return numbers.all { number -> validRanges.any { range -> range.isValidNumber(number) } } } fun readValidTicket(ticket: String) { validTickets.add(ticket.split(",").map(String::toInt)) } fun determineValidRangeAtIndex(): MutableList<Pair<Int, String>> { val numbersToCheck = mutableListOf<Int>() var rangeMap = mutableMapOf<Int, MutableList<String>>() (0..19).forEach { rangeMap.put(it, mutableListOf()) } for (index in 0..19) { for (ticket in validTickets) { numbersToCheck.add(ticket[index]) } for (range in validRanges) { if (numbersToCheck.all { number -> range.isValidNumber(number) }) rangeMap.get(index)?.add(range.name) } numbersToCheck.clear() } val rangeIndexes = mutableListOf<Pair<Int, String>>() while (rangeMap.isNotEmpty()) { var nextRange = "" rangeMap.forEach { (index, list) -> if (list.size == 1) { rangeIndexes.add(index to list.first()) nextRange = list.first() } } rangeMap.values.forEach {it.removeIf { name -> name == nextRange } } rangeMap = rangeMap.filterNot { entry -> entry.value.isEmpty() }.toMutableMap() } return rangeIndexes } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,538
kotlin-coding-challenges
MIT License
stepik/sportprogramming/UnlimitedAudienceApplicationsGreedyAlgorithm.kt
grine4ka
183,575,046
false
{"Kotlin": 98723, "Java": 28857, "C++": 4529}
package stepik.sportprogramming import java.io.File fun main() { val rooms = IntArray(33000) { 0 } val applications = readFromFile() println("Max of applications is ${count(rooms, applications)}") } private fun readFromFile(): MutableList<AudienceApplication> { val applications = mutableListOf<AudienceApplication>() File("stepik/sportprogramming/request2unlim.in").forEachLine { applications.add(readApplication(it)) } return applications } private fun readFromInput(): MutableList<AudienceApplication> { val applications = mutableListOf<AudienceApplication>() val n = readInt() repeat(n) { applications.add(readApplication(readLine()!!)) } return applications } private fun count(rooms: IntArray, applications: List<AudienceApplication>): Int { for (application in applications) { for (i in application.left until application.right) { rooms[i]++ } } return rooms.max()!! } private class AudienceApplication(val left: Int, val right: Int) private fun readInt() = readLine()!!.trim().toInt() private fun readApplication(string: String): AudienceApplication { val ints = string.split(" ").map { it.trim().toInt() }.toIntArray() return AudienceApplication(ints[0], ints[1]) } private fun readInts() = readLine()!!.split(" ").map(String::toInt).toIntArray()
0
Kotlin
0
0
c967e89058772ee2322cb05fb0d892bd39047f47
1,377
samokatas
MIT License
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p01/Leet198.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p01 import com.artemkaxboy.leetcode.LeetUtils.toIntArray import kotlin.system.measureNanoTime class Leet198 { class MySolution { private val knownResults = HashMap<Int, Pair<Int, Int>>() // nanotime = 82218, 36926, 47676, 2171884, 21085261 fun rob(nums: IntArray): Int { return maxOf(robNext(nums), robNext(nums, 0, 1)) } private fun robNext(nums: IntArray, sum: Int = 0, allowedIndex: Int = 0): Int { if (allowedIndex >= nums.size) return sum knownResults[allowedIndex]?.takeIf { it.first >= sum }?.let { return it.second } if (allowedIndex == nums.size - 1) { return sum + nums[allowedIndex].also { knownResults[allowedIndex] = sum to it } } return maxOf( robNext(nums, sum + nums[allowedIndex], allowedIndex + 2), robNext(nums, sum + nums[allowedIndex + 1], allowedIndex + 3) ).also { knownResults[allowedIndex] = sum to it } } } /** * This is a method named rob that takes an array of integers as input, and returns a single integer. * The purpose of this method is to solve the "House Robber" problem: given an array of non-negative integers * representing the amount of money of each house, determine the maximum amount of money you can rob tonight * without alerting the police. * * The implementation uses dynamic programming, specifically memoization, to solve the problem efficiently. * It starts with two variables, prev1 and prev2, both initially set to 0. Then, for each element in the input * array, it calculates the maximum amount of money that can be robbed up to that point by choosing between * robbing the current house plus the previous previous house (prev2 + nums[i]), or skipping the current house * and using the maximum value seen so far (prev1). * * To avoid counting duplicates, the previous maximum value is stored in a temporary variable temp, which is * used to update prev2 after prev1 has been updated. The final result is stored in prev1 and returned at the * end of the function. * * Overall, this algorithm achieves a time complexity of O(n), where n is the length of the input array, * and a space complexity of O(1) because the only memory used are the two variables prev1 and prev2. * * * Данный код на Kotlin решает задачу "Грабитель домов". В этой задаче имеется массив неотрицательных чисел, * каждый элемент которого представляет собой количество денег в доме. Требуется определить максимальную сумму * денег, которую можно украсть без привлечения полиции. * * Алгоритм использует метод динамического программирования, а именно мемоизацию, для эффективного решения задачи. * Он начинается со значения двух переменных prev1 и prev2, равных 0. Затем, для каждого элемента входного массива, * вычисляется максимальная возможная сумма денег, которую можно украсть к данному моменту времени, выбрав между * грабежом текущего дома плюс дома, предшествующего предыдущему (prev2 + nums[i]) или пропустив текущий дом и * используя максимальное значение, найденное до этого (prev1). * * Для предотвращения повторов предыдущее максимальное значение хранится во временной переменной temp, которая * используется для обновления значения prev2 после того, как значение prev1 было обновлено. Конечный результат * хранится в prev1 и возвращается в конце функции. * * В целом, данный алгоритм достигает временной сложности O(n), где n - длина входного массива, и пространственной * сложности O(1), потому что единственные переменные, используемые в процессе выполнения, это prev1 и prev2. * * */ class BestSolution { // nanoTime = 55032, 33021, 35335, 705249, 1354351 fun rob(nums: IntArray): Int { var prev1 = 0 var prev2 = 0 for (i in nums.indices) { val temp = prev1 prev1 = Math.max(prev1, prev2 + nums[i]) prev2 = temp } return prev1 } } companion object { @JvmStatic fun main(args: Array<String>) { val testCase1 = Data("[1,90,100,90,1]", 180) val testCase2 = Data("[100,90,100,90,100]", 300) val testCase3 = Data("[100,5,5,100,5,5,100]", 300) val testCase4 = Data( "[226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166,124]", 7102, ) val testCase5 = Data( "[" + "226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166," + "226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166," + "226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166," + "226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166," + "226,174,214,16,218,48,153,131,128,17,157,142,88,43,37,157,43,221,191,68,206,23,225,82,54,118,111,46,80,49,245,63,25,194,72,80,143,55,209,18,55,122,65,66,177,101,63,201,172,130,103,225,142,46,86,185,62,138,212,192,125,77,223,188,99,228,90,25,193,211,84,239,119,234,85,83,123,120,131,203,219,10,82,35,120,180,249,106,37,169,225,54,103,55,166," + "124]", 34846, ) doWork(testCase1) doWork(testCase1) doWork(testCase2) doWork(testCase3) doWork(testCase4) doWork(testCase5) } private fun doWork(data: Data) { // val solution = MySolution() val solution = BestSolution() val result: Any val time = measureNanoTime { result = solution.rob(data.input.toIntArray()) } println("Data: ${data.input}") println("Expected: ${data.expected}") println("Result: $result") println("Time: $time\n") if (data.expected != result) { throw AssertionError("\nExpected: ${data.expected}\nActual: $result") } } } data class Data( val input: String, val expected: Int ) }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
8,859
playground
MIT License
src/Day05.kt
annagergaly
572,917,403
false
{"Kotlin": 6388}
fun main() { fun part1(input: List<String>): String { val stacks = listOf( mutableListOf('V', 'J', 'B', 'D'), mutableListOf('F', 'D', 'R', 'W', 'B', 'V', 'P'), mutableListOf('Q', 'W', 'C', 'D', 'L', 'F', 'G', 'R'), mutableListOf('B', 'D', 'N', 'L', 'M', 'P', 'J', 'W'), mutableListOf('Q', 'S', 'C', 'P', 'B', 'N', 'H'), mutableListOf('G', 'N', 'S', 'B', 'D', 'R'), mutableListOf('H', 'S', 'F', 'Q', 'M', 'P', 'B', 'Z'), mutableListOf('F', 'L', 'W'), mutableListOf('R', 'M', 'F', 'V', 'S') ) input.map { it.removePrefix("move ").split(" from ", " to ").map { it.toInt() }} .map { val move = stacks[it[1]-1].take(it[0]).reversed() repeat(it[0]) {_ -> stacks[it[1]-1].removeAt(0) } stacks[it[2]-1].addAll(0, move) } stacks.map { println(it) } return stacks.map { it.first() }.joinToString("") } fun part2(input: List<String>): String { val stacks = listOf( mutableListOf('V', 'J', 'B', 'D'), mutableListOf('F', 'D', 'R', 'W', 'B', 'V', 'P'), mutableListOf('Q', 'W', 'C', 'D', 'L', 'F', 'G', 'R'), mutableListOf('B', 'D', 'N', 'L', 'M', 'P', 'J', 'W'), mutableListOf('Q', 'S', 'C', 'P', 'B', 'N', 'H'), mutableListOf('G', 'N', 'S', 'B', 'D', 'R'), mutableListOf('H', 'S', 'F', 'Q', 'M', 'P', 'B', 'Z'), mutableListOf('F', 'L', 'W'), mutableListOf('R', 'M', 'F', 'V', 'S') ) stacks.map { println(it) } input.map { it.removePrefix("move ").split(" from ", " to ").map { it.toInt() }} .map { val move = stacks[it[1]-1].take(it[0]) repeat(it[0]) {_ -> stacks[it[1]-1].removeAt(0) } stacks[it[2]-1].addAll(0, move) } return stacks.map { it.first() }.joinToString("") } val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
89b71c93e341ca29ddac40e83f522e5449865b2d
2,111
advent-of-code22
Apache License 2.0
kotlin/numbertheory/MultiplicativeFunction.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package numbertheory import java.util.Arrays // f(a*b) = f(a)*f(b) | gcd(a,b)=1 interface MultiplicativeFunction { fun apply(prime: Long, exponent: Int, power: Long): Long operator fun get(x: Long): Long { var x = x var res: Long = 1 var d: Long = 2 while (d * d <= x) { if (x % d == 0L) { var exp = 0 var power: Long = 1 do { ++exp power *= d x /= d } while (x % d == 0L) res *= apply(d, exp, power) } d++ } if (x != 1L) res *= apply(x, 1, x) return res } fun generateValues(n: Int): LongArray { val divisor = generateDivisors(n) val res = LongArray(n + 1) res[1] = 1 for (i in 2..n) { var j = i var exp = 0 do { j /= divisor[i] ++exp } while (j % divisor[i] == 0) res[i] = res[j] * apply(divisor[i].toLong(), exp, (i / j).toLong()) } return res } companion object { fun generateDivisors(n: Int): IntArray { val divisors: IntArray = IntStream.range(0, n + 1).toArray() var i = 2 while (i * i <= n) { if (divisors[i] == i) { var j = i * i while (j <= n) { divisors[j] = i j += i } } i++ } return divisors } // Usage example fun main(args: Array<String?>?) { System.out.println(1L == MOBIUS[1]) System.out.println(-1L == MOBIUS[2]) System.out.println(Arrays.toString(MOBIUS.generateValues(10))) } val PHI: MultiplicativeFunction = MultiplicativeFunction { p: Long, exp: Int, power: Long -> power - power / p } val MOBIUS: MultiplicativeFunction = MultiplicativeFunction { p: Long, exp: Int, power: Long -> if (exp == 1) -1 else 0 } val DIVISOR_COUNT: MultiplicativeFunction = MultiplicativeFunction { p: Long, exp: Int, power: Long -> exp + 1 } val DIVISOR_SUM: MultiplicativeFunction = MultiplicativeFunction { p: Long, exp: Int, power: Long -> (power * p - 1) / (p - 1) } } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
2,431
codelibrary
The Unlicense
src/main/kotlin/co/csadev/adventOfCode/Searching.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/* * Copyright (c) 2022 by <NAME> */ package co.csadev.adventOfCode import com.sksamuel.scrimage.color.Color import java.util.* /** * Creates a path from an end point going through parent nodes back to the beginning */ fun Map<Point2D, Point2D>.pathThroughList(end: Point2D): List<Point2D> { var cur = end val path = mutableListOf<Point2D>() while (containsKey(cur)) { path.add(cur) cur = this[cur] ?: throw InputMismatchException("Parent not found!") } return path } /** * Maps the shortest path from [start] to [end] * Optionally can use [includeDiagonal] */ fun <T> Map<Point2D, T>.shortestPath( start: Point2D, end: Point2D, includeDiagonal: Boolean = false, visualize: ((current: Point2D, best: List<Point2D>, queue: List<Point2D>) -> Color)? = null, validator: (current: Point2D, next: Point2D) -> Boolean ): List<Point2D>? { val visualization = if (visualize != null) createVisualization() else null val best = mutableMapOf<Point2D, Int>() val tracking = mutableMapOf<Point2D, Point2D>() val queue = LinkedList<Point2D>() best[start] = 0 queue.add(start) while (queue.size > 0) { val cur: Point2D = queue.poll() if (cur == end) { return tracking.pathThroughList(cur).also { visualization?.visualizeFrame( getCurrentState(it, visualize = visualize!!) ) visualization?.finalizeVisualization() } } for (c in (if (includeDiagonal) cur.neighbors else cur.adjacent)) { // skip if outside bounds or if height is more than one above current if (!validator(cur, c)) continue val testPath = best[cur]!! + 1 if (testPath < best.getOrDefault(c, Int.MAX_VALUE)) { best[c] = testPath tracking[c] = cur queue.add(c) } } visualization?.visualizeFrame( getCurrentState( tracking.pathThroughList(cur), queue, visualize!! ) ) } return null }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,171
advent-of-kotlin
Apache License 2.0
src/main/kotlin/io/matrix/MaximalSquare.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.matrix import io.utils.runTests // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3312/ class MaximalSquare { fun execute(input: Array<IntArray>): Int { val visited = mutableSetOf<Pair<Int, Int>>() var result = 0 input.forEachIndexed { index, row -> row.forEachIndexed { col, value -> if (!visited.contains(index to col)) { visited.add(index to col) if (value == 1) { result = maxOf(result, findSize(input, index, col, visited)) } } } } return result } private fun findSize(input: Array<IntArray>, row: Int, col: Int, visited: MutableSet<Pair<Int, Int>>): Int { var result = 1 var offset = 1 loop@ while (true) { val offsetCol = col + offset val offsetRow = row + offset if (offsetCol >= input.first().size || offsetRow >= input.size) { break } for (r in 0..offset) { val currentRow = row + r if (input[currentRow][offsetCol] != 1) { visited.add(currentRow to offsetCol) break@loop } } for (c in 0 until offset) { val currentCol = col + c if (input[offsetRow][currentCol] != 1) { visited.add(offsetRow to currentCol) break@loop } } result = (offset + 1) * (offset + 1) offset++ } return result } } fun main() { runTests(listOf( arrayOf( intArrayOf(1, 0, 1, 0, 0), intArrayOf(1, 0, 1, 1, 1), intArrayOf(1, 1, 1, 1, 1), intArrayOf(1, 0, 0, 1, 0) ) to 4, arrayOf( intArrayOf(1, 1, 1, 0, 0), intArrayOf(1, 1, 1, 1, 1), intArrayOf(1, 1, 1, 1, 1), intArrayOf(1, 0, 1, 1, 1) ) to 9, arrayOf( intArrayOf(1, 1, 1, 1, 0), intArrayOf(1, 1, 1, 1, 1), intArrayOf(1, 1, 1, 1, 1), intArrayOf(1, 1, 1, 1, 1) ) to 16, arrayOf( intArrayOf(1, 1, 1, 1, 0) ) to 1, arrayOf( intArrayOf(1) ) to 1, arrayOf( intArrayOf(0) ) to 0, arrayOf( intArrayOf() ) to 0 )) { (input, value) -> value to MaximalSquare().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,274
coding
MIT License
src/main/kotlin/g2301_2400/s2321_maximum_score_of_spliced_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2321_maximum_score_of_spliced_array // #Hard #Array #Dynamic_Programming #2023_06_30_Time_497_ms_(50.00%)_Space_56.9_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun maximumsSplicedArray(nums1: IntArray, nums2: IntArray): Int { var nums1 = nums1 var nums2 = nums2 var sum1 = 0 var sum2 = 0 val n = nums1.size for (num in nums1) { sum1 += num } for (num in nums2) { sum2 += num } if (sum2 > sum1) { val temp = sum2 sum2 = sum1 sum1 = temp val temparr = nums2 nums2 = nums1 nums1 = temparr } // now sum1>=sum2 // maxEndingHere denotes the maximum sum subarray ending at current index(ie. element at // current index has to be included) // minEndingHere denotes the minimum sum subarray ending at current index var maxEndingHere: Int var minEndingHere: Int var maxSoFar: Int var minSoFar: Int var currEle: Int minSoFar = nums2[0] - nums1[0] maxSoFar = minSoFar minEndingHere = maxSoFar maxEndingHere = minEndingHere for (i in 1 until n) { currEle = nums2[i] - nums1[i] minEndingHere += currEle maxEndingHere += currEle if (maxEndingHere < currEle) { maxEndingHere = currEle } if (minEndingHere > currEle) { minEndingHere = currEle } maxSoFar = maxEndingHere.coerceAtLeast(maxSoFar) minSoFar = minEndingHere.coerceAtMost(minSoFar) } // return the maximum of the 2 possibilities dicussed // also keep care that maxSoFar>=0 and maxSoFar<=0 return (sum1 + maxSoFar.coerceAtLeast(0)).coerceAtLeast(sum2 - 0.coerceAtMost(minSoFar)) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,938
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/book/recipe/data/SummaryExtension.kt
becgabi
363,655,691
false
null
package com.book.recipe.data fun Recipe.toSummary(): RecipeSummary { val sum = recipeIngredients.reduce { acc, recipeIngredient -> acc + recipeIngredient } return RecipeSummary( recipe = this, sumNutritionFact = sum.ingredient.nutritionFact, sumWeightInGram = sum.weightInGram ) } operator fun RecipeIngredient.plus(other: RecipeIngredient): RecipeIngredient { return RecipeIngredient( weightInGram = weightInGram + other.weightInGram, ingredient = ingredient + other.ingredient ) } operator fun Ingredient.plus(other: Ingredient): Ingredient { return Ingredient( nutritionFact = nutritionFact + other.nutritionFact ) } operator fun NutritionFact.plus(other: NutritionFact): NutritionFact { return NutritionFact( calories = (calories + other.calories).roundTo(), fat = (fat + other.fat).roundTo(), protein = (protein + other.protein).roundTo(), carbs = (carbs + other.carbs).roundTo(), sugar = (sugar + other.sugar).roundTo() ) } operator fun NutritionFact.times(times: Float): NutritionFact { return NutritionFact( calories = (calories * times).roundTo(), fat = (fat * times).roundTo(), protein = (protein * times).roundTo(), carbs = (carbs * times).roundTo(), sugar = (sugar * times).roundTo() ) } fun Double.roundTo(n: Int = 2): Double { return "%.${n}f".format(this).toDouble() }
0
Kotlin
0
0
67887851a82a96206e9bcea9102b0a11c6382b31
1,466
recipe-book
MIT License
src/Day02/Day02.kt
suttonle24
573,260,518
false
{"Kotlin": 26321}
package Day02 import readInput //--- Day 2: Rock Paper Scissors --- //The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress. // //Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw. // //Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent. // //The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen. // //The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). // //Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide. // //For example, suppose you were given the following strategy guide: // //A Y //B X //C Z //This strategy guide predicts and recommends the following: // //In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won). //In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0). //The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6. //In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6). // //What would your total score be if everything goes exactly according to your strategy guide? fun main() { fun part1(input: List<String>): Int { val rock = 1; val iLose = 'X'; val theirRockChar = 'A'; val paper = 2; val iTie = 'Y'; val theirPaperChar = 'B'; val scissors = 3; val iWin = 'Z'; val theirScissorsChar = 'C'; val win = 6; val draw = 3; val loss = 0; var score = 0; var opponent = mutableListOf<Char>(); var me = mutableListOf<Char>(); val itr = input.listIterator(); itr.forEach { opponent.add(it[0]); me.add(it[2]); } val myGame = me.listIterator(); for ((index, myResult) in myGame.withIndex()) { val theirChoice = opponent[index]; if (myResult == iLose) { score += rock; if (theirChoice == theirRockChar) { score += draw; } else if (theirChoice == theirPaperChar) { score += loss; } else if (theirChoice == theirScissorsChar) { score += win; } } else if (myResult == iTie) { score += paper; if (theirChoice == theirRockChar) { score += win; } else if (theirChoice == theirPaperChar) { score += draw; } else if (theirChoice == theirScissorsChar) { score += loss; } } else { score += scissors; if (theirChoice == theirRockChar) { score += loss; } else if (theirChoice == theirPaperChar) { score += win; } else if (theirChoice == theirScissorsChar) { score += draw; } } } println("My score: $score"); return input.size } fun part2(input: List<String>): Int { val rock = 1; val iLose = 'X'; val theirRockChar = 'A'; val paper = 2; val iTie = 'Y'; val theirPaperChar = 'B'; val scissors = 3; val iWin = 'Z'; val theirScissorsChar = 'C'; val win = 6; val draw = 3; val loss = 0; var score = 0; var opponent = mutableListOf<Char>(); var me = mutableListOf<Char>(); val itr = input.listIterator(); itr.forEach { opponent.add(it[0]); me.add(it[2]); } val myGame = me.listIterator(); for ((index, myResult) in myGame.withIndex()) { val theirChoice = opponent[index]; if (myResult == iLose) { score += loss; if (theirChoice == theirRockChar) { score += scissors; } else if (theirChoice == theirPaperChar) { score += rock; } else if (theirChoice == theirScissorsChar) { score += paper; } } else if (myResult == iTie) { score += draw; if (theirChoice == theirRockChar) { score += rock; } else if (theirChoice == theirPaperChar) { score += paper; } else if (theirChoice == theirScissorsChar) { score += scissors; } } else { score += win; if (theirChoice == theirRockChar) { score += paper; } else if (theirChoice == theirPaperChar) { score += scissors; } else if (theirChoice == theirScissorsChar) { score += rock; } } } println("My second score: $score"); return input.size } val input = readInput("Day02/Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
039903c7019413d13368a224fd402625023d6f54
6,490
AoC-2022-Kotlin
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day05.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput import kotlin.math.pow class Day05 : Day<Int> { private val registeredSeats: List<Seat> = readDayInput() .lineSequence() .map { it.parseSeat() } .toList() companion object { const val ROW_CHAR_COUNT = 7 const val COL_CHAR_COUNT = 3 const val FRONT = 'F' const val BACK = 'B' const val RIGHT = 'R' const val LEFT = 'L' val rowCount = 2f.pow(ROW_CHAR_COUNT).toInt() val columnCount = 2f.pow(COL_CHAR_COUNT).toInt() } data class Seat(val row: Int, val col: Int, val id: Int = row * 8 + col) private fun String.parseSeat(): Seat { val rowCode = take(ROW_CHAR_COUNT) val colCode = takeLast(COL_CHAR_COUNT) return Seat( row = getPositionFromCode(rowCode, min = 0, max = rowCount - 1), col = getPositionFromCode(colCode, min = 0, max = columnCount - 1) ) } private tailrec fun getPositionFromCode(code: String, min: Int, max: Int): Int { // println("getPositionFromCode($code, $min, $max)") if (code.length == 1) { return when (code.first()) { // Lower half FRONT, LEFT -> min // Upper half BACK, RIGHT -> max else -> throw IllegalArgumentException() } } val (newMin, newMax) = when (code.first()) { // Lower half FRONT, LEFT -> min to min + ((max - min) / 2) // Upper half BACK, RIGHT -> min + ((max - min) / 2) + 1 to max else -> throw IllegalArgumentException() } return getPositionFromCode(code.drop(1), newMin, newMax) } override fun step1(): Int { return registeredSeats.maxOf { it.id } } override fun step2(): Int { val allSeats = (0 until rowCount).map { row -> (0 until columnCount).map { col -> Seat(row, col) } }.flatten() val minId = registeredSeats.minOf { it.id } val maxId = registeredSeats.maxOf { it.id } val notRegistered = allSeats.filterNot { seat -> seat in registeredSeats }.filter { seat -> seat.id in (minId..maxId) } return notRegistered.first().id } override val expectedStep1: Int = 915 override val expectedStep2: Int = 699 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,547
adventofcode
Apache License 2.0
src/main/kotlin/days/Day05.kt
poqueque
430,806,840
false
{"Kotlin": 101024}
package days import util.Coor class Day05 : Day(5) { override fun partOne(): Any { val data = mutableMapOf<Coor, Int>() inputList.forEach { val (start, stop) = it.split(" -> ").map { it.split(",") } val s = Coor(start[0].toInt(), start[1].toInt()) val e = Coor(stop[0].toInt(), stop[1].toInt()) if (s.x == e.x) { for (i in s.y..e.y) { data[Coor(s.x, i)] = (data[Coor(s.x, i)] ?: 0) + 1 } for (i in e.y..s.y) { data[Coor(s.x, i)] = (data[Coor(s.x, i)] ?: 0) + 1 } } if (s.y == e.y) { for (i in s.x..e.x) { data[Coor(i, s.y)] = (data[Coor(i, s.y)] ?: 0) + 1 } for (i in e.x..s.x) { data[Coor(i, s.y)] = (data[Coor(i, s.y)] ?: 0) + 1 } } } return data.values.count { it > 1 } } override fun partTwo(): Any { val data = mutableMapOf<Coor, Int>() inputList.forEach { val (start, stop) = it.split(" -> ").map { it.split(",") } val s = Coor(start[0].toInt(), start[1].toInt()) val e = Coor(stop[0].toInt(), stop[1].toInt()) if (s.x == e.x) { for (i in s.y..e.y) { data[Coor(s.x, i)] = (data[Coor(s.x, i)] ?: 0) + 1 } for (i in e.y..s.y) { data[Coor(s.x, i)] = (data[Coor(s.x, i)] ?: 0) + 1 } } else if (s.y == e.y) { for (i in s.x..e.x) { data[Coor(i, s.y)] = (data[Coor(i, s.y)] ?: 0) + 1 } for (i in e.x..s.x) { data[Coor(i, s.y)] = (data[Coor(i, s.y)] ?: 0) + 1 } } else { var i = Coor(s.x, s.y) var dir = Coor(0, 0) if (s.x < e.x && s.y < e.y) dir = Coor(1, 1) if (s.x > e.x && s.y < e.y) dir = Coor(-1, 1) if (s.x < e.x && s.y > e.y) dir = Coor(1, -1) if (s.x > e.x && s.y > e.y) dir = Coor(-1, -1) data[i] = (data[i] ?: 0) + 1 while (i != e) { i += dir data[i] = (data[i] ?: 0) + 1 } } } /* for (i in 0 .. data.keys.maxOf { it.y }) { for (j in 0 .. data.keys.maxOf { it.x }) print (data[Coor(j,i)] ?: ".") println () } println()*/ return data.values.count { it > 1 } } }
0
Kotlin
0
0
4fa363be46ca5cfcfb271a37564af15233f2a141
2,686
adventofcode2021
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year19/Day18.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year19 import com.grappenmaker.aoc.* fun PuzzleSet.day18() = puzzle(day = 18) { fun Char.isKey() = this in 'a'..'z' val grid = inputLines.asCharGrid() val totalKeys = grid.elements.count(Char::isKey) fun Grid<Char>.adj(point: Point, keys: Set<Char>) = point.adjacentSides().filter { when (val v = this[it]) { in 'A'..'Z' -> v.lowercaseChar() in keys '#' -> false else -> true } } data class SolveDistance(val key: Point, val moved: Point, val distance: Int) data class MemoEntry(val keys: Set<Char>, val pos: Set<Point>) fun Grid<Char>.solve( keys: Set<Char> = emptySet(), pos: Set<Point> = findPointsValued('@').toSet(), memo: MutableMap<MemoEntry, Int> = mutableMapOf() ): Int = memo.getOrPut(MemoEntry(keys, pos)) { if (keys.size == totalKeys) return@getOrPut 0 pos.flatMap { toMove -> buildList { // Modded version of fillDistance val queue = queueOf(toMove to 0) val seen = hashSetOf(toMove) queue.drain { (curr, dist) -> val value = this@solve[curr] if (value.isKey() && value !in keys) add(SolveDistance(curr, toMove, dist)) else adj(curr, keys).forEach { if (seen.add(it)) queue.addFirst(it to dist + 1) } } } }.minOf { (key, moved, distance) -> solve(keys + this[key], pos - moved + key, memo) + distance } } partOne = grid.solve().s() partTwo = grid.asMutableGrid().apply { val center = Point(width / 2, height / 2) val toAdd = """ @#@ ### @#@ """.trimIndent().lines().asCharGrid() val start = center - Point(toAdd.width / 2, toAdd.height / 2) toAdd.points.forEach { p -> this[start + p] = toAdd[p] } }.asGrid().solve().s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,966
advent-of-code
The Unlicense
src/main/kotlin/days/Day19.kt
TheMrMilchmann
433,608,462
false
{"Kotlin": 94737}
/* * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package days import utils.* import kotlin.math.* fun main() { data class Vec3(val x: Int, val y: Int, val z: Int) { val rolled by lazy { Vec3(x, z, -y) } val turned by lazy { Vec3(-y, x, z) } /* https://stackoverflow.com/questions/16452383/how-to-get-all-24-rotations-of-a-3-dimensional-array */ val rotations by lazy { var vec = this buildList { for (cycle in 0..1) { for (step in 0..2) { vec = vec.rolled add(vec) for (i in 0..2) { vec = vec.turned add(vec) } } vec = vec.rolled.turned.rolled } } } infix fun distanceTo(other: Vec3) = (x - other.x).absoluteValue + (y - other.y).absoluteValue + (z - other.z).absoluteValue operator fun minus(other: Vec3) = Vec3(x - other.x, y - other.y, z - other.z) operator fun plus(other: Vec3) = Vec3(x + other.x, y + other.y, z + other.z) } data class Scanner(val id: Int, val coords: List<Vec3>) { val rotations: List<List<Vec3>> by lazy { coords.flatMap { it.rotations.mapIndexed { index, vec -> index to vec } } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .values .toList() } fun findMatchingFor(other: Set<Vec3>): Pair<Vec3, Set<Vec3>>? { for (rot in rotations) { for (source in rot) { for (target in other) { val offset = target - source if (rot.map { it + offset }.count { it in other } >= 12) return offset to rot.map { it + offset }.toSet() } } } return null } } fun List<String>.parseInput(): List<Scanner> = buildList { var offset = 0 while (offset < this@parseInput.size) { val (scannerID) = """--- scanner (\d+) ---""".toRegex().matchEntire(this@parseInput[offset++])!!.destructured val coords = this@parseInput.drop(offset).takeWhile { it.isNotEmpty() }.map { it.split(',').map(String::toInt).let { (x, y, z) -> Vec3(x, y, z) } } add(Scanner(scannerID.toInt(), coords)) offset += (1 + coords.size) } } val input = readInput().parseInput() var base = input[0].coords.toSet() val scanners = mutableSetOf(Vec3(x = 0, y = 0, z = 0)) var scannerResults = input.drop(1) while (scannerResults.isNotEmpty()) { for (scanner in scannerResults) { val matching = scanner.findMatchingFor(base) if (matching != null) { val (matchedScanner, matchedBeacons) = matching base = base + matchedBeacons scanners += matchedScanner scannerResults = (scannerResults - scanner) break } } } println("Part 1: ${base.size}") println("Part 2: ${scanners.flatMap { a -> scanners.map { b -> a distanceTo b } }.maxOf { it }}") }
0
Kotlin
0
1
dfc91afab12d6dad01de552a77fc22a83237c21d
4,436
AdventOfCode2021
MIT License
src/main/kotlin/exercise/medium/id57/Solution57.kt
kotler-dev
706,379,223
false
{"Kotlin": 63887}
package exercise.medium.id57 import kotlin.math.max import kotlin.math.min class Solution57 { fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) if (newInterval.isEmpty()) return intervals println("[${newInterval[0]}, ${newInterval[1]}]") var start = newInterval[0] var end = newInterval[1] val left = 0 val right = 1 val merged = mutableListOf<IntArray>() var index = 0 while (index < intervals.size && intervals[index][right] < start) { merged.add(intervals[index]) index++ } while (index < intervals.size && intervals[index][left] <= end) { start = min(start, intervals[index][left]) end = max(end, intervals[index][right]) index++ } merged.add(intArrayOf(start, end)) while (index < intervals.size) { merged.add(intervals[index]) index++ } return merged.toTypedArray() } /* fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { if (intervals.isEmpty()) return arrayOf(newInterval) println("[${newInterval[0]}, ${newInterval[1]}]") val start = newInterval[0] val end = newInterval[1] val left = 0 val right = 1 val merged1 = mutableListOf<IntArray>() var index1 = 0 while (index1 < intervals.size && intervals[index1][right] < start) { merged1.add(intervals[index1]) index1++ } if (intervals.size == 1) index1-- val merged2 = mutableListOf<IntArray>() var index2 = intervals.size - 1 while (index2 >= 0 && intervals[index2][left] > end) { merged2.add(intervals[index2]) index2-- } if (intervals.size > 1) { val min = min(start, intervals[index1][left]) val max = max(end, intervals[index2][right]) merged1.add(intArrayOf(min, max)) } merged2.forEach { merged1.add(it) } return merged1.toTypedArray() } var index2 = index while (index2 < intervals.size) { if (intervals[index2][left] > end) { array.add(intervals[index2]) index2++ } } for ((index, arr) in intervals.withIndex()) { if (arr[right] < start) { array.add(arr) } } while (index < intervals.size ) { val value = intervals[index][right] if (value < start) { array.add(intervals[index]) } else if (value < intervals[index][leftIndex]) { intervals[index][right] = end array.add(intervals[index]) sliceStart = index break } } for (index in intervals.indices) { val value = intervals[index][rightIndex] if (value < start) { array.add(intervals[index]) } else if (value < intervals[index][leftIndex]) { intervals[index][rightIndex] = end array.add(intervals[index]) sliceStart = index break } } fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { println("[${newInterval[0]}, ${newInterval[1]}]") val arrayFlatten = mutableListOf<Int>() for (index in intervals.indices) { arrayFlatten.add(intervals[index][0]) arrayFlatten.add(intervals[index][1]) } val arrayNonOverlapping = mutableListOf<Int>() for (index in 0..<arrayFlatten.size) { if (arrayFlatten[index] !in newInterval[0]..newInterval[1]) { println("==> ${arrayFlatten[index]}") arrayNonOverlapping.add(arrayFlatten[index]) } } val arr = mutableListOf<IntArray>() for (index in 0..arrayNonOverlapping.size - 1 step 2) { arr.add(intArrayOf(arrayNonOverlapping[index], arrayNonOverlapping[index + 1])) } return arr.toTypedArray() } fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { println("[${newInterval[0]}, ${newInterval[1]}]") val list = intervals.flatMap { it.asIterable() }.toMutableList() val start = newInterval[0] val end = newInterval[1] if (start !in list) list.add(start) if (end !in list) list.add(end) list.sort() var shiftLeft = 1 var shiftRight = 1 if (list.size % 2 != 0) shiftLeft-- val part1: List<Int> = list.slice(0..<list.indexOf(start) - shiftLeft) if (part1.size % 2 == 0) shiftRight++ val part2: List<Int> = list.slice(list.indexOf(end) + shiftRight..<list.size) val part3: List<Int> = listOf(part1, part2).flatten() val arr2 = mutableListOf<IntArray>() for (index in 0..part3.size - 1 step 2) { arr2.add(intArrayOf(part3[index], part3[index + 1])) } return arr2.toTypedArray() } */ }
0
Kotlin
0
0
0659e72dbf28ce0ec30aa550b6a83c1927161b14
5,144
kotlin-leetcode
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/longest_common_prefix/LongestCommonPrefix.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.longest_common_prefix import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/problems/longest-common-prefix */ class LongestCommonPrefixTests { @Test fun `find the longest common prefix string amongst an array of strings`() { longestCommonPrefix(arrayOf("flower")) shouldEqual "flower" longestCommonPrefix(arrayOf("flower", "flow")) shouldEqual "flow" longestCommonPrefix(arrayOf("flower", "flow", "flight")) shouldEqual "fl" longestCommonPrefix(arrayOf("dog", "racecar", "car")) shouldEqual "" } } private fun longestCommonPrefix(strings: Array<String>): String { var prefixLength = strings.first().length var index = prefixLength - 1 while (index >= 0) { strings.forEach { s -> val match = index < s.length && s[index] == strings.first()[index] if (!match) prefixLength = index } index-- } return strings.first().substring(0, prefixLength) }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,007
katas
The Unlicense
Kotlin/src/WordSearch.kt
TonnyL
106,459,115
false
null
/** * Given a 2D board and a word, find if the word exists in the grid. * * The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. * The same letter cell may not be used more than once. * * For example, * Given board = * * [ * ['A','B','C','E'], * ['S','F','C','S'], * ['A','D','E','E'] * ] * word = "ABCCED", -> returns true, * word = "SEE", -> returns true, * word = "ABCB", -> returns false. * * Accepted. */ class WordSearch { fun exist(board: Array<CharArray>, word: String): Boolean { if (board.isEmpty() || board[0].isEmpty()) { return false } for (i in board.indices) { (0 until board[0].size) .filter { search(board, i, it, word, 0) } .forEach { return true } } return false } private fun search(board: Array<CharArray>, i: Int, j: Int, word: String, index: Int): Boolean { if (index >= word.length) { return true } if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] != word[index]) { return false } board[i][j] = (board[i][j].toInt() xor 255).toChar() val res = (search(board, i - 1, j, word, index + 1) || search(board, i + 1, j, word, index + 1) || search(board, i, j - 1, word, index + 1) || search(board, i, j + 1, word, index + 1)) board[i][j] = (board[i][j].toInt() xor 255).toChar() return res } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,698
Windary
MIT License
src/week1/GroupAnagrams.kt
anesabml
268,056,512
false
null
package week1 import java.util.* import kotlin.system.measureNanoTime class GroupAnagrams { /** Group By * Time complexity : O(log n) * Space complexity : O(1) */ fun groupAnagrams(strs: Array<String>): List<List<String>> { return strs.groupBy { it.toCharArray().sorted() }.map { it.value } } /** Sort and Group By * Time complexity : O(k log n) * Space complexity : O(kn) */ fun groupAnagrams2(strs: Array<String>): List<List<String>?> { if (strs.isEmpty()) return listOf() val output: MutableMap<String, MutableList<String>> = HashMap() for (s in strs) { val key = String(s.toCharArray().sortedArray()) if (!output.containsKey(key)) output[key] = mutableListOf() output[key]!!.add(s) } return output.values.toList() } /** Create a key and Group By * Time complexity : O(kn) * Space complexity : O(kn) */ fun groupAnagrams3(strs: Array<String>): List<List<String>?> { if (strs.isEmpty()) return listOf() val output: MutableMap<String, MutableList<String>> = HashMap() for (s in strs) { val count = IntArray(26) for (c in s.toCharArray()) { count[c - 'a']++ } val key = count.joinToString("#") if (!output.containsKey(key)) output[key] = mutableListOf() output[key]!!.add(s) } return output.values.toList() } } fun main() { val input = arrayOf("eat", "tea", "tan", "ate", "nat", "bat") val groupAnagrams = GroupAnagrams() val firstSolutionTime = measureNanoTime { println(groupAnagrams.groupAnagrams(input)) } val secondSolutionTime = measureNanoTime { println(groupAnagrams.groupAnagrams2(input)) } val thirdSolutionTime = measureNanoTime { println(groupAnagrams.groupAnagrams3(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") println("Third Solution execution time: $thirdSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,145
leetCode
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year17/Day24.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year17 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.splitInts fun PuzzleSet.day24() = puzzle(day = 24) { data class Component(val portA: Int, val portB: Int) val allComponents = inputLines.map { l -> l.splitInts().let { (a, b) -> Component(a, b) } } data class State( val components: List<Component> = emptyList(), val left: List<Component> = allComponents, val endPort: Int = 0 ) fun State.strength() = components.sumOf { it.portA + it.portB } // TODO: pruning fun recurse(curr: State, comparator: Comparator<State>): State = when { curr.left.isEmpty() -> curr else -> curr.left.flatMap { next -> listOfNotNull( if (curr.endPort == next.portA) recurse( State(curr.components + next, curr.left - next, next.portB), comparator ) else null, if (curr.endPort == next.portB) recurse( State(curr.components + next, curr.left - next, next.portA), comparator ) else null, curr ) }.maxWith(comparator) } // Slow strategy for part two, but it generalizes nicely fun solve(comparator: Comparator<State>) = recurse(State(), comparator).strength().s() partOne = solve(compareBy { it.strength() }) partTwo = solve(compareBy<State> { it.components.size }.thenBy { it.strength() }) }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,504
advent-of-code
The Unlicense
src/main/kotlin/Day18.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import java.util.* import kotlin.String import kotlin.collections.List object Day18 { data class Segment(val coordinates: Set<Day17.Coordinate>) { val minX = coordinates.minOf { it.x } val maxX = coordinates.maxOf { it.x } val minY = coordinates.minOf { it.y } val maxY = coordinates.maxOf { it.y } fun crosses(coordinate: Day17.Coordinate): Boolean { return if (minX == maxX && minX == coordinate.x) { coordinate.y in minY..maxY } else if (minY == maxY && minY == coordinate.y) { coordinate.x in minX..maxX } else { false } } fun crosses(y: Int): Boolean { return y in minY..maxY } fun length(): Int { return if (minX == maxX) { maxY - minY + 1 } else { maxX - minX + 1 } } /** * Returns true if the segment is vertical, false otherwise */ fun isVertical(): Boolean { return minX == maxX } /** * Returns true if the segment is horizontal, false otherwise */ fun isHorizontal(): Boolean { return minY == maxY } override fun hashCode(): Int { return Objects.hash(minX, maxX, minY, maxY) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Segment if (coordinates != other.coordinates) return false if (minX != other.minX) return false if (maxX != other.maxX) return false if (minY != other.minY) return false if (maxY != other.maxY) return false return true } } enum class Direction { UP, DOWN, LEFT, RIGHT } data class Instruction(val direction: Direction, val steps: Int, val colorCode: String) { fun toTrueInstruction(): Instruction { val directionCode = colorCode.last() val hexSteps = colorCode.drop(1).dropLast(1) val steps = hexSteps.toInt(16) val direction = when (directionCode) { '0' -> Direction.RIGHT '1' -> Direction.DOWN '2' -> Direction.LEFT '3' -> Direction.UP else -> throw IllegalStateException("Should not happen") } return Instruction(direction, steps, colorCode) } companion object { fun parse(input: String): Instruction { val pattern = "([U|L|D|R]) ([0-9]+) \\((#[a-z0-9]+)\\)".toRegex() val (rawDirection, rawSteps, rawColorCode) = pattern.matchEntire(input)!!.destructured val direction = when (rawDirection) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> throw IllegalStateException("Should not happen") } val steps = rawSteps.toInt() return Instruction(direction, steps, rawColorCode) } } } fun part1(input: List<String>): String { val instructions = input.map { Instruction.parse(it) } return cubicMetersEnclosed(instructions).toString() } fun cubicMetersEnclosed(instructions: List<Instruction>): Long { val segments = dig(instructions) val minY = segments.minOf { it.minY } val maxY = segments.maxOf { it.maxY } val minX = segments.minOf { it.minX } val maxX = segments.maxOf { it.maxX } val delta = maxY - minY var current = 0 var mySegments = segments.sortedWith(compareBy({ it.minY }, { it.maxY })) val enclosedCoordinates = (minY..maxY).sumOf { y -> val startCoordinate = Day17.Coordinate(minX, y) val endCoordinate = Day17.Coordinate(maxX, y) val ret = rayCast(startCoordinate, endCoordinate, mySegments) current += 1 if (current % 1000000 == 0) { mySegments = mySegments.filter { it.maxY >= y } println("Progress: ${String.format("%.2f", current.toDouble() / delta * 100)}%") } ret } val segmentSizes = segments.sumOf { it.length() } val duplicateSegments = segments.flatMap { it.coordinates.toList() }.groupBy { it }.filter { it.value.size > 1 }.keys.size return (enclosedCoordinates + segmentSizes - duplicateSegments) } private fun rayCast( startCoordinate: Day17.Coordinate, endCoordinate: Day17.Coordinate, segments: List<Segment> ): Long { var segmentsEncountered = 0 var cellsWithinPolygon = 0L val runningSegmentsCrossed = mutableSetOf<Segment>() var currentX = startCoordinate.x val segmentsCrossedByRay = segments .takeWhile { it.minY <= endCoordinate.y } .filter { it.crosses(startCoordinate.y) } while (currentX <= endCoordinate.x) { val currentCoordinate = Day17.Coordinate(currentX, startCoordinate.y) val segmentCrosses = segmentsCrossedByRay.filter { it.crosses(currentCoordinate) } val sizeBefore = runningSegmentsCrossed.size runningSegmentsCrossed.addAll(segmentCrosses) val sizeAfter = runningSegmentsCrossed.size val touchedAnotherSegment = sizeAfter > sizeBefore if (segmentCrosses.isNotEmpty()) { // Advance the current position to the max x value of the segment we crossed currentX = segmentCrosses.maxOf { it.maxX } // This is an odd edge case // where there are overlapping segments that are connected // but we encountered the last one if (!touchedAnotherSegment) { currentX += 1 } } else { if (isSingleOrSnakeShaped(runningSegmentsCrossed)) { segmentsEncountered += 1 } runningSegmentsCrossed.clear() val nextSegmentToBeCrossed = segmentsCrossedByRay .minOfOrNull { if (it.minX > currentX) it.minX else Int.MAX_VALUE } val nextX = nextSegmentToBeCrossed ?: (endCoordinate.x + 1) // If the number of segments encountered is odd, then we are within the polygon val isWithinPolygon = segmentsEncountered % 2 == 1 if (isWithinPolygon) { val lengthOfEmptySpace = nextX - currentX cellsWithinPolygon += lengthOfEmptySpace } // Advance the current position to the next segment crossing since all of // these are filled or ignored currentX = nextX } } return cellsWithinPolygon } /** * An annoying case in which we can run into * is when we have a single segment or a snake shaped segment * * # * # * # * # # # * # * # * # * * This counts as one segment */ private fun isSingleOrSnakeShaped(crossedSegments: Set<Segment>): Boolean { if (crossedSegments.isEmpty()) { return false } if (crossedSegments.size == 1) { return true } if (crossedSegments.size == 2) { return false } val verticalSegments = crossedSegments.count { it.isVertical() } val horizontalSegments = crossedSegments.count { it.isHorizontal() } return if (verticalSegments > horizontalSegments) { // This means that the segments are vertical but share a same y coordinte, like // // # // # // # // # # # // # // # // # val sorted = crossedSegments.sortedWith( compareBy({ it.minX }, { it.maxX }) ) val start = sorted.first() val end = sorted.last() val ys = start.coordinates.map { it.y }.toList() + end.coordinates.map { it.y }.toList() val grouped = ys.groupBy { it } val ysThatAppearTwice = grouped.filter { it.value.size == 2 }.keys.first() ysThatAppearTwice > ys.min() && ysThatAppearTwice < ys.max() } else { // This means that the segments are horizontal but share a same x coordinate, like // // # # # # // # // # // # // # // # // # # # # val sorted = crossedSegments.sortedWith(compareBy({ it.minY }, { it.maxY })) val start = sorted.first() val end = sorted.last() val xs = start.coordinates.map { it.x }.toList() + end.coordinates.map { it.x }.toList() val grouped = xs.groupBy { it } val xsThatAppearTwice = grouped.filter { it.value.size == 2 }.keys.first() xsThatAppearTwice > xs.min() && xsThatAppearTwice < xs.max() } } /** * Take a list of instructions that take a starting point and a direction to "dig", which * will then be represented as line segments */ fun dig(instructions: List<Instruction>): List<Segment> { val currentCoordinate = Day17.Coordinate(0, 0) return instructions.fold(currentCoordinate to emptyList<Segment>()) { (currentCoordinate, segments), instruction -> val direction = instruction.direction val steps = instruction.steps val nextCoordinate = when (direction) { Direction.UP -> Day17.Coordinate(currentCoordinate.x, currentCoordinate.y - steps) Direction.DOWN -> Day17.Coordinate(currentCoordinate.x, currentCoordinate.y + steps) Direction.LEFT -> Day17.Coordinate(currentCoordinate.x - steps, currentCoordinate.y) Direction.RIGHT -> Day17.Coordinate(currentCoordinate.x + steps, currentCoordinate.y) } val segment = Segment(setOf(currentCoordinate, nextCoordinate)) nextCoordinate to (segments + listOf(segment)) }.second } fun part2(input: List<String>): String { val instructions = input.map { Instruction.parse(it) }.map { it.toTrueInstruction() } return cubicMetersEnclosed(instructions).toString() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
10,769
kotlin-kringle
Apache License 2.0
instantsearch-core/src/commonMain/kotlin/com/algolia/instantsearch/core/tree/Extensions.kt
algolia
55,971,521
false
{"Kotlin": 689459}
package com.algolia.instantsearch.core.tree public fun <T> Tree<T>.findNode( separator: String, content: T, isMatchingNode: (T, Node<T>, String) -> Boolean ): Node<T>? = children.findNode(separator, content, isMatchingNode) public fun <T> Tree<T>.findNode( content: T, isMatchingNode: (T, Node<T>) -> Boolean ): Node<T>? = children.findNode(content, isMatchingNode) public fun <T> List<Node<T>>.findNode( separator: String, content: T, isMatchingNode: (T, Node<T>, String) -> Boolean ): Node<T>? { forEach { node -> if (isMatchingNode(content, node, separator)) return node.children.findNode(separator, content, isMatchingNode) ?: node } return null } public fun <T> List<Node<T>>.findNode( content: T, isMatchingNode: (T, Node<T>) -> Boolean ): Node<T>? { forEach { node -> if (isMatchingNode(content, node)) return node.children.findNode(content, isMatchingNode) ?: node } return null } public fun <T> List<T>.toNodes( separator: String, isMatchingNode: (T, Node<T>, String) -> Boolean, isSelected: ((T) -> Boolean)? = null ): Tree<T> { return map { Node(it, isSelected != null && isSelected.invoke(it)) }.asTree(separator, isMatchingNode) } public fun <T> List<T>.toNodes( isMatchingNode: (T, Node<T>) -> Boolean, isSelected: ((T) -> Boolean)? = null ): Tree<T> { return map { Node(it, isSelected != null && isSelected.invoke(it)) }.asTree(isMatchingNode) } public fun <T> List<Node<T>>.asTree( separator: String, isMatchingNode: (T, Node<T>, String) -> Boolean ): Tree<T> = Tree<T>().also { tree -> forEach { node -> val root = tree.findNode(separator, node.content, isMatchingNode) if (root != null) { root.children += node } else { tree.children += node } } } public fun <T> List<Node<T>>.asTree( isMatchingNode: (T, Node<T>) -> Boolean ): Tree<T> = Tree<T>().also { tree -> forEach { node -> val root = tree.findNode(node.content, isMatchingNode) if (root != null) { root.children += node } else { tree.children += node } } } /** * Transforms a List of Nodes with children into a flat list matching the nodes hierarchy. * * @param comparator a [Comparator] to sort sibling nodes. * @param transform A function transforming a Node`<`**I**`>` into an **O**, knowing its depth and if it has children. */ public fun <I, O> Tree<I>.asTree( comparator: Comparator<O>, transform: (Node<I>, Int, Boolean) -> O ): List<O> = children.asTree(0, transform).sortedWith(comparator) private fun <I, O> List<Node<I>>.asTree( level: Int = 0, transform: (Node<I>, Int, Boolean) -> O ): List<O> { return mutableListOf<O>().also { list -> forEach { node -> list += transform(node, level, node.children.isEmpty()) list += node.children.asTree(level + 1, transform) } } }
15
Kotlin
32
155
cb068acebbe2cd6607a6bbeab18ddafa582dd10b
2,998
instantsearch-android
Apache License 2.0
src/main/kotlin/be/brammeerten/graphs/Dijkstra.kt
BramMeerten
572,879,653
false
{"Kotlin": 170522}
package be.brammeerten.graphs object Dijkstra { fun <K, V> findShortestPath(graph: Graph<K, V>, start: K, end: K, cache: HashMap<Pair<K, K>, List<Node<K, V>>?>? = null): List<Node<K, V>>? { // Check cache val cached = cache?.get(start to end) if (cached != null) return cached // Traverse graph val prevs = traverse(graph, start) // Calculate path val result = toPath(end, start, prevs, graph) // Store in cache if (cache != null) { cache[start to end] = result cache[end to start] = result?.reversed() } return result } private fun <K, V> traverse(graph: Graph<K, V>, start: K): HashMap<K, K?> { val unvisited = HashSet<K>(graph.nodes.keys) val prevs = HashMap<K, K?>() val distances = HashMap<K, Int>() graph.nodes.values.forEach { distances[it.key] = Int.MAX_VALUE } distances[start] = 0 while (unvisited.isNotEmpty()) { val cur = graph.nodes.values.filter { unvisited.contains(it.key) }.minBy { distances[it.key]!! } unvisited.remove(cur.key) cur.vertices.forEach { vertex -> val d = distances[cur.key]!! + vertex.weight if (d < distances[vertex.to]!!) { distances[vertex.to] = d prevs[vertex.to] = cur.key } } } return prevs } private fun <K, V> toPath(end: K, start: K, prevs: HashMap<K, K?>, graph: Graph<K, V>): List<Node<K, V>>? { val path = ArrayList<K>() var curr: K? = end while (curr != null && curr != start) { path.add(curr) curr = prevs[curr] } if (curr == null) return null path.add(curr) return path.map { graph.nodes[it]!! }.reversed() } }
0
Kotlin
0
0
1defe58b8cbaaca17e41b87979c3107c3cb76de0
1,917
Advent-of-Code
MIT License
kotlin/12.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
class Day12 : Day<Graph<String>>("12") { val Graph<String>.start get() = nodes["start"]!! val Graph<String>.end get() = nodes["end"]!! val Node<String>.isSmall get() = data[0].isLowerCase() val Node<String>.isBig get() = !isSmall fun Graph<String>.dfs( cur: Node<String>, path: List<Node<String>> = mutableListOf(), continuePred: Graph<String>.(Node<String>, List<Node<String>>) -> Boolean ): Int = when { cur == end -> 1 continuePred(cur, path) -> cur.undirNeighbors.sumOf { dfs(it, path + cur, continuePred) } else -> 0 } val bigOrNew: Graph<String>.(Node<String>, List<Node<String>>) -> Boolean = { node, path -> node.isBig || node !in path } override fun dataStar1(lines: List<String>) = Graph(lines.map { it.strings("-").run { Edge(get(0), get(1)) } }) override fun dataStar2(lines: List<String>) = dataStar1(lines) override fun star1(data: Graph<String>): Number = data.dfs(data.start, continuePred = bigOrNew) override fun star2(data: Graph<String>): Number = data.dfs(data.start) { node, path -> bigOrNew(node, path) || (node != start && path.filter { it.isSmall }.run { size == distinct().size }) } } fun main() { Day12()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
1,258
advent-of-code-2021
MIT License