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
src/Day01.kt
mzlnk
573,124,510
false
{"Kotlin": 14876}
fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for(line: String in input) { if(line.isEmpty()) { max = Math.max(max, current) current = 0 continue } current += line.toInt() } max = Math.max(max, current) return max } fun part2(input: List<String>): Int { val calories = ArrayList<Int>() var current = 0 for(line: String in input) { if(line.isEmpty()) { calories.add(current) current = 0 continue } current += line.toInt() } calories.add(current) return calories.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24_000) check(part2(testInput) == 45_000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5
1,098
advent-of-code-2022
Apache License 2.0
letcode/src/main/java/daily/LeetCodeLCP13.kt
chengw315
343,265,699
false
null
package daily import java.util.* fun main() { //16 val i = SolutionLCP13().minimalSteps(arrayOf("S#O", "M..", "M.T")); //-1 val i1 = SolutionLCP13().minimalSteps(arrayOf("S#O", "M.#", "M.T")); //17 val i2 = SolutionLCP13().minimalSteps(arrayOf("S#O", "M.T", "M..")); } class SolutionLCP13 { data class Point(val x:Int,val y:Int) fun minimalSteps(maze: Array<String>): Int { var xS = 0 var yS = 0 var xT = 0 var yT = 0 var numofO = 0 var numofM = 0 val hashMapO = HashMap<Point, Int>() val hashMapM = HashMap<Point, Int>() for (i in maze.indices) { for (j in maze[i].indices) { when(maze[i][j]) { 'O'-> hashMapO.put(Point(i,j),numofO++) 'M'-> hashMapM.put(Point(i,j),numofM++) 'S'-> { xS = i yS = j } 'T'-> { xT = i yT = j } } } } //result = 所有最小(M->O)之和 + 最小(S->O->M0 + M1->T - M1->O) //需要统计的只有: // 1. S->所有O的最短距离;————>BFS val minS2Os = IntArray(numofO){Int.MAX_VALUE} // 2. 所有O->最近M的最短距离;————>BFS val minO2Ms = IntArray(numofO){Int.MAX_VALUE} val minPointO2Ms = Array<Point>(numofO) { Point(0,0) } // 2. 所有M->最近O的最短距离;————>BFS val minM2Os = IntArray(numofM){Int.MAX_VALUE} // 3. 所有M->T的最短距离;————BFS (2.和3.可以在同一轮BFS解决) val minM2Ts = IntArray(numofM){Int.MAX_VALUE} //BFS(S) S->所有O的最短距离 val queue = LinkedList<Point>() var deep = 0 queue.offer(Point(xS,yS)) var colors = Array(maze.size) {BooleanArray(maze[0].length) {false} } while (!queue.isEmpty()) { val size = queue.size for (i in 0 until size) { val pop = queue.poll() if(colors[pop.x][pop.y]) continue colors[pop.x][pop.y] = true if(maze[pop.x][pop.y] == '#') continue if(maze[pop.x][pop.y] == 'O') { minS2Os[hashMapO[pop]!!] = Math.min(deep, minS2Os[hashMapO[pop]!!]) } if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y)) if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y)) if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1)) if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1)) deep++ } } // 2. 所有O->最近M的最短距离;————>BFS loop@ for (O in hashMapO.keys) { queue.clear() deep = 0 queue.offer(O) colors = Array(maze.size) {BooleanArray(maze[0].length) {false} } while (!queue.isEmpty()) { val size = queue.size for (i in 0 until size) { val pop = queue.pop() if(colors[pop.x][pop.y]) continue colors[pop.x][pop.y] = true if(maze[pop.x][pop.y] == '#') continue if(maze[pop.x][pop.y] == 'M') { minO2Ms[hashMapO[O]!!] = deep minPointO2Ms[hashMapO[O]!!] = pop continue@loop } if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y)) if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y)) if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1)) if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1)) deep++ } } } loop2@for (M in hashMapM.keys) { queue.clear() deep = 0 queue.offer(M) colors = Array(maze.size) {BooleanArray(maze[0].length) {false} } var findO = false var findT = false while (!queue.isEmpty()) { val size = queue.size for (i in 0 until size) { val pop = queue.pop() if(colors[pop.x][pop.y]) continue colors[pop.x][pop.y] = true if(maze[pop.x][pop.y] == '#') continue if(!findO && maze[pop.x][pop.y] == 'O') { minM2Os[hashMapM[M]!!] = deep findO = true } if(!findT && maze[pop.x][pop.y] == 'T') { minM2Ts[hashMapM[M]!!] = deep findT = true } if(findO && findT) continue@loop2 if(pop.x > 0) queue.offer(Point(pop.x - 1,pop.y)) if(pop.x < maze.size - 1) queue.offer(Point(pop.x + 1,pop.y)) if(pop.y > 0) queue.offer(Point(pop.x,pop.y - 1)) if(pop.y < maze[pop.x].length - 1) queue.offer(Point(pop.x,pop.y + 1)) deep++ } } } //最小(S->O->M0 + M1->T - M1->O) var minS2O2MAndM2TSubM2O = Int.MAX_VALUE for (i in minS2Os.indices) for (j in minO2Ms.indices) for (x in minM2Os.indices) for (y in minM2Ts.indices) minS2O2MAndM2TSubM2O = if(minPointO2Ms[j] == getKey(hashMapM,x)) minS2O2MAndM2TSubM2O else Math.min(minS2O2MAndM2TSubM2O, minS2Os[i] + minM2Os[j] - minM2Os[x] + minM2Ts[y]) return minM2Os.sum() + minS2O2MAndM2TSubM2O } private fun getKey(hashMapM: HashMap<Point, Int>, x: Int): Point { for ((k,v) in hashMapM) { if (v == x) return k } return Point(1,1) } }
0
Java
0
2
501b881f56aef2b5d9c35b87b5bcfc5386102967
5,994
daily-study
Apache License 2.0
src/Day12.kt
anisch
573,147,806
false
{"Kotlin": 38951}
private typealias Area = Array<CharArray> private fun Area.neighbors(c: Vec): List<Vec> { val next = mutableListOf<Vec>() val cc = when { this[c.y][c.x] == 'S' -> 'a' this[c.y][c.x] == 'E' -> 'z' else -> this[c.y][c.x] } if (0 < c.x) { val cl = this[c.y][c.x - 1] if (cl <= cc + 1) { next += Vec(c.x - 1, c.y) } } if (c.x < this[0].lastIndex) { val cr = this[c.y][c.x + 1] if (cr <= cc + 1) { next += Vec(c.x + 1, c.y) } } if (c.y < lastIndex) { val cb = this[c.y + 1][c.x] if (cb <= cc + 1) { next += Vec(c.x, c.y + 1) } } if (0 < c.y) { val ct = this[c.y - 1][c.x] if (ct <= cc + 1) { next += Vec(c.x, c.y - 1) } } return next } fun main() { fun part1(input: List<String>): Int { val area = input .map { it.toCharArray() } .toTypedArray() var start = Vec(0, 0) var goal = Vec(0, 0) for (y in area.indices) { for (x in area[0].indices) { if (area[y][x] == 'S') { area[y][x] = 'a' start = Vec(x, y) } if (area[y][x] == 'E') { area[y][x] = 'z' goal = Vec(x, y) } } } val frontier = ArrayDeque<Vec>() frontier.addFirst(start) val cameFrom = mutableMapOf<Vec, Vec?>() cameFrom[start] = null while (frontier.isNotEmpty()) { val current = frontier.removeFirst() if (current == goal) break for (next in area.neighbors(current)) { if (!cameFrom.containsKey(next)) { frontier.add(next) cameFrom[next] = current } } } var current = goal val path = mutableListOf<Vec>() while (current != start) { path += current current = cameFrom[current]!! } return path.size } fun part2(input: List<String>): Int { val area = input .map { it.toCharArray() } .toTypedArray() val startVecs = mutableListOf<Vec>() var goal = Vec(0, 0) for (y in area.indices) { for (x in area[0].indices) { if (area[y][x] in listOf('S', 'a')) { area[y][x] = 'a' startVecs += Vec(x, y) } if (area[y][x] == 'E') { area[y][x] = 'z' goal = Vec(x, y) } } } val min = startVecs.minOf { start -> val frontier = ArrayDeque<Vec>() frontier.addFirst(start) val cameFrom = mutableMapOf<Vec, Vec?>() cameFrom[start] = null while (frontier.isNotEmpty()) { val current = frontier.removeFirst() if (current == goal) break for (next in area.neighbors(current)) { if (!cameFrom.containsKey(next)) { frontier.add(next) cameFrom[next] = current } } } var current = goal val path = mutableListOf<Vec>() while (current != start) { path += current val vec = cameFrom[current] if (vec != null) current = vec else return@minOf Int.MAX_VALUE } path.size } return min } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") val input = readInput("Day12") check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
4,157
Advent-of-Code-2022
Apache License 2.0
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/backtracking/Backtracking.kt
joffrey-bion
9,559,943
false
{"Kotlin": 51198, "HTML": 187}
package org.hildan.sudoku.solver.backtracking import org.hildan.sudoku.model.* private const val USE_FORWARD_CHECK = true /** Heuristic of Most Constrained/Constraining Variables */ private const val USE_MCV_HEURISTICS = true /** Heuristic of Least Constraining Value */ private const val USE_LCV_HEURISTIC = true /** * Solve this grid and returns the number of visited nodes in the backtracking algorithm. */ fun Grid.solveWithBacktracking(): Int { // Forward-Checking preparation if (USE_FORWARD_CHECK) { // find the clue-cells and remove the possible values in the impacted // empty cells before starting the search. val stillValid = removeImpossibleCandidates() require(stillValid) { "Incorrect clues in the given grid." } } return backtracking(this) } /** * Recursive backtracking search. If the forward checking is enabled, the possible values of the cells must have * been already updated due to the constraints of the clues. */ private fun backtracking(grid: Grid): Int { if (grid.isComplete) { return 0 } // Choose an empty cell (unassigned variable) val cell = grid.selectEmptyCell() grid.emptyCells.remove(cell) var nbVisitedNodes = 1 // Try the possible values for this cell for (value in cell.orderedCandidates()) { // Check whether the value is still consistent in the current grid. // (This test is not necessary when forward-checking is enabled, because invalid candidates are // eliminated during the search) if (!USE_FORWARD_CHECK && cell.sees(value)) { continue } val success = cell.assignValue(value) // If the forward-checking detected failure, skip the recursion with this value, there is no point if (success) { nbVisitedNodes += backtracking(grid) if (grid.isComplete) return nbVisitedNodes } // Clear the cell (remove the variable from assignment) to try other values cell.unassignValue() } grid.emptyCells.add(cell) return nbVisitedNodes } /** * Choose the next empty cell to fill. */ private fun Grid.selectEmptyCell(): Cell { // Without heuristics, take the first one that comes if (!USE_MCV_HEURISTICS) { return emptyCells.first() } // Most Constrained Variable heuristic (or Minimum Remaining Values) // We try here to choose a cell with the fewest remaining candidates val cellsWithFewestCandidates = emptyCells.filterFewestCandidates() // Most Constraining Variable heuristic (or "degree" heuristic) // We choose the cell with the most empty sisters (thus the most impact) to discover dead-ends early return cellsWithFewestCandidates.maxByOrNull { it.nbEmptySisters } ?: error("No empty cells") } private fun Iterable<Cell>.filterFewestCandidates(): List<Cell> = buildList { var minLCV = 9 for (cell in this@filterFewestCandidates) { val size = cell.candidates.size if (size == minLCV) { add(cell) } else if (size < minLCV) { clear() add(cell) minLCV = size } } } /** * Returns an ordered list of values to test for this [Cell]. */ private fun Cell.orderedCandidates(): List<Digit> { if (!USE_LCV_HEURISTIC || candidates.size <= 1) { // the second part of the test saves some time return candidates.toList() } // Least Constraining Value // We want to sort the possible digits for the given cell, choosing first those which impose the fewest constraints // on the sisters (so it gives more chance to find a solution and avoid backtracking) return candidates.sortedBy { value -> // For each possible value of the Cell, we count the number of possibilities which will be ruled out by the // forward checking if we assign this value to this cell. // That is the number of sisters having this value in their possibilities. sisters.count { s -> s.isEmpty && value in s.candidates } } } /** * Assigns the given [value] to this [Cell], and if forward checking is enabled, updates the sisters' possibilities. * * @return `false` if the forward checking is enabled and one of the sisters has no more possible values, * `true` otherwise. */ private fun Cell.assignValue(value: Digit): Boolean { this.value = value // Forward Checking: propagate the constraints right now to foresee the problems return if (USE_FORWARD_CHECK) removeValueFromSistersCandidates() else true } /** * Remove the assigned value to this [Cell], and if forward checking is enabled, update the sisters' possibilities. */ private fun Cell.unassignValue() { val value = value ?: error("the cell should have a value to unassign") this.value = null // Forward Checking: restore the possibilities that had been removed if (USE_FORWARD_CHECK) { restoreValueInSisters(value) } }
0
Kotlin
0
0
441fbb345afe89b28df9fe589944f40dbaccaec5
4,977
sudoku-solver
MIT License
2023/src/main/kotlin/sh/weller/aoc/Day11.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc import sh.weller.aoc.util.to2DList import kotlin.math.max import kotlin.math.min object Day11 : SomeDay<String, Long> { override fun partOne(input: List<String>): Long = calculateDistances(2, input.to2DList()) override fun partTwo(input: List<String>): Long = calculateDistances(1000000, input.to2DList()) private fun calculateDistances(expandFactor: Long, grid: List<List<Char>>): Long { val emptyRows = grid.mapIndexedNotNull { index, chars -> if (chars.all { it == '.' }) { index } else { null } } val emptyColumns = mutableListOf<Int>() for (i in 0..<grid.first().size) { val column = grid.map { it[i] } if (column.all { it == '.' }) { emptyColumns.add(i) } } val stars: MutableList<Pair<Int, Int>> = mutableListOf() for ((rowIndex, row) in grid.withIndex()) { for ((colIndex, c) in row.withIndex()) { if (c == '#') { stars.add(rowIndex to colIndex) } } } val distances = mutableListOf<Long>() for ((index, star) in stars.withIndex()) { val otherStars = stars.drop(index + 1) for (other in otherStars) { val minRow = min(star.first, other.first) val maxRow = max(star.first, other.first) val minCol = min(star.second, other.second) val maxCol = max(star.second, other.second) val emptyRowsBetween = emptyRows.count { it in minRow..maxRow } val expandedRows = emptyRowsBetween * (expandFactor - 1) val emptyColsBetween = emptyColumns.count { it in minCol..maxCol } val expandedCols = emptyColsBetween * (expandFactor - 1) val rowDistance = maxRow + expandedRows - minRow val colDistance = maxCol + expandedCols - minCol distances.add(rowDistance + colDistance) } } return distances.sum() } }
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
2,165
AdventOfCode
MIT License
src/Day25.kt
uekemp
575,483,293
false
{"Kotlin": 69253}
typealias Snafu = String private fun Snafu.toInt(): Int { val chars = toCharArray() chars.reverse() var f = 1 return chars.sumOf { c -> val result = f * snafuToInt(c) f *= 5 result } } fun snafuToInt(digit: Char): Int { return when(digit) { '2' -> 2 '1' -> 1 '0' -> 0 '-' -> -1 '=' -> -2 else -> error("Unknown SNAFU digit: $digit") } } fun main() { fun part1(input: List<String>): Int { return input.sumOf { line -> line.toInt() } } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") check(part1(testInput) == 4890) val input = readInput("Day25") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bc32522d49516f561fb8484c8958107c50819f49
873
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-17.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2021, "17-input") val test1 = readInputText(2021, "17-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: String): Int { val (bottomLeft, _) = parse(input) val maxY = -bottomLeft.y - 1 return (maxY * (maxY + 1)) / 2 } private fun part2(input: String): Int { val (bottomLeft, topRight) = parse(input) val maxX = topRight.x val minX = 0 val maxY = -bottomLeft.y - 1 val minY = bottomLeft.y var result = 0 for (dx in minX .. maxX) { for (dy in minY .. maxY) { val velocity = Coord2D(dx, dy) if (willHit(velocity, bottomLeft, topRight)) result++ } } return result } private fun willHit(initialVelocity: Coord2D, bottomLeft: Coord2D, topRight: Coord2D): Boolean { var position = Coord2D(0, 0) var velocity = initialVelocity while (position.x <= topRight.x && position.y >= bottomLeft.y) { position += velocity velocity = velocity.copy(x = (velocity.x - 1).coerceAtLeast(0), y = velocity.y - 1) if (position.x in bottomLeft.x .. topRight.x && position.y in bottomLeft.y .. topRight.y) { return true } } return false } private fun parse(input: String): Pair<Coord2D, Coord2D> { val regex = """target area: x=(\d+)..(\d+), y=(-?\d+)..(-?\d+)""".toRegex() val (x1, x2, y1, y2) = regex.matchEntire(input)!!.destructured return Coord2D(x1.toInt(), y1.toInt()) to Coord2D(x2.toInt(), y2.toInt()) }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,858
advent-of-code
MIT License
jax/codeforces/uncategorized/8-kotlin/d_sweepstake.kt
jaxvanyang
423,682,977
false
{"C++": 1073738, "Kotlin": 10571, "Java": 8975, "Python": 3215, "Shell": 508, "Makefile": 389, "PowerShell": 341}
fun readLn() = readLine()!! fun readStrs() = readLn().split(" ") fun readInts() = readStrs().map { it.toInt() } fun main() { val (n, m) = readInts() val a = Array(m) { readInts() } val fCnt = IntArray(n + 1) { 0 } val lCnt = IntArray(n + 1) { 0 } val hashCnt = IntArray((n + 1) * n) { 0 } fun hash(f: Int, l: Int) = f * n + l for (i in 0 until m) { fCnt[a[i][0]]++ lCnt[a[i][1]]++ hashCnt[hash(a[i][0], a[i][1])]++ } var ans = 1 val x = a[0][0] val y = a[0][1] for (i in 1..n) { for (j in 1..n) { if (i == j) continue val c2 = hashCnt[hash(i, j)] val c1 = fCnt[i] + lCnt[j] - c2 * 2 when { x == i && y == j -> ans = max(ans, 1) x == i || y == j -> ans = max(ans, c2 + 1) else -> ans = max(ans, c2 + c1 + 1) } } } println(ans) } fun max(a: Int, b: Int) = if (a > b) a else b
0
C++
0
0
ee41f1cbf692b7b1463a9467401bb6e7d38aecce
842
acm
MIT License
src/main/kotlin/g0401_0500/s0417_pacific_atlantic_water_flow/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0417_pacific_atlantic_water_flow // #Medium #Array #Depth_First_Search #Breadth_First_Search #Matrix // #Graph_Theory_I_Day_4_Matrix_Related_Problems #Level_2_Day_10_Graph/BFS/DFS #Udemy_Graph // #2022_12_06_Time_319_ms_(100.00%)_Space_37.5_MB_(100.00%) class Solution { private var col = 0 private var row = 0 fun pacificAtlantic(matrix: Array<IntArray>): List<List<Int>> { val res: MutableList<List<Int>> = ArrayList() if (matrix.size == 0) { return res } col = matrix.size row = matrix[0].size val pacific = Array(col) { BooleanArray( row ) } val atlantic = Array(col) { BooleanArray( row ) } for (i in 0 until col) { dfs(i, 0, matrix, pacific) dfs(i, row - 1, matrix, atlantic) } for (i in 0 until row) { dfs(0, i, matrix, pacific) dfs(col - 1, i, matrix, atlantic) } for (i in 0 until col) { for (j in 0 until row) { if (pacific[i][j] && atlantic[i][j]) { val temp: MutableList<Int> = ArrayList() temp.add(i) temp.add(j) res.add(temp) } } } return res } private fun dfs(i: Int, j: Int, matrix: Array<IntArray>, visited: Array<BooleanArray>) { if (i < 0 || j < 0 || i >= matrix.size || j >= matrix[0].size || visited[i][j]) { return } visited[i][j] = true if (i < col - 1 && matrix[i][j] <= matrix[i + 1][j]) { dfs(i + 1, j, matrix, visited) } if (i > 0 && matrix[i][j] <= matrix[i - 1][j]) { dfs(i - 1, j, matrix, visited) } if (j < row - 1 && matrix[i][j] <= matrix[i][j + 1]) { dfs(i, j + 1, matrix, visited) } if (j > 0 && matrix[i][j] <= matrix[i][j - 1]) { dfs(i, j - 1, matrix, visited) } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,103
LeetCode-in-Kotlin
MIT License
math/FastFourierTransform.kt
wangchaohui
737,511,233
false
{"Kotlin": 36737}
data class Complex( val re: Double = 0.0, val im: Double = 0.0, ) { operator fun plus(other: Complex) = Complex(re + other.re, im + other.im) operator fun minus(other: Complex) = Complex(re - other.re, im - other.im) operator fun times(other: Double) = Complex(re * other, im * other) operator fun times(other: Complex) = Complex( re = re * other.re - im * other.im, im = re * other.im + im * other.re, ) operator fun div(other: Double) = Complex(re / other, im / other) // override fun toString(): String = "${re.roundToInt()}+${im.roundToInt()}i" companion object { val UNITY = Complex(1.0) fun polar(modulus: Double, argument: Double) = Complex(cos(argument), sin(argument)) * modulus } } class FastFourierTransform { private val rev = IntArray(N) private val w = Array(N) { Complex.UNITY } init { val wn = Complex.polar(1.0, 2 * Math.PI / N) for (i in 1..<N) { w[i] = w[i - 1] * wn rev[i] = rev[i / 2] / 2 if (i and 1 == 1) { rev[i] += N / 2 } } } fun dft(p: Array<Complex>, inverse: Boolean = false) { prepare(p) var subProblemSize = 2 while (subProblemSize <= N) { val wStep = (if (inverse) -1 else 1) * N / subProblemSize for (subProblemStart in 0..<N step subProblemSize) { var wIndex = 0 for (j in subProblemStart..<subProblemStart + subProblemSize / 2) { val u = p[j] val t = w[wIndex.mod(N)] * p[j + subProblemSize / 2] p[j] = u + t p[j + subProblemSize / 2] = u - t wIndex += wStep } } subProblemSize *= 2 } if (inverse) for (j in 0..<N) p[j] = p[j] / N.toDouble() } private fun prepare(x: Array<Complex>) { for (i in 1..<N) { if (i < rev[i]) x[i] = x[rev[i]].also { x[rev[i]] = x[i] } } } companion object { const val LOG_N = 20 const val N = 1 shl LOG_N } }
0
Kotlin
0
0
241841f86fdefa9624e2fcae2af014899a959cbe
2,164
kotlin-lib
Apache License 2.0
lib/src/main/kotlin/com/github/xmppjingle/bayes/GaussianNaiveBayes.kt
xmppjingle
583,324,456
false
{"Kotlin": 35890}
package com.github.xmppjingle.bayes import org.apache.commons.math3.stat.descriptive.moment.Variance import kotlin.math.ln import kotlin.math.pow class GaussianDistribution(val mean: Double, val std: Double) { fun probability(x: Double): Double { val exponent = -(x - mean).pow(2.0) / (2.0 * std.pow(2.0)) return (1.0 / (std * Math.sqrt(2.0 * Math.PI))) * Math.exp(exponent) } } class GaussianNaiveBayes(private val distributions: Map<String, List<GaussianDistribution>>) { companion object { private val LABELS = listOf("Work", "Home", "Other") fun train(data: List<Pair<List<Double>, String>>): GaussianNaiveBayes { val variance = Variance() val featureVariances = List(data[0].first.size) { i -> variance.evaluate(data.map { it.first[i] }.toDoubleArray()) } val updatedDistributions = mutableMapOf<String, List<GaussianDistribution>>() for (label in LABELS) { val labelData = data.filter { it.second == label } val labelDistributions = List(labelData[0].first.size) { i -> GaussianDistribution( labelData.map { it.first[i] }.average(), Math.sqrt(featureVariances[i]) ) } updatedDistributions[label] = labelDistributions } return GaussianNaiveBayes(updatedDistributions) } fun splitTimeOfDay(timeOfDay: Double): List<Double> { val sin = Math.sin(timeOfDay * (Math.PI / 12)) * 120 val cos = Math.cos(timeOfDay * (Math.PI / 12)) * 120 return listOf(sin, cos) } fun splitInputTimeOfDay(input: List<Double>, index: Int = 1): List<Double> { val timeOfDay = input[index] val splitTimeOfDay = splitTimeOfDay(timeOfDay) return input.subList(0, index) + splitTimeOfDay + input.subList(index + 1, input.size) } } fun predict(features: List<Double>): String { var maxLogProb = Double.NEGATIVE_INFINITY var maxLabel = "" var logProb = 0.0 for ((label, labelDistributions) in distributions) { logProb = ln(1.0 / distributions.size.toDouble()) for (i in labelDistributions.indices) { logProb += ln(labelDistributions[i].probability(features[i])) } if (logProb >= maxLogProb) { maxLogProb = logProb maxLabel = label } } if(maxLabel.isBlank()){ println("Blank: $features") } return maxLabel } }
0
Kotlin
1
0
9c0057acb21e8f32bd083c71b6532efe92ae5513
2,696
homework
Apache License 2.0
src/main/kotlin/com/marcdenning/adventofcode/day18/Day18b.kt
marcdenning
317,730,735
false
{"Kotlin": 87536}
package com.marcdenning.adventofcode.day18 import java.io.File fun main(args: Array<String>) { val sum = File(args[0]).readLines().map { evaluateExpressionInverse(it) }.sum() println("Sum of all operations: $sum") } fun evaluateExpressionInverse(expression: String) = evaluateExpressionTree(buildTreeFromExpression(expression)) fun buildTreeFromExpression(expression: String): ExpressionNode { val expressionTree = ExpressionNode('+', ExpressionNode('0')) var currentNode = expressionTree for (char in expression) { if (char != ' ') { currentNode = currentNode.addChar(char) } } return expressionTree } fun evaluateExpressionTree(node: ExpressionNode): Long { if (node.left == null && node.right == null) { return ("" + node.char).toLong() } return when (node.char) { '+' -> evaluateExpressionTree(node.left!!) + evaluateExpressionTree(node.right!!) '*' -> evaluateExpressionTree(node.left!!) * evaluateExpressionTree(node.right!!) else -> throw Exception() } } data class ExpressionNode( var char: Char, var left: ExpressionNode? = null, var right: ExpressionNode? = null ) { fun addChar(newChar: Char): ExpressionNode { return when { char.isDigit() && (newChar == '+' || newChar == '*') -> { left = ExpressionNode(char) char = newChar this } (char == '+' || char == '*') && (newChar.isDigit() || newChar == '(') -> { right = ExpressionNode(newChar) right!! } char == '(' && newChar.isDigit() -> { left = ExpressionNode(newChar) this } char == '(' && (newChar == '+' || newChar == '*') -> { char = newChar this } newChar == ')' -> this else -> throw Exception() } } }
0
Kotlin
0
0
b227acb3876726e5eed3dcdbf6c73475cc86cbc1
1,981
advent-of-code-2020
MIT License
calendar/day04/Day4.kt
divgup92
573,352,419
false
{"Kotlin": 15497}
package day04 import Day import Lines import kotlin.streams.toList class Day4 : Day() { override fun part1(input: Lines) = input.stream().map { line -> getPairs(line) }.filter { pairs -> isFullOverlap(pairs) }.toList().count() private fun getPairs(input: String) = input.split(",").stream().map { i -> i.split("-") }.toList() private fun isFullOverlap(pairs: List<List<String>>): Boolean { // [a,b] [c,d] val (a,b,c,d) = listOf(pairs[0][0].toInt(), pairs[0][1].toInt(), pairs[1][0].toInt(), pairs[1][1].toInt()); return (a in c..d && b in c..d) || (c in a..b && d in a..b) } override fun part2(input: Lines) = input.stream().map { line -> getPairs(line) }.filter { pairs -> isPartialOverlap(pairs) }.toList().count() private fun isPartialOverlap(pairs: List<List<String>>): Boolean { val (a,b,c,d) = listOf(pairs[0][0].toInt(), pairs[0][1].toInt(), pairs[1][0].toInt(), pairs[1][1].toInt()); return (a in c..d) || (b in c..d) || (c in a..b) || (d in a..b) } }
0
Kotlin
0
0
dcd221197ecb374efa030a7993a0152099409f14
1,035
advent-of-code-2022
Apache License 2.0
src/main/kotlin/adventofcode2020/solution/Day2.kt
lhess
320,667,380
false
null
package adventofcode2020.solution import adventofcode2020.Solution import adventofcode2020.resource.PuzzleInput class Day2(puzzleInput: PuzzleInput<String>) : Solution<String, Int>(puzzleInput) { private val passwords = puzzleInput.map(Password::of) override fun runPart1() = passwords.count { (range, char, password) -> password.count { it == char } in range } .apply { check(this == 586) } override fun runPart2() = passwords.count { (range, char, password) -> (password[range.first - 1] == char) xor (password[range.last - 1] == char) } .apply { check(this == 352) } private data class Password(val range: IntRange, val char: Char, val value: String) { companion object { private val pattern = """^(\d+)-(\d+) (\w): (\w+)$""".toRegex() fun of(input: String): Password { val (min, max, char, value) = pattern.find(input)!!.destructured return Password(min.toInt()..max.toInt(), char.first(), value) } } } }
0
null
0
1
cfc3234f79c27d63315994f8e05990b5ddf6e8d4
1,102
adventofcode2020
The Unlicense
aoc-2023/src/main/kotlin/aoc/aoc21.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.* val testInput = """ ........... .....###.#. .###.##..#. ..#.#...#.. ....#.#.... .##..S####. .##..#...#. .......##.. .##.#.####. .##..##.##. ........... """.parselines // part 1 fun List<String>.part1(): Int { val grid = GridBlinker(this, findCoords2 { it == 'S' }.values.first().first()) repeat(if (size < 20) 6 else 64) { grid.step() } return grid.sizes.last() } // part 2 fun CharGrid.open(c: Coord) = getOrNull(c.y)?.getOrNull(c.x)?.let { it == '.' || it == 'S' } ?: false fun CharGrid.offMap(c: Coord) = getOrNull(c.y)?.getOrNull(c.x) == null class GridBlinker(val map: CharGrid, val start: Coord) { var posn = setOf<Coord>(start) val sizes = mutableListOf(1) val mayGoOff = mutableListOf(UP, DOWN, LEFT, RIGHT) /** Take one step in the grid, updating positions and sizes. Return a list of steps that would go off the map. */ fun step(): List<Coord> { val off = posn.flatMap { p -> mayGoOff.toList().mapNotNull { dir -> val c = p + dir if (map.offMap(c)) { mayGoOff.remove(dir) c } else null } } posn = posn.flatMap { listOf(it.top, it.bottom, it.left, it.right).filter { map.open(it) } }.toSet() sizes += posn.size return off } /** * Determine # of positions after [iters] iterations, given starting step #s (keys in [start]) and copies (values in [start]). * Assume the grid has already been iterated at least (map.size*2) times. */ fun after(iters: Int, start: Map<Int, Int>): Long { return start.entries.sumOf { (stepNo, copies) -> val sample = if (iters - stepNo < map.size * 2) sizes[iters - stepNo] else sizes[map.size * 2 + (iters - stepNo) % 2] sample * copies.toLong() } } } fun List<String>.part2(ITERS: Int): Long { val sz = size val md = sz / 2 // create instance of each type of grid, based on where the starting position is val gridUL = GridBlinker(this, Coord(0, 0)) val gridU = GridBlinker(this, Coord(md, 0)) val gridUR = GridBlinker(this, Coord(sz-1, 0)) val gridL = GridBlinker(this, Coord(0, md)) val gridC = GridBlinker(this, Coord(md, md)) val gridR = GridBlinker(this, Coord(sz-1, md)) val gridDL = GridBlinker(this, Coord(0, sz-1)) val gridD = GridBlinker(this, Coord(md, sz-1)) val gridDR = GridBlinker(this, Coord(sz-1, sz-1)) // gather sequences for each type of grid listOf(gridUL, gridU, gridUR, gridL, gridC, gridR, gridDL, gridD, gridDR).forEach { grid -> repeat(size * 2 + 2) { grid.step() } } // determine entry points in # of steps for each type of grid val centerEntry = 0 // generate sequence with 66, 197, ... for each of the four compass directions val edgeEntry = generateSequence(md + 1) { it + sz }.takeWhile { it <= ITERS }.toList() // generate sequence with 132, 263, 263, 394, 394, 394, etc. for each of the four corners of the grid val cornerEntry = generateSequence(sz + 1) { it + sz }.takeWhile { it <= ITERS }.toList() .map { it to it/sz } return gridC.after(ITERS, start = mapOf(centerEntry to 1)) + listOf(gridU, gridD, gridL, gridR).sumOf { grid -> edgeEntry.sumOf { grid.after(ITERS, start = mapOf(it to 1)) } } + listOf(gridUL, gridUR, gridDL, gridDR).sumOf { grid -> cornerEntry.sumOf { grid.after(ITERS, start = mapOf(it.first to it.second)) } } } fun List<String>.part2b(): Int { val grid = GridBlinker(this, findCoords2 { it == 'S' }.values.first().first()) val wid = size /** Keep track of where you first enter each grid, since a unique starting location will yield a unique pattern. */ val gridsByStart = mutableMapOf(grid.start to grid) /** Track the entry times to each grid. */ val grids = mutableMapOf(grid to mutableListOf(0)) (1..200).forEach { step -> grids.keys.toList().forEach { val offMap = it.step() offMap.forEach { val newStart = (it.x + wid) % wid to (it.y + wid) % wid print("Leaving map after $step steps at $it, will reenter at $newStart, ") val existingGrid = gridsByStart[newStart] if (existingGrid != null) { println("this start has already been seen ${grids[existingGrid]!!.size} times.") grids[existingGrid]!!.add(step) } else { println("this starting position is new.") val newGrid = GridBlinker(this, newStart) gridsByStart[newStart] = newGrid grids[newGrid] = mutableListOf(step) } } } } return 0 } /** Attempt to create a bigger maze and see if there's a pattern. */ fun List<String>.part2a(iters: Int): Int { val COPIES = 2 * (iters/size) + 3 val map0 = this as CharGrid val map101a = map0.map { it.repeat(COPIES).replace("S", ".") } val map = generateSequence { map101a }.take(COPIES).flatten().toMutableList() val xr = map.xrange val yr = map.yrange val start = xr.last/2 to yr.last/2 println(start) var posn = setOf<Coord>(start) val sizes = mutableListOf(1) repeat(iters) { i -> posn = posn.flatMap { listOf(it.top, it.bottom, it.left, it.right).filter { map.at(it) == '.' || map.at(it) == 'S' } }.toSet() sizes += posn.size if (i in listOf(6, 10, 50, 64, 100, 500, 1000, 5000)) print(" " + sizes[i]) } println() // val diffs = sizes.drop(wid).mapIndexed { i, v -> v - sizes[i] } // diffs.chunked(wid).forEach { // println(it.joinToString(" ") { "%5d".format(it) } ) // } return sizes.last() } // calculate answers val day = 21 val input = getDayInput(day, 2023) val testResult = testInput.part1().also { it.print } testInput.part2a(101) val answer1 = input.part1().also { it.print } val answer2a = input.part2a(101).also { it.print } listOf(6, 10, 50, 64, 100, 500, 1000, 5000).forEach { print("$it $ANSI_BLUE${input.part2(it)}$ANSI_RESET ") } println() val answer2 = input.part2(26501365).also { it.print } // print results AocRunner(day, test = { "$testResult" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
6,552
advent-of-code
Apache License 2.0
src/day01/Day01.kt
Dr4kn
575,092,295
false
{"Kotlin": 12652}
package day01 import readInput fun main() { fun part1(input: List<String>): Int { var maxValue = 0 var currentValue = 0 input.forEachIndexed { index, value -> if (value != "") { currentValue += value.toInt() } if (value == "" || index == input.size - 1) { if (currentValue > maxValue) { maxValue = currentValue } currentValue = 0 } } return maxValue } fun part2(input: List<String>): Int { var currentValue = 0 val topThree: IntArray = IntArray(3) input.forEachIndexed { index, value -> if (value != "") { currentValue += value.toInt() } if (value == "" || index == input.size - 1) { if (currentValue > topThree[0]) { topThree[0] = currentValue topThree.sort() } currentValue = 0 } } return topThree.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5
1,378
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g0101_0200/s0109_convert_sorted_list_to_binary_search_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0109_convert_sorted_list_to_binary_search_tree // #Medium #Tree #Binary_Tree #Linked_List #Binary_Search_Tree #Divide_and_Conquer // #2023_07_11_Time_191_ms_(100.00%)_Space_39.5_MB_(61.54%) import com_github_leetcode.ListNode import com_github_leetcode.TreeNode /* * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun sortedListToBST(head: ListNode?): TreeNode? { // Empty list -> empty tree / sub-tree if (head == null) { return null } // No next node -> this node will become leaf if (head.next == null) { val leaf = TreeNode(head.`val`) leaf.left = null leaf.right = null return leaf } var slow = head // Head-Start fast by 1 to get slow = mid -1 var fast = head.next!!.next // Find the mid of list while (fast != null && fast.next != null) { slow = slow!!.next fast = fast.next!!.next } // slow.next -> mid = our "root" val root = TreeNode(slow!!.next!!.`val`) // Right sub tree from mid - end root.right = sortedListToBST(slow.next!!.next) // Left sub tree from head - mid (chop slow.next) slow.next = null root.left = sortedListToBST(head) return root } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,690
LeetCode-in-Kotlin
MIT License
src/Day04.kt
cerberus97
579,910,396
false
{"Kotlin": 11722}
fun main() { fun parseRange(range: String): IntRange { val lo = range.substringBefore('-').toInt() val hi = range.substringAfter('-').toInt() return IntRange(lo, hi) } fun IntRange.contains(other: IntRange): Boolean = contains(other.first) && contains(other.last) fun IntRange.overlaps(other: IntRange): Boolean = contains(other.first) || contains(other.last) fun part1(input: List<String>): Int { return input.count { ranges -> val firstRange = parseRange(ranges.substringBefore(',')) val secondRange = parseRange(ranges.substringAfter(',')) firstRange.contains(secondRange) || secondRange.contains(firstRange) } } fun part2(input: List<String>): Int { return input.count { ranges -> val firstRange = parseRange(ranges.substringBefore(',')) val secondRange = parseRange(ranges.substringAfter(',')) firstRange.overlaps(secondRange) || secondRange.overlaps(firstRange) } } val input = readInput("in") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ed7b5bd7ad90bfa85e868fa2a2cdefead087d710
1,038
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/theo/TheoPcpK.kt
sssemil
268,084,789
false
null
package theo import kotlin.math.abs class TheoPcpK { private fun visit( instances: List<Instance>, visitedStates: MutableList<Instance>, initialState: Instance, k: Int, trace: List<Instance> ): List<List<Instance>?> { val currentState = initialState.reduce() // check if solved if (currentState.xs.isEmpty() && currentState.ys.isEmpty()) { return listOf(trace) } // check if its still k-bound if (currentState.distance() > k) { return emptyList() } // check if this state was visited before if (visitedStates.contains(currentState)) { return emptyList() } visitedStates.add(currentState) // continue visiting other states return instances.filter { (currentState + it).reduce().initial() }.flatMap { visit(instances, visitedStates, currentState + it, k, trace + it) } } fun findKBoundSolutions(instances: List<Instance>, k: Int): List<List<Instance>?> { val visitedStates = mutableListOf<Instance>() return instances.filter { it.initial() }.flatMap { initialState -> visit(instances, visitedStates, initialState, k, listOf(initialState)) } } data class Instance(val xs: String, val ys: String) { fun reduce() = when { xs.startsWith(ys) -> { Instance(xs.substring(ys.length), "") } ys.startsWith(xs) -> { Instance("", ys.substring(xs.length)) } else -> this } fun distance() = abs(xs.length - ys.length) operator fun plus(other: Instance) = Instance(xs + other.xs, ys + other.ys) fun initial(): Boolean = xs.startsWith(ys) || ys.startsWith(xs) } } fun main() { TheoPcpK().apply { println( findKBoundSolutions( instances = listOf( TheoPcpK.Instance("bb", "b"), TheoPcpK.Instance("ab", "ba"), TheoPcpK.Instance("c", "bc") ), k = 5 ) ) println( findKBoundSolutions( instances = listOf( TheoPcpK.Instance("ab", "a"), TheoPcpK.Instance("b", "a"), TheoPcpK.Instance("a", "b") ), k = 5 ) ) println( findKBoundSolutions( instances = listOf( TheoPcpK.Instance("1", "111"), TheoPcpK.Instance("10111", "10"), TheoPcpK.Instance("10", "0") ), k = 5 ) ) println( findKBoundSolutions( instances = listOf( TheoPcpK.Instance("a", "baa"), TheoPcpK.Instance("ab", "aa"), TheoPcpK.Instance("bba", "bb") ), k = 5 ) ) } }
0
Kotlin
0
0
02d951b90e0225bb1fa36f706b19deee827e0d89
3,084
math_playground
MIT License
2017-kotlin/src/main/kotlin/com/morninghacks/aoc2017/Day07.kt
whaley
116,508,747
false
null
package com.morninghacks.aoc2017 import java.lang.invoke.MethodHandles private data class NodeFromLine(val id: String, val weight: Int, val childIds: List<String>) private data class Node(val id: String, val weight: Int, var children: List<Node> = listOf(), val parent: Node? = null) { fun treeWeight() : Int = weight + children.sumBy(Node::treeWeight) override fun toString(): String { return "Node(id='$id', weight=$weight, children=$children)" } } fun solve(source: String): Pair<String,Pair<String,Int>> { //need two maps - id -> Node for all nodes val allNodes: List<NodeFromLine> = source.lines() .filter(String::isNotBlank) .map(::nodeFromLine) val nodesById: Map<String,NodeFromLine> = allNodes.associateBy(NodeFromLine::id) val parentsAndChildren: Map<String,List<NodeFromLine?>> = createParentChildRelationships(nodesById) val allChildren = parentsAndChildren.values.flatten().filterNotNull() val rootId: String = parentsAndChildren.keys.minus(allChildren.map(NodeFromLine::id)).first() //createTree val rootNodeFrom = nodesById.getValue(rootId) val rootNode = createTree(rootNodeFrom, nodesById) val unbalanced = findUnbalanceNode(rootNode) val unbalancedParent = unbalanced.parent val otherWeight = unbalancedParent!!.children.minus(unbalanced).first().treeWeight() val difference = otherWeight - unbalanced.treeWeight() return Pair(rootNode.id,Pair(unbalanced.id, Math.abs(unbalanced.weight + difference))) } private tailrec fun findUnbalanceNode(node: Node): Node { val nodesByWeight = node.children.groupBy(Node::treeWeight) if (nodesByWeight.size == 1) { return node } else { for (childNodes: List<Node> in nodesByWeight.values) { if (childNodes.size == 1) { return findUnbalanceNode(childNodes[0]) } } } throw IllegalStateException() } private fun createTree(rootNfl: NodeFromLine, nodesById: Map<String,NodeFromLine>) : Node { fun createSubTree(nfl: NodeFromLine, parent: Node): Node { val node = Node(nfl.id, nfl.weight, parent = parent) node.children = nfl.childIds.map { childId -> createSubTree(nodesById.getValue(childId), node) } return node } val rootNode = Node(rootNfl.id, rootNfl.weight, parent = null) rootNode.children = rootNfl.childIds.map { childId -> createSubTree(nodesById.getValue(childId),rootNode) } return rootNode } private fun createParentChildRelationships(nodesById: Map<String,NodeFromLine>) : Map<String,List<NodeFromLine?>> { return nodesById.filter { (id,node) -> node.childIds.isNotEmpty() } .mapValues { (id,node) -> node.childIds.map(nodesById::get) } } private fun nodeFromLine(line: String) : NodeFromLine { //Sample Line: ugml (68) -> gyxo, ebii, jptl val id = line.subSequence(0,line.indexOf('(')).trim().toString() val weight = line.subSequence(line.indexOf('(') + 1, line.indexOf(')')).toString().toInt() val childIds : List<String> = if (line.contains('>')) { val childIdSection = line.subSequence(line.indexOf('>') + 1,line.length) childIdSection.split(",").map { s -> s.trim() }.toList() } else { listOf() } return NodeFromLine(id,weight,childIds) } fun main(args: Array<String>) { val input = MethodHandles.lookup().lookupClass().getResourceAsStream("/Day07Input.txt").bufferedReader().readText() println(solve(input)) }
0
Kotlin
0
0
16ce3c9d6310b5faec06ff580bccabc7270c53a8
3,505
advent-of-code
MIT License
src/main/kotlin/days/Day10.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import xyz.hughjd.aocutils.Collections.stackOf import xyz.hughjd.aocutils.Tuples.product class Day10 : Day(10) { val program = inputList.map { if (it == "noop") Noop() else { val parts = it.split(" ") AddX(v = parts[1].toInt()) } } override fun partOne(): Any { return CPU().run(program) .filter { it.first in listOf(20, 60, 100, 140, 180, 220) } .sumOf { it.product() } } override fun partTwo(): Any { return "\n${CRT().drawScreen(program)}" } data class CRT(private val pxHeight: Int = 6, private val pxWidth: Int = 40) { private val pxTotal: Int = pxHeight * pxWidth fun drawScreen(program: List<Instruction>): String { val states = CPU().run(program) return (0 until pxTotal).map { pixel -> val x = states[pixel].second val spritePixels = listOf(x - 1, x, x + 1) if (pixel % 40 in spritePixels) "#" else "." }.chunked(pxWidth).joinToString("\n") { it.joinToString("") } } } sealed class Instruction { abstract val cycles: Int abstract fun exec(): Instruction } data class Noop(override val cycles: Int = 1) : Instruction() { override fun exec() = copy(cycles = cycles - 1) } data class AddX(override val cycles: Int = 2, val v: Int) : Instruction() { override fun exec() = copy(cycles = cycles - 1) } // minor issue with this class is that because of the `takeWhile { !instructions.empty() }`, execution ends // before the program is done (because the stack is empty but the current instruction may have 1 or 2 cycles left) // workaround for now is adding as many extra Noops as the final instruction has cycles at the end which ensure the 'real' instructions get fully executed class CPU { fun run(program: List<Instruction>): List<Pair<Int, Int>> { val instructions = stackOf(program + List(program.last().cycles) { Noop() }) return generateSequence(Triple(1, 1, instructions.pop())) { (cycle, x, instruction) -> if (instruction.cycles == 1) { Triple(cycle + 1, runInstruction(instruction, x), instructions.pop()) } else { Triple(cycle + 1, x, instruction.exec()) } }.map { it.first to it.second }.takeWhile { !instructions.empty() }.toList() } private fun runInstruction(instruction: Instruction, x: Int): Int { return when (instruction) { is AddX -> x + instruction.v is Noop -> x } } } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
2,748
aoc-2022
Creative Commons Zero v1.0 Universal
kotlin/src/com/s13g/aoc/aoc2021/Day23.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 kotlin.math.max import kotlin.math.min /** * --- Day 23: Amphipod --- * https://adventofcode.com/2021/day/23 */ class Day23 : Solver { companion object { val podCost = mutableMapOf( "A" to 1, "B" to 10, "C" to 100, "D" to 1000 ) } override fun solve(lines: List<String>): Result { // These are taken from the input. val podsPartA = setOf( Pod("B", XY(3, 2)), Pod("A", XY(5, 2)), Pod("A", XY(7, 2)), Pod("D", XY(9, 2)), Pod("D", XY(3, 3)), Pod("C", XY(5, 3)), Pod("B", XY(7, 3)), Pod("C", XY(9, 3)) ) val podsPartB = setOf( Pod("B", XY(3, 2)), Pod("A", XY(5, 2)), Pod("A", XY(7, 2)), Pod("D", XY(9, 2)), Pod("D", XY(3, 3)), Pod("C", XY(5, 3)), Pod("B", XY(7, 3)), Pod("A", XY(9, 3)), Pod("D", XY(3, 4)), Pod("B", XY(5, 4)), Pod("A", XY(7, 4)), Pod("C", XY(9, 4)), Pod("D", XY(3, 5)), Pod("C", XY(5, 5)), Pod("B", XY(7, 5)), Pod("C", XY(9, 5)) ) val partA = cheapestWayCached(podsPartA, WorldData(false)) val partB = cheapestWayCached(podsPartB, WorldData(true)) return Result("$partA", "$partB") } // Memoization for the 'cheapestWay' function. private val cache = mutableMapOf<Set<Pod>, Int>() private fun cheapestWayCached(pods: Set<Pod>, world: WorldData): Int { if (cache.containsKey(pods)) return cache[pods]!! val result = cheapestWay(pods, world) cache[pods] = result return result } private fun cheapestWay(pods: Set<Pod>, world: WorldData): Int { val state = State(pods, world) if (state.isDone()) { return 0 } // Sort options by cost. If no options exist, return immediately. val options = state.genNextSteps().sortedBy { it.second } if (options.isEmpty()) return Int.MAX_VALUE var cheapestCost = Int.MAX_VALUE for (option in options) { // Do not process if the cost for this step is higher than processing the // tail. if (option.second >= cheapestCost) continue val cost = cheapestWayCached(option.first.pods, world) if (cost != Int.MAX_VALUE) { val totalCost = cost + option.second cheapestCost = min(cheapestCost, totalCost) } } return cheapestCost } private data class State(val pods: Set<Pod>, val world: WorldData) { fun genNextSteps(): Set<Pair<State, Int>> { if (isDone()) error("Should never be called") val results = mutableSetOf<Pair<State, Int>>() // For each pod, figure out all the places it can go. for (pod in pods) { // The pod has already moved into the hallways it now needs to find its // way to its room. if (pod.pos.y == 1) { // First check of the room the pod needs to go to is empty or only // occupied by the correct pod. if (isRoomReadyToEnter(pod.id)) { // Second, check if the way is clear to enter the room val goalX = world.horLocForType(pod.id) var clearToGo = true var movesToRoom = 0 for (x in min(goalX, pod.pos.x)..max(goalX, pod.pos.x)) { val tile = get(x, 1) if (tile != "." && x != pod.pos.x) { clearToGo = false break } movesToRoom++ } if (clearToGo) { // What's the lowest slot in the room that's available... for (y in world.vertLocsForRooms()) { if (isEmpty(goalX, y)) { val newState = this.newState(pod, Pod(pod.id, XY(goalX, y), true)) results.add(Pair(newState, (movesToRoom) * podCost[pod.id]!!)) break } movesToRoom++ } } } } } // Prefer moves that bring pods into their rooms. No need to eval other // options, so return early. This will speed up things significantly. if (results.isNotEmpty()) return results for (pod in pods) { // If the pod has not moved (aka is still in the room) and it can move // up... if (!pod.moved && isEmpty(pod.pos.x, pod.pos.y - 1)) { val y = 1 var x = pod.pos.x var moves = pod.pos.y - 1 // Check left way while (get(x, y) == ".") { if (x != 3 && x != 5 && x != 7 && x != 9) { val newState = this.newState(pod, Pod(pod.id, XY(x, y), true)) results.add(Pair(newState, moves * podCost[pod.id]!!)) } moves++ x-- } x = pod.pos.x moves = pod.pos.y - 1 // Check right way while (get(x, y) == ".") { if (x != 3 && x != 5 && x != 7 && x != 9) { val newState = this.newState(pod, Pod(pod.id, XY(x, y), true)) results.add(Pair(newState, moves * podCost[pod.id]!!)) } moves++ x++ } } } return results } private fun newState(oldPod: Pod, replacePod: Pod): State { val newState = pods.filter { it != oldPod }.toMutableSet() newState.add(replacePod) return State(newState, world) } fun isDone() = world .podIds.sumBy { podID -> world.roomLocations(podID) .count { loc -> get(loc.x, loc.y) != podID } } == 0 private fun get(x: Int, y: Int): String { val pos = XY(x, y) return pods.firstOrNull { it.pos == pos }?.id ?: world.tileTypes[pos]!! } private fun isRoomReadyToEnter(podId: String): Boolean { return world.roomLocations(podId).map { get(it.x, it.y) } .count { it != podId && it != "." } == 0 } private fun isEmpty(x: Int, y: Int): Boolean { val pos = XY(x, y) return pods.count { it.pos == pos } == 0 && world.tileTypes[pos] != "#" } } private data class XY(val x: Int, val y: Int) private data class Pod( val id: String, val pos: XY, val moved: Boolean = false ) private class WorldData(val partB: Boolean) { val podIds = listOf("A", "B", "C", "D") private val locsForRoom = podIds.associateWith { genLocsForRoom(it) } val tileTypes = genTileTypes() private fun genTileTypes(): Map<XY, String> { val result = mutableMapOf<XY, String>() for (y in 0..(if (partB) 6 else 4)) { for (x in 0..12) { val loc = XY(x, y) result[loc] = tileType(loc) } } return result } private fun tileType(pos: XY): String { if (pos in locsForRoom["A"]!!) return "." if (pos in locsForRoom["B"]!!) return "." if (pos in locsForRoom["C"]!!) return "." if (pos in locsForRoom["D"]!!) return "." if (pos.y == 1 && pos.x >= 1 && pos.x <= 11) return "." return "#" } fun horLocForType(podId: String): Int { return when (podId) { "A" -> 3 "B" -> 5 "C" -> 7 "D" -> 9 else -> { error("Unknown pod ID: $podId") } } } fun roomLocations(podId: String): List<XY> { return locsForRoom[podId]!! } fun vertLocsForRooms() = if (partB) { listOf(2, 3, 4, 5) } else { listOf(2, 3) } private fun genLocsForRoom(podId: String): List<XY> { val x = horLocForType(podId) return vertLocsForRooms().map { XY(x, it) } } } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
7,615
euler
Apache License 2.0
src/main/kotlin/fr/pturpin/coursera/dynprog/ArithmeticExpression.kt
TurpIF
159,055,822
false
null
package fr.pturpin.coursera.dynprog class ArithmeticExpression(private val strExpression: String) { private val cache = ArrayList<MutableList<MinMaxExpression?>>(strExpression.length) fun getMaximumValue(): Long { clearCache() return computeCachedMaximumValue(0, strExpression.length).maxExpression } private fun clearCache() { cache.clear() for (i in 0..strExpression.length) { val elements = ArrayList<MinMaxExpression?>(strExpression.length) for (j in 0..strExpression.length) { elements.add(null) } cache.add(elements) } } private fun computeCachedMaximumValue(indexFrom: Int, indexTo: Int): MinMaxExpression { cache[indexFrom][indexTo]?.let { return it } val result = computeMaximumValue(indexFrom, indexTo) cache[indexFrom][indexTo] = result return result } private fun computeMaximumValue(indexFrom: Int, indexTo: Int): MinMaxExpression { if (indexFrom == indexTo - 1) { val strNumber = strExpression[indexFrom] val value = strNumber.toLong() - '0'.toLong() return MinMaxExpression(value, value) } var minimum = Long.MAX_VALUE var maximum = Long.MIN_VALUE getSplitExpressions(indexFrom, indexTo) .flatMap { computeCandidateValues(it) } .forEach { candidate -> if (candidate >= maximum) { maximum = candidate } if (candidate <= minimum) { minimum = candidate } } return MinMaxExpression(minimum, maximum) } private fun computeCandidateValues(splitExpression: SplitExpression): Sequence<Long> { val leftMinMax = computeCachedMaximumValue(splitExpression.leftFrom, splitExpression.leftTo) val rightMinMax = computeCachedMaximumValue(splitExpression.rightFrom, splitExpression.rightTo) return sequenceOf( evaluate(splitExpression.operator, leftMinMax.minExpression, rightMinMax.minExpression), evaluate(splitExpression.operator, leftMinMax.maxExpression, rightMinMax.minExpression), evaluate(splitExpression.operator, leftMinMax.minExpression, rightMinMax.maxExpression), evaluate(splitExpression.operator, leftMinMax.maxExpression, rightMinMax.maxExpression)) } private fun evaluate(operator: Char, left: Long, right: Long): Long { when (operator) { '+' -> return left + right '-' -> return left - right '*' -> return left * right } throw UnsupportedOperationException() } private fun getSplitExpressions(indexFrom: Int, indexTo: Int): Sequence<SplitExpression> { return (indexFrom + 1 until indexTo).step(2) .asSequence() .map { SplitExpression( indexFrom, it, it + 1, indexTo, strExpression[it] ) } } private data class SplitExpression( val leftFrom: Int, val leftTo: Int, val rightFrom: Int, val rightTo: Int, val operator: Char) private data class MinMaxExpression( val minExpression: Long, val maxExpression: Long) } fun main(args: Array<String>) { val expression = readLine()!! val arithmeticExpression = ArithmeticExpression(expression) val maximumValue = arithmeticExpression.getMaximumValue() print(maximumValue) }
0
Kotlin
0
0
86860f8214f9d4ced7e052e008b91a5232830ea0
3,653
coursera-algo-toolbox
MIT License
2021/14/kotlin/solve.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 val lines = File(args[0]).readLines() val polymers = lines[0] val rules = lines.slice(2..lines.lastIndex).map { it.split(" -> ") }.associate { it[0] to it[1] } var freq = hashMapOf<String,Long>() polymers.windowed(2).forEach { freq.set(it, 1 + freq.getOrDefault(it, 0)) } freq.set("_" + polymers.substring(0,1), 1 ); freq.set(polymers.substring( polymers.lastIndex, polymers.lastIndex+1) + "_", 1 ); // part 1: 1..10, part 2: 1..40 (1..40).forEach { var freq2 = hashMapOf<String,Long>() freq.forEach { val k = it.key val v = it.value; if (rules.containsKey(k)) { val (a,c) = it.key.windowed(1) val b = rules.getValue(k) freq2[a+b] = v + freq2.getOrDefault(a+b, 0) freq2[b+c] = v + freq2.getOrDefault(b+c, 0) } else { freq2.set(k, v) } } freq = freq2 } var cfreq = hashMapOf<String,Long>() freq.forEach { tok -> tok.key.windowed(1).forEach { c -> cfreq.put(c, tok.value + cfreq.getOrElse(c, { 0 })) } } cfreq.remove("_") val cfreqvals: List<Long> = cfreq.map { it.value / 2 } println( cfreqvals.maxOrNull()!! - cfreqvals.minOrNull()!! )
0
Raku
1
5
ca0555efc60176938a857990b4d95a298e32f48a
1,201
advent-of-code
Creative Commons Zero v1.0 Universal
src/Day03.kt
Jaavv
571,865,629
false
{"Kotlin": 14896}
// https://adventofcode.com/2022/day/3 fun main() { val input = readInput("Day03") val testinput = readInput("Day03_test") println(day03part1(input)) //7691 println(day03part2(input)) //2508 } val lowerPriority = ('a'..'z').mapIndexed { index, c -> c to index + 1 }.toMap() val upperPriority = ('A'..'Z').mapIndexed { index, c -> c to index + 27 }.toMap() val priority = lowerPriority + upperPriority fun day03part1(input: List<String>): Int { return input.sumOf { item -> priority.getValue( item.substring(0, item.length / 2).first { it in item.substring(item.length/2)} ) } } fun day03part2(input: List<String>): Int { return input .windowed(3, 3) .sumOf { rucksacks -> priority.getValue( rucksacks[0].first { it in rucksacks[1] && it in rucksacks[2] } ) } }
0
Kotlin
0
0
5ef23a16d13218cb1169e969f1633f548fdf5b3b
884
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountSortedVowelStrings.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 /** * Count Sorted Vowel Strings. * @see <a href="https://leetcode.com/problems/count-sorted-vowel-strings">Source</a> */ fun interface CountSortedVowelStrings { operator fun invoke(n: Int): Int } private const val VOWEL_COUNT = 5 /** * Approach 1: Brute Force Using Backtracking. * Time Complexity : O(n5). * Space Complexity: O(n). */ class CountSortedVowelBruteForce : CountSortedVowelStrings { override operator fun invoke(n: Int): Int { return countVowelStringUtil(n, 1) } private fun countVowelStringUtil(n: Int, vowels: Int): Int { if (n == 0) return 1 var result = 0 for (i in vowels..VOWEL_COUNT) { result += countVowelStringUtil(n - 1, i) } return result } } /** * Approach 2: Decoding the Pattern, Using Recursion. * Time Complexity : O(n5). * Space Complexity: O(n). */ class CountSortedVowelRecursion : CountSortedVowelStrings { override operator fun invoke(n: Int): Int { return countVowelStringUtil(n, VOWEL_COUNT) } private fun countVowelStringUtil(n: Int, vowels: Int): Int { if (n == 1) return vowels return if (vowels == 1) { 1 } else { countVowelStringUtil(n - 1, vowels) + countVowelStringUtil(n, vowels - 1) } } } /** * Approach 3: Using Recursion + Memoization, Top Down Dynamic Programming. * Time Complexity : O(n). * Space Complexity: O(n). */ class CountSortedVowelTopDynamic : CountSortedVowelStrings { // Override the invoke operator function to calculate and return the count of sorted vowel strings override operator fun invoke(n: Int): Int { // Initialize a memoization array to store computed values for dynamic programming val memo = Array(n + 1) { IntArray(VOWEL_COUNT + 1) } // Call the helper function to perform the actual calculation using dynamic programming return countVowelStringUtil(n, VOWEL_COUNT, memo) } // Helper function to recursively calculate the count of sorted vowel strings private fun countVowelStringUtil(n: Int, vowels: Int, memo: Array<IntArray>): Int { // Base case: If n is 1, return the count of vowels if (n == 1) return vowels // Base case: If there is only 1 vowel, return 1 if (vowels == 1) return 1 // If the result for the current parameters is already computed, return it if (memo[n][vowels] != 0) return memo[n][vowels] // Calculate the result for the current state (length of string 'n' and remaining vowels 'vowels'). // Recursive call 1: Consider the case where a consonant is added to the end of the string. val resultConsonant = countVowelStringUtil(n - 1, vowels, memo) // Recursive call 2: Consider the case where a vowel is added to the end of the string. val resultVowel = countVowelStringUtil(n, vowels - 1, memo) // Combine the results of the two recursive calls to get the total count of sorted vowel strings. val res = resultConsonant + resultVowel // Store the computed result in the memoization array memo[n][vowels] = res // Return the final result return res } } class CountSortedVowelBottomUp : CountSortedVowelStrings { override operator fun invoke(n: Int): Int { val dp = Array(n + 1) { IntArray(VOWEL_COUNT + 1) } for (vowels in 1..VOWEL_COUNT) dp[1][vowels] = vowels for (nValue in 2..n) { dp[nValue][1] = 1 for (vowels in 2..VOWEL_COUNT) { dp[nValue][vowels] = dp[nValue][vowels - 1] + dp[nValue - 1][vowels] } } return dp[n][VOWEL_COUNT] } } /** * Approach 5: Math. * Time Complexity : O(1). * Space Complexity: O(1). */ class CountSortedVowelMath : CountSortedVowelStrings { override operator fun invoke(n: Int): Int { return (n + 4) * (n + 3) * (n + 2) * (n + 1) / DENOMINATOR } companion object { private const val DENOMINATOR = 24 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,698
kotlab
Apache License 2.0
src/main/kotlin/days/Day5.kt
hughjdavey
572,954,098
false
{"Kotlin": 61752}
package days import xyz.hughjd.aocutils.Collections.split import java.util.Stack class Day5 : Day(5) { private val inputs = inputList.split("") private val moves = getMoves(inputs[1]) override fun partOne(): Any { return moveStacks(this::move9000) } override fun partTwo(): Any { return moveStacks(this::move9001) } private fun moveStacks(moveFn: (move: Move, stacks: List<Stack<Char>>) -> Unit): String { val stacks = getStacks(inputs[0]) moves.forEach { moveFn(it, stacks) } return stacks.map(Stack<Char>::pop).joinToString("") } data class Move(val n: Int, val src: Int, val dest: Int) fun move9000(move: Move, stacks: List<Stack<Char>>) { (0 until move.n).forEach { stacks[move.dest - 1].push(stacks[move.src - 1].pop()) } } fun move9001(move: Move, stacks: List<Stack<Char>>) { val toMove = (0 until move.n).map { stacks[move.src - 1].pop() }.reversed() toMove.forEach { stacks[move.dest - 1].push(it) } } companion object { fun getStacks(stacksInput: List<String>): List<Stack<Char>> { val maxLen = stacksInput.maxBy { it.length }.length val range = (1..maxLen).step(4) val stacks = range.map { Stack<Char>() } return stacksInput.dropLast(1).foldRight(stacks) { elem, acc -> val cols = range.map { index -> getLetterOrNull(elem, index) } cols.forEachIndexed { index, c -> if (c != null) acc[index].push(c) } acc } } fun getMoves(movesInput: List<String>): List<Move> { return movesInput.map { move -> val matches = Regex(".+?(\\d+).+?(\\d+).+?(\\d+)").matchEntire(move)!!.groupValues.drop(1) matches.map { it.toInt() } }.map { Move(it[0], it[1], it[2]) } } private fun getLetterOrNull(str: String, index: Int): Char? { val char = str.getOrNull(index) return if (char == null) null else if (Character.isAlphabetic(char.code)) char else null } } }
0
Kotlin
0
2
65014f2872e5eb84a15df8e80284e43795e4c700
2,126
aoc-2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumOfRootToLeafBinaryNumbers.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 java.util.Deque import java.util.LinkedList /** * 1022. Sum of Root To Leaf Binary Numbers * @see <a href="https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/">Source</a> */ fun interface SumOfRootToLeafBinaryNumbers { operator fun invoke(root: TreeNode?): Int } class SumOfRootToLeafBinaryNumbersBitwise : SumOfRootToLeafBinaryNumbers { override fun invoke(root: TreeNode?): Int { var rootNode = root var rootToLeaf = 0 var currNumber: Int val stack: Deque<Pair<TreeNode?, Int>> = LinkedList() stack.push(rootNode to 0) while (stack.isNotEmpty()) { val treeNodeIntPair = stack.pop() rootNode = treeNodeIntPair.first currNumber = treeNodeIntPair.second if (rootNode != null) { currNumber = currNumber shl 1 or rootNode.value // if it's a leaf, update root-to-leaf sum if (rootNode.left == null && rootNode.right == null) { rootToLeaf += currNumber } else { stack.push(Pair(rootNode.right, currNumber)) stack.push(Pair(rootNode.left, currNumber)) } } } return rootToLeaf } } // Iterative Preorder Traversal class SumOfRootToLeafBinaryNumbersIPT : SumOfRootToLeafBinaryNumbers { override fun invoke(root: TreeNode?): Int { var rootToLeaf = 0 var currNumber: Int var treeNode = root val stack: Deque<Pair<TreeNode?, Int>> = LinkedList() stack.push(treeNode to 0) while (stack.isNotEmpty()) { val p = stack.pop() treeNode = p.first currNumber = p.second if (treeNode != null) { currNumber = currNumber shl 1 or treeNode.value // if it's a leaf, update root-to-leaf sum if (treeNode.left == null && treeNode.right == null) { rootToLeaf += currNumber } else { stack.push(treeNode.right to currNumber) stack.push(treeNode.left to currNumber) } } } return rootToLeaf } } // Recursive Preorder Traversal class SumOfRootToLeafBinaryNumbersRPT : SumOfRootToLeafBinaryNumbers { private var rootToLeaf = 0 override fun invoke(root: TreeNode?): Int { preorder(root, 0) return rootToLeaf } private fun preorder(node: TreeNode?, currNumber: Int) { var number = currNumber if (node != null) { number = number shl 1 or node.value // if it's a leaf, update root-to-leaf sum if (node.left == null && node.right == null) { rootToLeaf += number } preorder(node.left, number) preorder(node.right, number) } } } // Morris Preorder Traversal class SumOfRootToLeafBinaryNumbersMPT : SumOfRootToLeafBinaryNumbers { override fun invoke(root: TreeNode?): Int { var rootToLeaf = 0 var currNumber = 0 var steps: Int var predecessor: TreeNode? var treeNode = root while (treeNode != null) { // If there is a left child, // then compute the predecessor. // If there is no link predecessor.right = root --> set it. // If there is a link predecessor.right = root --> break it. if (treeNode.left != null) { // Predecessor node is one step to the left // and then to the right till you can. predecessor = treeNode.left steps = 1 while (predecessor!!.right != null && predecessor.right !== treeNode) { predecessor = predecessor.right ++steps } // Set link predecessor.right = root // and go to explore the left subtree if (predecessor.right == null) { currNumber = currNumber shl 1 or treeNode.value predecessor.right = treeNode treeNode = treeNode.left } else { // If you're on the leaf, update the sum if (predecessor.left == null) { rootToLeaf += currNumber } // This part of tree is explored, backtrack for (i in 0 until steps) { currNumber = currNumber shr 1 } predecessor.right = null treeNode = treeNode.right } } else { currNumber = currNumber shl 1 or treeNode.value // if you're on the leaf, update the sum if (treeNode.right == null) { rootToLeaf += currNumber } treeNode = treeNode.right } } return rootToLeaf } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,701
kotlab
Apache License 2.0
src/main/kotlin/graph/variation/ShortestMidPoint.kt
yx-z
106,589,674
false
null
package graph.variation import graph.core.Vertex import graph.core.WeightedEdge import graph.core.WeightedGraph import graph.core.dijkstra import util.max // given an undirected weighted graph, a starting point s, and another starting // point t, find a vertex v that minimize the total cost from s to v and t to v fun <V> WeightedGraph<V, Int>.shortestMidPoint(s: Vertex<V>, t: Vertex<V>): Int { // our strategy is: // distS = run a dijkstra from s, distT = run another dijkstra from t val (distS, _) = dijkstra(s) val (distT, _) = dijkstra(t) println(distS) println(distT) // find the min_v { max{ distS[v], distT[v] } } return vertices.map { max(distS[it]!!, distT[it]!!) }.min()!! } fun main(args: Array<String>) { val vertices = (0..4).map { Vertex(it) } val edges = setOf( WeightedEdge(vertices[0], vertices[1], weight = 3), WeightedEdge(vertices[0], vertices[3], weight = 1), WeightedEdge(vertices[1], vertices[2], weight = 1), WeightedEdge(vertices[2], vertices[3], weight = 2), WeightedEdge(vertices[2], vertices[4], weight = 3), WeightedEdge(vertices[3], vertices[4], weight = 1)) val graph = WeightedGraph(vertices, edges) println(graph.shortestMidPoint(vertices[0], vertices[4])) }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,227
AlgoKt
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RemoveDuplicateLetters.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import java.util.Stack /** * 316. Remove Duplicate Letters * @see <a href="https://leetcode.com/problems/remove-duplicate-letters">Source</a> */ fun interface RemoveDuplicateLetters { operator fun invoke(s: String): String } class RemoveDuplicateLettersSolution : RemoveDuplicateLetters { override fun invoke(s: String): String { val lastIndex = IntArray(ALPHABET_LETTERS_COUNT) for (i in s.indices) { lastIndex[s[i] - 'a'] = i // track the lastIndex of character presence } val seen = BooleanArray(ALPHABET_LETTERS_COUNT) // keep track seen val st: Stack<Int> = Stack() for (i in s.indices) { val curr: Int = s[i] - 'a' if (seen[curr]) continue // if seen continue as we need to pick one char only while (st.isNotEmpty() && st.peek() > curr && i < lastIndex[st.peek()]) { seen[st.pop()] = false // pop out and mark unseen } st.push(curr) // add into stack seen[curr] = true // mark seen } val sb = StringBuilder() while (st.isNotEmpty()) sb.append((st.pop() + 'a'.code).toChar()) return sb.reverse().toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,912
kotlab
Apache License 2.0
src/Day01.kt
Pixselve
572,907,486
false
{"Kotlin": 7404}
fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for (s in input) { if (s.isEmpty()) { max = current.coerceAtLeast(max) current = 0 continue } current += s.toInt() } return max } fun part2(input: List<String>): Int { val caloriesPerElf = mutableListOf<Int>(0) for (s in input) { if (s.isEmpty()) { caloriesPerElf.add(0) continue } caloriesPerElf[caloriesPerElf.lastIndex] += s.toInt() } // sort list caloriesPerElf.sortDescending() return caloriesPerElf[0] + caloriesPerElf[1] + caloriesPerElf[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
10e14393b8b6ee3f98dfd4c37e32ad81f9952533
1,032
advent-of-code-2022-kotlin
Apache License 2.0
src/main/java/leetcode/a167_twoSumInputSortArray_SIMPLE/Solution.kt
Laomedeia
122,696,571
true
{"Java": 801075, "Kotlin": 38473, "JavaScript": 8268}
package leetcode.a167_twoSumInputSortArray_SIMPLE /** * 两数之和 II - 输入有序数组 * 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明: 返回的下标值(index1 和 index2)不是从零开始的。 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。 示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。 */ class Solution { /** * 解题思路: * https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/solution/shuang-zhi-zhen-on-shi-jian-fu-za-du-by-cyc2018/ 使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。 如果两个指针指向元素的和 sum == targetsum==target,那么得到要求的结果; 如果 sum > targetsum>target,移动较大的元素,使 sumsum 变小一些; 如果 sum < targetsum<target,移动较小的元素,使 sumsum 变大一些。 数组中的元素最多遍历一次,时间复杂度为 O(N)O(N)。只使用了两个额外变量,空间复杂度为 O(1)O(1)。 */ fun twoSum(numbers: IntArray, target: Int): IntArray { if (numbers == null) return intArrayOf() var i = 0 var j = numbers.size - 1 while (i < j) { var sum = numbers[i] + numbers[j]; if (sum == target) { return intArrayOf(i + 1, j + 1) } else if (sum < target) { i++ } else { j-- } } return intArrayOf() } }
0
Java
0
0
0dcd8438e0846493ced9c1294ce686bac34c8614
1,900
Java8InAction
MIT License
src/main/kotlin/g1901_2000/s1938_maximum_genetic_difference_query/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1901_2000.s1938_maximum_genetic_difference_query // #Hard #Array #Bit_Manipulation #Trie #2023_06_20_Time_855_ms_(100.00%)_Space_84.4_MB_(100.00%) class Solution { fun maxGeneticDifference(parents: IntArray, queries: Array<IntArray>): IntArray { val n = parents.size val fd = arrayOfNulls<IntArray>(n) for (i in 0 until n) { fill(parents, n, fd, i) } val ret = IntArray(queries.size) for (q in queries.indices) { var cur = queries[q][0] val value = queries[q][1] for (p in 30 downTo 0) { val msk = 1 shl p if (value and msk != cur and msk) { ret[q] = ret[q] or msk } else if (fd[cur]!![p] >= 0) { ret[q] = ret[q] or msk cur = fd[cur]!![p] } } } return ret } private fun fill(parents: IntArray, n: Int, fd: Array<IntArray?>, i: Int) { if (fd[i] == null) { fd[i] = IntArray(31) var a = parents[i] if (a >= 0) { fill(parents, n, fd, a) } for (p in 30 downTo 0) { if (a == -1) { fd[i]!![p] = -1 } else { if (i and (1 shl p) == a and (1 shl p)) { fd[i]!![p] = fd[a]!![p] } else { fd[i]!![p] = a a = fd[a]!![p] } } } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,597
LeetCode-in-Kotlin
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Types.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import org.junit.jupiter.api.Test import kotlin.math.abs import kotlin.test.assertEquals import kotlin.test.assertTrue interface Coordinate : Comparable<Coordinate> { val x: Int val y: Int override fun compareTo(other: Coordinate): Int { return compareValuesBy(this, other, { it.y }, { it.x }) } fun distanceTo(other: Coordinate): Int { return abs(other.x - x) + abs(other.y - y) } fun isAdjacentTo(other: Point): Boolean { return (abs(other.x - this.x) <= 1) and (abs(other.y - this.y) <= 1) } } data class Point(override val x: Int, override val y: Int) : Coordinate { override fun toString(): String = "($x,$y)" fun north() = Point(x, y - 1) fun east() = Point(x + 1, y) fun south() = Point(x, y + 1) fun west() = Point(x - 1, y) fun edges(): List<Point> { return listOf( // Above Point(x - 1, y - 1), Point(x, y - 1), Point(x + 1, y - 1), // Side Point(x - 1, y), Point(x + 1, y), // Below Point(x - 1, y + 1), Point(x, y + 1), Point(x + 1, y + 1), ) } @JvmName("containedInStrings") infix fun containedIn(map: List<String>): Boolean { return map.getOrNull(y)?.getOrNull(x) != null } infix fun containedIn(map: List<List<*>>): Boolean { return map.getOrNull(y)?.getOrNull(x) != null } fun move(steps: Int, direction: Direction): Point { return when (direction) { Direction.N -> copy(y = y - steps) Direction.E -> copy(x = x + steps) Direction.S -> copy(y = y + steps) Direction.W -> copy(x = x - steps) } } } enum class Direction { N, E, S, W; val opposite get() = when (this) { N -> S E -> W S -> N W -> E } } class PointTest { @Test fun testEdgesAndAdjacent() { val center = Point(0, 0) assertTrue(center.edges().all { edge -> edge.isAdjacentTo(center) }) } @Test fun testDistance() { val zero = Point(0, 0) assertEquals(0, zero.distanceTo(zero)) assertEquals(1, zero.distanceTo(Point(1, 0))) assertEquals(1, zero.distanceTo(Point(0, 1))) assertEquals(1, zero.distanceTo(Point(-1, 0))) assertEquals(1, zero.distanceTo(Point(0, -1))) assertEquals(2, zero.distanceTo(Point(1, 1))) } @Test fun testEdgesUnique() { assertEquals(8, Point(0, 0).edges().distinct().size) } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,647
aoc
Apache License 2.0
src/util/Grid.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package util import kotlin.math.max import kotlin.math.min typealias Pos = Pair<Int, Int> typealias PosL = Pair<Long, Long> operator fun Pos.plus(b: Pos) = this.first + b.first to this.second + b.second operator fun PosL.minus(b: PosL) = this.first + b.first to this.second + b.second operator fun Pos.times(b: Int) = this.first * b to this.second * b operator fun PosL.times(b: Long) = this.first * b to this.second * b fun Pos.inverse() = this.second to this.first fun Pos.toLong() = this.first.toLong() to this.second.toLong() fun Pos.neighbors(): List<Pos> { return Cardinal.entries.map { it.of(this) } + Cardinal.diagonals.map { (one, two) -> one.of(two.of(this)) } } fun Pos.neighborsManhattan(): List<Pos> { return Cardinal.entries.map { it.of(this) } } fun <T> List<List<T>>.transpose(): List<List<T>> { return List(first().size) { rowIdx -> List(size) { colIdx -> this[colIdx][rowIdx] } } } operator fun <T> List<List<T>>.get(p: Pos) = this[p.first][p.second] operator fun <T> MutableList<MutableList<T>>.set(p: Pos, value: T) { this[p.first][p.second] = value } fun <T> getRow(grid: List<List<T>>, rowIdx: Int) = grid[rowIdx] fun <T> getCol(grid: List<List<T>>, colIdx: Int) = grid.map { it[colIdx] } fun <T> getRange(grid: List<List<T>>, startRow: Int, startCol: Int, stopRow: Int, stopCol: Int) : List<T> { return (startRow..stopRow).map { x -> (startCol..stopCol).map { y -> grid[x to y] } }.flatten() } enum class Cardinal(val relativePos: Pos) { NORTH(-1 to 0), EAST(0 to 1), SOUTH(1 to 0), WEST(0 to -1); companion object { val diagonals = listOf(NORTH to WEST, NORTH to EAST, SOUTH to WEST, SOUTH to EAST) } fun of(pos: Pair<Int, Int>): Pair<Int, Int> { return pos + relativePos } fun turn(direction: Turn): Cardinal { return when (direction) { Turn.RIGHT -> Cardinal.entries[(this.ordinal + 1) % 4] Turn.LEFT -> Cardinal.entries[(this.ordinal - 1).mod(4)] } } } enum class Turn { LEFT, RIGHT; companion object { fun fromChar(c: Char): Turn { return when (c) { 'L' -> LEFT 'R' -> RIGHT else -> error("$c is not a turn indicator") } } } } enum class Direction { UP, RIGHT, DOWN, LEFT; companion object { fun fromChar(c: Char): Direction { return when (c) { 'R' -> RIGHT 'U' -> UP 'D' -> DOWN 'L' -> LEFT else -> error("$c is not a direction") } } } fun move(pos: Pair<Int, Int>): Pair<Int, Int> { val (fromX, fromY) = pos return when (this) { UP -> fromX to fromY + 1 DOWN -> fromX to fromY - 1 LEFT -> fromX - 1 to fromY RIGHT -> fromX + 1 to fromY } } fun moveL(pos: Pair<Long, Long>): Pair<Long, Long> { val (fromX, fromY) = pos return when (this) { UP -> fromX to fromY + 1 DOWN -> fromX to fromY - 1 LEFT -> fromX - 1 to fromY RIGHT -> fromX + 1 to fromY } } } fun minMax(gridPositions: Set<Pos>): Pair<Pos, Pos> { val minRow = gridPositions.minOf { it.first } val maxRow = gridPositions.maxOf { it.first } val minCol = gridPositions.minOf { it.second } val maxCol = gridPositions.maxOf { it.second } return (minRow to minCol) to (maxRow to maxCol) } fun printGrid(positions: Map<Pos, String>, width: Int = 1) { println("number positions in grid: ${positions.size}") val (min, max) = minMax(positions.keys) val (minRow, minCol) = min val (maxRow, maxCol) = max val result = List(maxRow - minRow + 1) { rowIdx -> List(maxCol - minCol + 1) { colIdx -> if (rowIdx + minRow to colIdx + minCol in positions) { positions[rowIdx + minRow to colIdx + minCol] } else { " ".repeat(width) } }.joinToString("") } println(result.joinToString("\n")) println("------------------------END GRID------------------------") } fun <T> printMatrix(grid: List<List<T>>, toString: (T) -> String) { grid.map { row -> val output = row.joinToString(separator = "") { item -> toString(item) } println(output) } } fun <T> getNeighbors(grid: List<List<T>>, pos: Pos): List<T> { val minRow = max(0, pos.first - 1) val maxRow = min(pos.first + 1, grid.size - 1) val minCol = max(0, pos.second - 1) val maxCol = min(pos.second + 1, grid.first().size - 1) return (minRow..maxRow).flatMap { row -> (minCol..maxCol).mapNotNull { col -> if (row to col != pos) grid[row to col] else null } } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
4,903
advent-of-code
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day21.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 21: Monkey Math --- * https://adventofcode.com/2022/day/21 */ class Day21 : Solver { override fun solve(lines: List<String>): Result { val monkeysA = parse(lines) settle(monkeysA) val partA = monkeysA["root"]!!.value val monkeysB = parse(lines).toMutableMap() // Make it unsolvable by making it a dependency on itself. monkeysB["humn"] = Monkey("humn", Long.MAX_VALUE, "humn", "+", "humn") settle(monkeysB) // Figure out which side is solved and which one has HUMN in it. val rootLhs = monkeysB["root"]!!.lhsId val rootRhs = monkeysB["root"]!!.rhsId var solveFor = if (monkeysB[rootLhs]!!.isSolved()) monkeysB[rootLhs]!!.value else monkeysB[rootRhs]!!.value var toSolve = if (monkeysB[rootLhs]!!.isSolved()) monkeysB[rootRhs]!! else monkeysB[rootLhs]!! while (toSolve.id != "humn") { val lhs = monkeysB[toSolve.lhsId]!! val rhs = monkeysB[toSolve.rhsId]!! // If RHS is solved, simply reverse operation for the "solveFor" side. // If LHS is solved, we need to handle non-commutative operations - and /. if (rhs.isSolved()) { solveFor = doReverseOp(solveFor, toSolve.op, rhs.value) toSolve = lhs } else if (lhs.isSolved()) { if (toSolve.op in setOf("+", "*")) { solveFor = doReverseOp(solveFor, toSolve.op, lhs.value) toSolve = rhs } else if (toSolve.op == "-") { solveFor = (solveFor - lhs.value) * -1 toSolve = rhs } else if (toSolve.op == "/") { // If this is a division but the unsolved part is the divisor, we have // to swap things around. val newSolveFor = lhs.value lhs.value = solveFor toSolve.op = reverseOp(toSolve.op) solveFor = newSolveFor } else throw RuntimeException("Unknown operation '${toSolve.op}'") } else throw RuntimeException("Neither side can be solved.") // println("$solveFor = ${buildGraph(toSolve.id, monkeysB)}") } return resultFrom(partA, solveFor) } private fun doReverseOp(lhs: Long, op: String, rhs: Long): Long { return when (op) { "+" -> lhs - rhs "*" -> lhs / rhs "-" -> lhs + rhs "/" -> lhs * rhs else -> throw RuntimeException("Waaa") } } private fun reverseOp(op: String): String { return when (op) { "+" -> "-" "*" -> "/" "-" -> "-" "/" -> "/" else -> throw RuntimeException("Unknown OP '$op'") } } private fun settle(monkeys: Map<String, Monkey>) { var complete = false while (!complete) { complete = true for (m in monkeys.values) { if (!m.isSolved() && monkeys[m.lhsId]!!.isSolved() && monkeys[m.rhsId]!!.isSolved() ) { val lhs = monkeys[m.lhsId]!!.value val rhs = monkeys[m.rhsId]!!.value m.value = when (m.op) { "+" -> lhs + rhs "*" -> lhs * rhs "-" -> lhs - rhs "/" -> lhs / rhs else -> throw RuntimeException("Waaa") } complete = false } } } } private fun parse(lines: List<String>) = lines.map { line -> val split = line.split(":") val id = split[0] var value = Long.MAX_VALUE var mathLeft = "" var op = "" var mathRight = "" val rhs = split[1].trim() try { value = rhs.toLong() } catch (ex: NumberFormatException) { val mathSplit = rhs.split(" ") mathLeft = mathSplit[0] op = mathSplit[1] mathRight = mathSplit[2] } Monkey(id, value, mathLeft, op, mathRight) }.associateBy { it.id }.toMap() private fun printGraph(id: String, monkeys: Map<String, Monkey>): String { if (id == "humn") return "HUMN" val m = monkeys[id]!! if (m.isSolved()) return m.value.toString() return "(${printGraph(m.lhsId, monkeys)} ${m.op} ${ printGraph( m.rhsId, monkeys ) })" } data class Monkey( val id: String, var value: Long, val lhsId: String = "", var op: String = "", val rhsId: String = "", ) { fun isSolved() = value != Long.MAX_VALUE } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
4,356
euler
Apache License 2.0
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day09.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwentyone import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.product import fr.outadoc.aoc.scaffold.readDayInput import kotlin.jvm.JvmInline class Day09 : Day<Int> { private companion object { const val MAX_HEIGHT = 9 } private val heightMap: HeightMap = readDayInput() .lineSequence() .map { line -> line.toList().map { it.digitToInt() } } .toList() .let { HeightMap(it) } @JvmInline private value class HeightMap(val map: List<List<Int>>) private data class Position(val x: Int, val y: Int) private val Position.surrounding: Set<Position> get() = setOf( copy(y = y - 1), copy(y = y + 1), copy(x = x - 1), copy(x = x + 1) ) private operator fun HeightMap.get(pos: Position): Int { return heightMap.map.getOrNull(pos.y)?.getOrNull(pos.x) ?: MAX_HEIGHT } private tailrec fun HeightMap.getBasinAt(knownBasin: Set<Position>): Set<Position> { val adjacent = knownBasin .flatMap { it.surrounding } .toSet() .minus(knownBasin) .filterNot { pos -> this[pos] == MAX_HEIGHT } .toSet() return when { adjacent.isEmpty() -> knownBasin else -> getBasinAt(knownBasin + adjacent) } } private fun HeightMap.findLowPoints(): List<Position> = map.flatMapIndexed { i, layer -> layer.mapIndexed { j, currentLocation -> Position(x = j, y = i).takeIf { currentPos -> currentPos.surrounding .map { pos -> heightMap[pos] } .all { pos -> pos > currentLocation } } }.filterNotNull() } override fun step1() = heightMap.findLowPoints().sumOf { pos -> 1 + heightMap[pos] } override fun step2() = heightMap .findLowPoints() .map { lowPoint -> heightMap.getBasinAt(setOf(lowPoint)).size } .sortedDescending() .take(3) .product() override val expectedStep1 = 577 override val expectedStep2 = 1_069_200 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,247
adventofcode
Apache License 2.0
src/Day10.kt
hottendo
572,708,982
false
{"Kotlin": 41152}
private class Tube(val cycles: IntArray) { var cycleCount = 0 var register = 1 var signalStrength = 0 val screen = CharArray(240) { '.' } fun calculateSignalStrength(): Int { var signalStrength = 0 if (cycleCount in cycles) { signalStrength = register * cycleCount } return signalStrength } fun isPixelLit(): Char { val xPosition = cycleCount.mod(40) if (xPosition >= (register - 1) && xPosition <= (register + 1)) { return '#' } return '.' } fun runCrt(input: List<String>) { for (item in input) { val cmd = item.split(' ').first() val arg: Int if (cmd == "addx") { arg = item.split(' ').last().toInt() screen[cycleCount] = isPixelLit() cycleCount++ screen[cycleCount] = isPixelLit() register += arg } else if (cmd == "noop") { screen[cycleCount] = isPixelLit() } cycleCount++ } } fun run(input: List<String>) { for (item in input) { val cmd = item.split(' ').first() val arg: Int if (cmd == "addx") { arg = item.split(' ').last().toInt() cycleCount++ signalStrength += calculateSignalStrength() cycleCount++ signalStrength += calculateSignalStrength() register += arg } else if (cmd == "noop") { cycleCount++ signalStrength += calculateSignalStrength() } } } } fun main() { fun check(): Int { return 0 } fun part1(input: List<String>): Int { val score: Int val tube = Tube(intArrayOf(20, 60, 100, 140, 180, 220)) tube.run(input) score = tube.signalStrength return score } fun part2(input: List<String>): Int { val score = 0 val tube = Tube(intArrayOf(20, 60, 100, 140, 180, 220)) tube.runCrt(input) var i = 0 for (y in 0 until 6) { for (x in 0 until 40) { print(tube.screen[i++]) } println() } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) // println("Part 1 (Test): ${part1(testInput)}") // check(part2(testInput) == 1) // part2(testInput) // println("Part 2 (Test): ${part2(testInput)}") // val testInput2 = readInput("Day09_2_test") // check(part2(testInput2) == 36) //println("Part 2.1 (Test): ${part2(testInput2)}") val input = readInput("Day10") // println("Part 1 : ${part1(input)}") println("Part 2 : ${part2(input)}") }
0
Kotlin
0
0
a166014be8bf379dcb4012e1904e25610617c550
2,926
advent-of-code-2022
Apache License 2.0
day07/src/main/kotlin/ver_b.kt
jabbalaci
115,397,721
false
null
package b import java.io.File object Tree { private val nodes = mutableMapOf<String, Node>() fun add(node: Node) { this.nodes[node.name] = node } fun getNodeByName(name: String): Node? { return this.nodes.getOrDefault(name, null) } fun getAllNodes(): List<Node> { return this.nodes.values.toList() } fun setParents() { for (parent in getAllNodes()) { for (child in parent.getChildrenAsNodes()) { child.parent = parent } } } } data class Node(val name: String, val weight: Int) { var parent : Node? = null val children = mutableListOf<String>() var totalWeight = weight fun addChild(child: String) { this.children.add(child) } fun hasChildren(): Boolean { return this.children.size > 0 } fun getChildrenAsNodes(): List<Node> { val li = mutableListOf<Node>() for (name in children) { li.add(Tree.getNodeByName(name)!!) } return li } override fun toString() : String { val sb = StringBuilder() sb.append("%s (%d) -> ".format(this.name, this.totalWeight)) var cnt = 0 for (ch in this.children) { val node = Tree.getNodeByName(ch)!! if (cnt > 0) { sb.append(", ") } sb.append("%s (%d)".format(node.name, node.totalWeight)) ++cnt } return sb.toString() } } fun main(args: Array<String>) { // val fname = "example.txt" // val fname = "input.txt" File(fname).forEachLine { line -> val parts = line.split(Regex(" -> ")) if (parts.size == 1) { val (name, weight) = extractNameAndWeight(parts[0]) Tree.add(Node(name, weight)) } else { val left = parts[0] val (name, weight) = extractNameAndWeight(left) val parent = Node(name, weight) Tree.add(parent) val right = parts[1] val pieces = right.split(", ") pieces.forEach { prgName -> parent.addChild(prgName) } } } Tree.setParents() for (node in Tree.getAllNodes()) { val weight = node.weight var curr = node.parent while (curr != null) { curr.totalWeight += weight curr = curr.parent } } for (node in Tree.getAllNodes()) { if (node.hasChildren()) { val bag = node.getChildrenAsNodes().map { it.totalWeight }.toSet() if (bag.size > 1) { println(node) } } } println(Tree.getNodeByName("gozhrsf")?.weight) /* output: exrud (7086) -> hpziqqg (1381), abxglwt (1381), gozhrsf (1386), oqjqu (1381), vhkodl (1381) rbzmniw (74207) -> tespoy (7081), tirifqs (7081), exrud (7086) eqgvf (445226) -> wdbmakv (74202), zqamk (74202), hvecp (74202), rbzmniw (74207), jfofam (74202), tigvdj (74202) 762 gozhrsf 's total weight is 1386. If its total weight would be 1381, then the tree would be balanced. That is, it should be lighter with 5 units. gozhrsf 's own weight is 762, thus the answer is: 762 - 5 = 757 */ } fun extractNameAndWeight(s: String): Pair<String, Int> { val pieces = s.split(Regex("\\s+")) val name = pieces[0] val weight = pieces[1].substring(1, pieces[1].lastIndex).toInt() return Pair(name, weight) }
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
3,514
aoc2017
MIT License
plugin/src/main/kotlin/net/siggijons/gradle/graphuntangler/graph/GraphUntangler.kt
siggijons
615,653,143
false
{"Kotlin": 47826}
package net.siggijons.gradle.graphuntangler.graph import org.jgrapht.GraphMetrics import org.jgrapht.alg.TransitiveReduction import org.jgrapht.alg.scoring.BetweennessCentrality import org.jgrapht.graph.AbstractGraph import org.jgrapht.graph.AsSubgraph import org.jgrapht.graph.DirectedAcyclicGraph import org.jgrapht.traverse.TopologicalOrderIterator class GraphUntangler { /** * Calculate statistics for graph. */ fun nodeStatistics( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge> ): GraphStatistics { val betweennessCentrality = BetweennessCentrality(graph).scores val heights = heights(graph) val iterator = TopologicalOrderIterator(graph) val nodes = mutableListOf<NodeStatistics>() while (iterator.hasNext()) { val node = iterator.next() val descendants = graph.getDescendants(node) val ancestors = graph.getAncestors(node) val descendantsChangeRate = descendants.sumOf { it.changeRate ?: 0 } val ownershipInfo = NodeStatistics.OwnershipInfo( nonSelfOwnedDescendants = descendants.count { it.owner != node.owner }, uniqueNonSelfOwnedDescendants = descendants .filter { it.owner != node.owner } .distinctBy { it.owner } .count(), nonSelfOwnedAncestors = ancestors.count { it.owner != node.owner }, uniqueNonSelfOwnedAncestors = ancestors .filter { it.owner != node.owner } .distinctBy { it.owner } .count() ) val s = NodeStatistics( node = node, betweennessCentrality = requireNotNull(betweennessCentrality[node]) { "betweennessCentrality not found for $node" }, degree = graph.degreeOf(node), inDegree = graph.inDegreeOf(node), outDegree = graph.outDegreeOf(node), height = heights.heightMap[node] ?: -1, ancestors = ancestors.size, descendants = descendants.size, changeRate = node.changeRate ?: 0, descendantsChangeRate = descendantsChangeRate, ownershipInfo = ownershipInfo ) nodes.add(s) } return GraphStatistics( nodes = nodes ) } /** * Generate a graph that consists only of nodes that participate in the longest paths * across the graph. This can be useful when there are multiple longest paths in a graph. * The algorithm is naive and unproven. */ fun heightGraph( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge>, nodes: List<NodeStatistics> ): DirectedAcyclicGraph<DependencyNode, DependencyEdge> { val g = DirectedAcyclicGraph<DependencyNode, DependencyEdge>(DependencyEdge::class.java) val added = mutableSetOf<DependencyNode>() val byHeight = nodes.sortedByDescending { it.height }.groupBy { it.height } byHeight.forEach { (_, currentLevel) -> if (added.isEmpty()) { currentLevel.forEach { g.addVertex(it.node) added.add(it.node) } } else { val connectionsToPrevious = currentLevel.map { v -> v.node to added.filter { u -> graph.containsEdge(u, v.node) } }.filter { it.second.isNotEmpty() } added.clear() connectionsToPrevious.forEach { (u, vs) -> vs.forEach { g.addVertex(u) g.addEdge(it, u, DependencyEdge(label = "Height Neighbor")) added.add(u) } } } } return g } /** * Creates a Graph and [heightGraph] for each vertex in [graph] * @see [AsSubgraph] */ fun analyzeSubgraphs( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge> ): List<SubgraphDetails> { return graph.vertexSet().map { vertex -> val descendants = graph.getDescendants(vertex) val subgraph = AsSubgraph(graph, descendants + vertex) val dag = DirectedAcyclicGraph.createBuilder<DependencyNode, DependencyEdge>( DependencyEdge::class.java ).addGraph(subgraph).build() val dagStats = nodeStatistics(dag) val subgraphHeightGraph = heightGraph(dag, dagStats.nodes) SubgraphDetails( vertex = vertex, subgraph = subgraph, descendants = descendants, subgraphHeightGraph = subgraphHeightGraph ) } } /** * Creates a subgraph for every module, or vertex, in the graph that only includes * vertices that are either ancestors or descendants of the vertex, as well as the vertex * itself. * * This creates a representation that makes it possible to reason how a specific module * interacts with the rest of the graph and can help visualize the value captured by RTTD. * * Additionally a csv, isolated-subgraph-size.csv, is created capturing the size of each * subgraph for further analysis. * * @see [NodeStatistics.rebuiltTargetsByTransitiveDependencies] */ fun isolateSubgraphs( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge> ): List<IsolatedSubgraphDetails> { return graph.vertexSet().map { vertex -> val ancestors = graph.getAncestors(vertex) val descendants = graph.getDescendants(vertex) val builder = DirectedAcyclicGraph.createBuilder<DependencyNode, DependencyEdge>( DependencyEdge::class.java ) builder.addGraph(graph) val disconnected = graph.vertexSet() - ancestors - descendants - vertex disconnected.forEach { builder.removeVertex(it) } val isolatedDag = builder.build() @Suppress("UNCHECKED_CAST") val reducedDag = isolatedDag.clone() as AbstractGraph<DependencyNode, DependencyEdge> TransitiveReduction.INSTANCE.reduce(reducedDag) IsolatedSubgraphDetails( vertex = vertex, isolatedDag = isolatedDag, reducedDag = reducedDag, isolatedDagSize = isolatedDag.vertexSet().size, fullGraphSize = graph.vertexSet().size ) } } @Suppress("UNCHECKED_CAST") fun safeReduce( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge> ): AbstractGraph<DependencyNode, DependencyEdge> { val clone = graph.clone() as AbstractGraph<DependencyNode, DependencyEdge> TransitiveReduction.INSTANCE.reduce(clone) return clone } /** * Calculate the "height" of the dependency graph. * * This was thought to be equal to the graph diameter, but for some reasons the diameter * as calculated by [GraphMetrics.getDiameter] has tended to return 0 for dags. */ private fun heights( graph: DirectedAcyclicGraph<DependencyNode, DependencyEdge> ): Heights<DependencyNode> { val map = HeightMeasurer(graph = graph).calculateHeightMap() return Heights(map) } }
2
Kotlin
1
31
1e154a8eb0541192219dac33449c949857552731
7,540
graph-untangler-plugin
Apache License 2.0
Dynamic Programming/Longest Palindromic Subsequence/test/HiddenTests.kt
jetbrains-academy
515,621,972
false
{"Kotlin": 123026, "TeX": 51581, "Java": 3566, "Python": 1156, "CSS": 671}
import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import kotlin.math.max import kotlin.random.Random import kotlin.time.Duration.Companion.seconds class HiddenTests { companion object { private val rng = Random(239L) private const val MAX_LENGTH = 5000 private fun validate(s: String): Boolean { return s.length <= MAX_LENGTH && s.all { it.isLowerCase() } } private fun randomLetter(alphabet: Int) = (rng.nextInt(alphabet) + 'a'.code).toChar() private fun randomString(length: Int, alphabet: Int): String { return (1..length) .map { randomLetter(alphabet) } .joinToString("") } private fun getLengthOfLongest(s: String): Int { if (s.isEmpty()) { return 0 } val longest = Array(s.length) { IntArray(s.length) } for (i in s.indices) { longest[i][i] = 1 } for (left in s.length - 2 downTo 0) { val current = longest[left] val next = longest[left + 1] for (right in left + 1 until s.length) { current[right] = max(next[right], current[right - 1]) if (s[left] == s[right]) { current[right] = max(current[right], next[right - 1] + 2) } } } return longest[0][s.length - 1] } private fun isPalindrome(sequence: String): Boolean = sequence == sequence.reversed() private fun isSubsequence(sub: String, of: String): Boolean { if (sub.isEmpty()) { return true } var indexInSub = 0 for (c in of) { // indexInSub < sub.length if (sub[indexInSub] == c) { indexInSub++ if (indexInSub == sub.length) { return true } } } return false } private fun shorten(seq: String): String { val shortened = if (seq.length > 10) { seq.substring(0 until 4) + "..." + seq.substring(seq.length - 4) } else { seq } return "\"" + shortened + "\"" } } private fun testSingle(s: String, message: String, withTimeout: Boolean = true) { check(validate(s)) val found = runIfTimeout(withTimeout, 1.seconds, message) { findLongestPalindromicSubsequence(s).toString() } assertTrue(isPalindrome(found)) { "Test [$message]: not a palindrome found -- ${shorten(found)}" } assertTrue(isSubsequence(found, s)) { "Test [$message]: is not a subsequence found -- ${shorten(found)}" } val lengthOfLongest = getLengthOfLongest(s) assertTrue(lengthOfLongest <= found.length) { "Test [$message]: not the longest palindrome found -- ${ shorten( found ) }, there is one of length $lengthOfLongest" } assertTrue(lengthOfLongest == found.length) { "Test [$message]: something wrong happened, contact the course developers" } } @Test fun testAllBinaryUpTo10() = runTimeout(2.seconds, "All binary strings up to length of 10") { for (length in 1..10) { for (mask in 0 until (1 shl length)) { val input = buildString { for (index in 0 until length) { append((((mask shr index) and 1) + 'a'.code).toChar()) } } testSingle(input, "\"" + input + "\"", withTimeout = false) } } } @Test fun testAllTertiaryUpTo8() = runTimeout(2.seconds, "All strings consisting of 'a', 'b', and 'c', up to length 8") { var count = 1 for (length in 1..8) { count *= 3 for (mask in 0 until count) { val input = buildString { var current = mask for (index in 0 until length) { append((current % 3 + 'a'.code).toChar()) current /= 3 } } testSingle(input, "\"" + input + "\"", withTimeout = false) } } } @Test fun testEmpty() { testSingle("", "Empty string") } @ParameterizedTest @ValueSource(ints = [20, 50, 100, MAX_LENGTH - 1, MAX_LENGTH]) fun testSingleLetterAlphabet(length: Int) { testSingle("a".repeat(length), "Single letter repeated $length times") } @ParameterizedTest @ValueSource(ints = [2, 3, 4, 5, 6, 10, 26]) fun randomSmall(alphabet: Int) = runTimeout(2.seconds, "Random tests of length up to 50") { repeat(100) { val input = randomString(rng.nextInt(50) + 1, alphabet) testSingle(input, shorten(input), withTimeout = false) } } @ParameterizedTest @ValueSource(ints = [2, 3, 4, 5, 6, 10, 26]) fun randomMedium(alphabet: Int) = runTimeout(2.seconds, "Random tests of length up to 500") { repeat(10) { val input = randomString(rng.nextInt(400) + 101, alphabet) testSingle(input, shorten(input), withTimeout = false) } } @ParameterizedTest @ValueSource(ints = [2, 3, 4, 5, 6, 10, 26]) fun randomMax(alphabet: Int) { val input = randomString(MAX_LENGTH, alphabet) testSingle(input, "Random test of maximum length") } @ParameterizedTest @ValueSource(ints = [0, 1, 2, 3, 4, 5, 6]) fun testBigPalindromeMutated(mutations: Int) { val alphabet = 26 val input = randomString(MAX_LENGTH / 2, alphabet).let { it + if (rng.nextBoolean()) { it.reversed() } else { it.reversed().substring(1) } }.toCharArray() repeat(mutations) { val index = rng.nextInt(input.size) input[index] = randomLetter(alphabet) } testSingle(input.concatToString(), "Test with a big palindrome") } }
2
Kotlin
0
10
a278b09534954656175df39601059fc03bc53741
6,403
algo-challenges-in-kotlin
MIT License
leetcode/kotlin/find-all-anagrams-in-a-string.kt
PaiZuZe
629,690,446
false
null
class Solution { fun findAnagrams(s: String, p: String): List<Int> { if (p.length > s.length) { return listOf<Int>() } val pCharFrequencies = IntArray(26) { 0 } val sCharFrequencies = IntArray(26) { 0 } initCharFreqs(s, p, sCharFrequencies, pCharFrequencies) val resp = mutableListOf<Int>() for (i in 0 until (s.length - p.length)) { if (isAnagram(pCharFrequencies, sCharFrequencies)) { resp.add(i) } sCharFrequencies[s[i].toInt() - 'a'.toInt()]-- sCharFrequencies[s[i + p.length].toInt() - 'a'.toInt()]++ } if (isAnagram(pCharFrequencies, sCharFrequencies)) { resp.add(s.length - p.length) } return resp.toList() } private fun isAnagram(aCharFrequencies: IntArray, bCharFrequencies: IntArray): Boolean { for (i in aCharFrequencies.indices) { if (aCharFrequencies[i] != bCharFrequencies[i]) { return false } } return true } private fun initCharFreqs(s: String, p: String, sCharFrequencies: IntArray, pCharFrequencies: IntArray) { for (i in p.indices) { pCharFrequencies[p[i].toInt() - 'a'.toInt()]++ sCharFrequencies[s[i].toInt() - 'a'.toInt()]++ } } }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
1,360
interprep
MIT License
src/Day04.kt
chasegn
573,224,944
false
{"Kotlin": 29978}
/** * Day 04 for Advent of Code 2022 * https://adventofcode.com/2022/day/4 */ class Day04 : Day { override val inputFileName: String = "Day04" override val test1Expected: Int = 2 override val test2Expected: Int = 4 /** * Accepted solution: 644 */ override fun part1(input: List<String>): Int { var count = 0 for (assignment in input) { val ranges = makeRanges(assignment) if ((ranges.first.contains(ranges.second.first) && ranges.first.contains(ranges.second.last)) || (ranges.second.contains(ranges.first.first) && ranges.second.contains(ranges.first.last))) { count++ } } return count } /** * Accepted solution: 926 */ override fun part2(input: List<String>): Int { var count = 0 for (assignment in input) { val ranges = makeRanges(assignment) if ((ranges.first.contains(ranges.second.first) || ranges.first.contains(ranges.second.last)) || (ranges.second.contains(ranges.first.first) || ranges.second.contains(ranges.first.last))) { count++ } } return count } private fun makeRanges(input: String): Pair<IntRange, IntRange> { val pair = input.split(',') val splitPair = Pair(pair[0].split('-'), pair[1].split('-')) val left = splitPair.first[0].toInt()..splitPair.first[1].toInt() val right = splitPair.second[0].toInt()..splitPair.second[1].toInt() return Pair(left, right) } }
0
Kotlin
0
0
2b9a91f083a83aa474fad64f73758b363e8a7ad6
1,600
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day6.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days class Day6 : Day(6) { override fun partOne(): Any { return p1(inputList, 80) } fun p1(inputList: List<String>, days: Int): Long { val times = inputList[0].split(",").map { it.toInt() } val startPopulation = Population( age0 = times.count { it == 0 }.toLong(), age1 = times.count { it == 1 }.toLong(), age2 = times.count { it == 2 }.toLong(), age3 = times.count { it == 3 }.toLong(), age4 = times.count { it == 4 }.toLong(), age5 = times.count { it == 5 }.toLong(), age6 = times.count { it == 6 }.toLong(), age7 = times.count { it == 7 }.toLong(), age8 = times.count { it == 8 }.toLong(), ) return doNextDays(startPopulation, days).size } private fun doNextDays(population: Population, days: Int): Population { if (days == 0) { return population } return doNextDays(population.nextDay(), days - 1) } override fun partTwo(): Any { return p1(inputList, 256) } fun nextDay(timers: List<Int>): List<Int> { val amountOfNewBorns = timers.count { it == 0 } val updated = timers.map { if (it == 0) { 6 } else { it - 1 } } return updated + List(amountOfNewBorns) { 8 } } } data class Population( val age0: Long, val age1: Long, val age2: Long, val age3: Long, val age4: Long, val age5: Long, val age6: Long, val age7: Long, val age8: Long, ) { val size = age0 + age1 + age2 + age3 + age4 + age5 + age6 + age7 + age8 fun nextDay(): Population { return Population( age0 = age1, age1 = age2, age2 = age3, age3 = age4, age4 = age5, age5 = age6, age6 = age7 + age0, age7 = age8, age8 = age0, ) } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
2,009
aoc2021
Creative Commons Zero v1.0 Universal
day-25/src/main/kotlin/SeaCucumber.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
import kotlin.system.measureTimeMillis fun main() { val partOneMillis = measureTimeMillis { println("Part One Solution: ${partOne()}") } println("Part One Solved in: $partOneMillis ms") val partTwoMillis = measureTimeMillis { println("Part Two Solution: ${partTwo()}") } println("Part Two Solved in: $partTwoMillis ms") } private val EAST = ">" private val SOUTH = "v" private val EMPTY = "." private fun partOne(): Int { var lines = readInputLines() .map { line -> line.toCharArray().map { it.toString() } } var count = 1 while (true) { var moved = false val toChange = lines.toMutableList().map { it.toMutableList() } for (x in lines.indices) { for (y in lines[0].indices) { if (lines[x][y] == EAST) { if ((y + 1) in lines[0].indices) { if (lines[x][y + 1] == EMPTY) { moved = true toChange[x][y + 1] = EAST toChange[x][y] = EMPTY } } else if (lines[x][0] == EMPTY) { moved = true toChange[x][0] = EAST toChange[x][y] = EMPTY } } } } lines = toChange.toMutableList().map { it.toMutableList() } for (x in lines.indices) { for (y in lines[0].indices) { if (lines[x][y] == SOUTH) { if ((x + 1) in lines.indices) { if (lines[x + 1][y] == EMPTY) { moved = true toChange[x + 1][y] = SOUTH toChange[x][y] = EMPTY } } else if (lines[0][y] == EMPTY) { moved = true toChange[0][y] = SOUTH toChange[x][y] = EMPTY } } } } lines = toChange.toMutableList().map { it.toMutableList() } if (moved) count++ else break } return count } private fun partTwo(): Long { return -1 } private fun readInputLines(): List<String> { return {}::class.java.classLoader.getResource("input.txt")!! .readText() .split("\n") .filter { it.isNotBlank() } }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
2,445
aoc-2021
MIT License
Collections/Max min/src/Task.kt
diskostu
554,658,487
false
{"Kotlin": 36179}
// Return a customer who has placed the maximum amount of orders fun Shop.getCustomerWithMaxOrders(): Customer? = customers.maxByOrNull { it.orders.size } // Return the most expensive product that has been ordered by the given customer fun getMostExpensiveProductBy(customer: Customer): Product? = customer.orders.flatMap { it.products }.maxByOrNull { it.price } fun main() { // demo code to find the solutions val shop = createSampleShop() println("shop.getCustomerWithMaxOrders() = ${shop.getCustomerWithMaxOrders()}") val customer = shop.customers[0] val flatMap = customer.orders.flatMap { it.products } val mostExpensiveProduct = flatMap.maxByOrNull { it.price } println("maxByOrNull = $mostExpensiveProduct") } fun createSampleShop(): Shop { // create some sample entities val product1 = Product("product 1", 1.0) val product2 = Product("product 2", 2.0) val product3 = Product("product 3", 3.0) val product4 = Product("product 4", 4.0) val product5 = Product("product 4", 5.0) val order1 = Order(listOf(product1), false) val order2 = Order(listOf(product2, product3), false) val order3 = Order(listOf(product1, product3, product4), false) val customer1 = Customer( name = "custumer1", city = City("Berlin"), orders = listOf(order1, order3) ) val customer2 = Customer( name = "custumer2", city = City("Hamburg"), orders = listOf(order2) ) return Shop("myShop", listOf(customer1, customer2)) }
0
Kotlin
0
0
3cad6559e1add8d202e15501165e2aca0ee82168
1,548
Kotlin_Koans
MIT License
app/src/main/kotlin/advent/of/code/day04/Day04.kt
dbubenheim
321,117,765
false
null
package advent.of.code.day04 import advent.of.code.enumContains import advent.of.code.toURL import com.google.common.base.Splitter import java.io.File class Day04 { companion object { @JvmStatic fun passportProcessing(validator : (Map<String, Any>) -> Validator) : Long { val splitter = Splitter.on(" ").withKeyValueSeparator(":") val map : MutableMap<String, String> = mutableMapOf() var count = 0L File("day04/input-day04.txt".toURL()).forEachLine { line -> if (line.isBlank()) { val wrapper = validator(map) if (wrapper.isValid()) count++ map.clear() } else { map.putAll(splitter.split(line)) } } return count } @JvmStatic fun main(args: Array<String>) { println(passportProcessing(::ValidatorPart1)) println(passportProcessing(::ValidatorPart2)) } } } class ValidatorPart1(fields: Map<String, Any?>) : Validator { private val defaultMap = fields.withDefault { null } private val byr : String? by defaultMap // (Birth Year) private val iyr : String? by defaultMap // (Issue Year) private val eyr : String? by defaultMap // (Expiration Year) private val hgt : String? by defaultMap // (Height) private val hcl : String? by defaultMap // (Hair Color) private val ecl : String? by defaultMap // (Eye Color) private val pid : String? by defaultMap // (Passport ID) private val cid : String? by defaultMap // (Country ID) override fun isValid() = byr != null && iyr != null && eyr != null && hgt != null && hcl != null && ecl != null && pid != null } class ValidatorPart2(fields: Map<String, Any?>) : Validator { private val defaultMap = fields.withDefault { null } private val byr : String? by defaultMap // (Birth Year) private val iyr : String? by defaultMap // (Issue Year) private val eyr : String? by defaultMap // (Expiration Year) private val hgt : String? by defaultMap // (Height) private val hcl : String? by defaultMap // (Hair Color) private val ecl : String? by defaultMap // (Eye Color) private val pid : String? by defaultMap // (Passport ID) private val cid : String? by defaultMap // (Country ID) private fun isValidByr() = byr?.toIntOrNull() in 1920..2002 private fun isValidIyr() = iyr?.toIntOrNull() in 2010..2020 private fun isValidEyr() = eyr?.toIntOrNull() in 2020..2030 private fun isValidHcl() = hcl?.matches(Regex("#[0-9a-f]{6}")) ?: false private fun isValidEcl() = ecl != null && enumContains<EyeColor>(ecl) private fun isValidPid() = pid?.matches(Regex("[0-9a-f]{9}")) ?: false private fun isValidHgt(): Boolean { val temp = hgt ?: return false val unit = temp.takeLast(2) val height = temp.substring(0, temp.length - 2) when (unit) { "cm" -> return height.toInt() in 150..193 "in" -> return height.toInt() in 59..76 } return false } override fun isValid() = isValidByr() && isValidIyr() && isValidEyr() && isValidHgt() && isValidHcl() && isValidEcl() && isValidPid() } interface Validator { fun isValid(): Boolean } enum class EyeColor { amb, blu, brn, gry, grn, hzl, oth }
5
Kotlin
0
0
c3b173fa5d579e0d3ba217319caf5e8cd090063f
3,563
advent-of-code-2020
MIT License
src/main/kotlin/ru/glukhov/aoc/Day9.kt
cobaku
576,736,856
false
{"Kotlin": 25268}
package ru.glukhov.aoc import java.io.BufferedReader import kotlin.math.abs private class Field { val head: Position = Position(0, 0) val tail: Position = Position(0, 0) private var oldDirection: Boolean? = true fun apply(input: String) { val (changeX, value) = input.parse() val increment = if (value < 0) -1 else 1 for (counter in 0 until abs(value)) { val headPrev = Pair(head.x, head.y) if (changeX) { head.moveX(increment) } else { head.moveY(increment) } if (changeX != oldDirection && counter == 0) { tail.set(headPrev) } if (counter != 0 && counter != abs(value) - 1) { if (changeX) { tail.moveX(increment) } else { tail.moveY(increment) } } } oldDirection = changeX } private fun String.parse(): Pair<Boolean, Int> { this.split(" ").let { val direction = it[0].trim() var vertical = false var multiplier = 1 when (direction) { "U" -> { vertical = true } "D" -> { vertical = true multiplier = -1 } "L" -> { multiplier = -1 } } return Pair(vertical, Integer.parseInt(it[1]) * multiplier) } } } private data class Position(var x: Int, var y: Int) { val history: MutableSet<Pair<Int, Int>> = mutableSetOf() init { history.add(Pair(x, y)) } fun set(position: Pair<Int, Int>) { this.x = position.first this.y = position.second history.add(position) } fun moveX(x: Int) { this.x += x history.add(Pair(this.x, y)) } fun moveY(y: Int) { this.y += y history.add(Pair(x, this.y)) } } fun main() { Problem.forDay("debug").use { solvePartOne(it) }.let { println("Debug of the first problem is $it") } //Problem.forDay("day9").use { solvePartOne(it) }.let { // println("Result of the first problem is $it") //} } private fun solvePartOne(reader: BufferedReader): Int { val field = Field() reader.forEachLine { field.apply(it) } return field.tail.history.size }
0
Kotlin
0
0
a40975c1852db83a193c173067aba36b6fe11e7b
2,493
aoc2022
MIT License
src/questions/MinDeletionUniqueFrequency.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe /** * Minimum Deletions to Make Character Frequencies Unique * * A string s is called good if there are no two different characters in s that have the same frequency. * Given a string s, return the minimum number of characters you need to delete to make s good. * * [Source](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) – [Solution](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/1107954/Java-Simple-Solution) */ @UseCommentAsDocumentation private fun minDeletions(s: String): Int { val countArray = IntArray(26) { 0 } // Maintain array of counts s.forEach { countArray[it - 'a']++ } val alreadyTaken = mutableSetOf<Int>() // the counts that has already been seen var deletion = 0 for (i in 0..countArray.lastIndex) { var counts = countArray[i] while (counts > 0 && alreadyTaken.contains(counts)) { countArray[i]-- // Count already exists so mark it for deletion counts = countArray[i] deletion++ } alreadyTaken.add(counts) // Unique count } return deletion } fun main() { // s is already good. minDeletions("aab") shouldBe 0 // You can delete two 'b's resulting in the good string "aaabcc". // Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". minDeletions(s = "aaabbbcc") shouldBe 2 // You can delete both 'c's resulting in the good string "eabaab". minDeletions(s = "ceabaacb") shouldBe 2 }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,646
algorithms
MIT License
src/leetcode_daily_chalange/InsertDeleteGetrandomO1.kt
faniabdullah
382,893,751
false
null
//Implement the RandomizedSet class: // // // RandomizedSet() Initializes the RandomizedSet object. // bool insert(int val) Inserts an item val into the set if not present. //Returns true if the item was not present, false otherwise. // bool remove(int val) Removes an item val from the set if present. Returns //true if the item was present, false otherwise. // int getRandom() Returns a random element from the current set of elements ( //it's guaranteed that at least one element exists when this method is called). //Each element must have the same probability of being returned. // // // You must implement the functions of the class such that each function works //in average O(1) time complexity. // // // Example 1: // // //Input //["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", //"insert", "getRandom"] //[[], [1], [2], [2], [], [1], [2], []] //Output //[null, true, false, true, 2, true, false, 2] // //Explanation //RandomizedSet randomizedSet = new RandomizedSet(); //randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was //inserted successfully. //randomizedSet.remove(2); // Returns false as 2 does not exist in the set. //randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now //contains [1,2]. //randomizedSet.getRandom(); // getRandom() should return either 1 or 2 //randomly. //randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now //contains [2]. //randomizedSet.insert(2); // 2 was already in the set, so return false. //randomizedSet.getRandom(); // Since 2 is the only number in the set, //getRandom() will always return 2. // // // // Constraints: // // // -2³¹ <= val <= 2³¹ - 1 // At most 2 * 10⁵ calls will be made to insert, remove, and getRandom. // There will be at least one element in the data structure when getRandom is //called. // // Related Topics Array Hash Table Math Design Randomized 👍 4585 👎 256 package leetcodeProblem.leetcode.editor.en import kotlin.random.Random class InsertDeleteGetrandomO1 { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class RandomizedSet() { private val randomStorage = hashMapOf<Int, Int>() fun insert(`val`: Int): Boolean { if (randomStorage[`val`] == null) { randomStorage[`val`] = `val` return true } return false } fun remove(`val`: Int): Boolean { if (randomStorage[`val`] == null) { return false } randomStorage.remove(`val`) return true } fun getRandom(): Int { return randomStorage[randomStorage.keys.random()] ?: 0 } } /** * Your RandomizedSet object will be instantiated and called as such: * var obj = RandomizedSet() * var param_1 = obj.insert(`val`) * var param_2 = obj.remove(`val`) * var param_3 = obj.getRandom() */ //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
3,194
dsa-kotlin
MIT License
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/interview/MajorityElement.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.simple.interview /** * 面试题 17.10. 主要元素 * https://leetcode.cn/problems/find-majority-element-lcci/ */ class MajorityElement { /** * 摩尔投票解法 * 遍历,并对不同的元素进行抵消。 * 核心思路是: * 1. **如果y的个数超过数组一半大小**,则经过抵消后剩下的数一定是y。 * 2. 如果个数超过一半大小的数不存在。则抵消后最后剩下的数可能是数组中任何一个数。因为抵消是随机的 * * 所以最后要对这个剩下的数的数目进行验证,就可以判断是否存在满足条件的数以及这个数的值 */ fun majorityElement(nums: IntArray): Int { var x = 0 var y = 0 for (num in nums) { if (x == 0) { y = num x = 1 } else { x += if (y == num) 1 else -1 } } x = 0 for (num in nums) if (y == num) x++ return if (nums.size / 2 < x) y else -1 } }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
1,095
blog-sample
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2022/Day16.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2022 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom import kotlin.math.max /** * --- Day 16: Proboscidea Volcanium --- * https://adventofcode.com/2022/day/16 */ class Day16 : Solver { private val cache = mutableMapOf<String, Int>() override fun solve(lines: List<String>): Result { val valves = lines.map { parseLine(it) }.associateBy { it.id } val partA = maxAddtlPoints(valves["AA"]!!, emptySet(), 30, 0, valves) cache.clear() val partB = maxAddtlPoints(valves["AA"]!!, emptySet(), 26, 1, valves) return resultFrom(partA, partB) } private fun maxAddtlPoints( current: Valve, opened: Set<String>, timeLeft: Int, numOthers: Int, allValves: Map<String, Valve>, ): Int { if (timeLeft == 0) { // Note, this solution for Part 2 is from <NAME>. I tried to // come up with doing DP in another way, but couldn't get to the solution. // See https://www.youtube.com/watch?v=DgqkVDr1WX8 for his excellent // explanation. return if (numOthers <= 0) 0 else maxAddtlPoints( allValves["AA"]!!, opened, 26, numOthers - 1, allValves ) } val cacheKey = "${current.id}-$timeLeft-${opened.sorted().joinToString(",")}-$numOthers" if (cacheKey in cache) return cache[cacheKey]!! // Can either open or not, then continue the other paths. // But you cannot open an already open valve. var maxValue = 0 // Open this valve and stay if it can produce steam and isn't already open. if (current.rate > 0 && current.id !in opened) { maxValue = max( maxValue, maxAddtlPoints( current, opened.plus(current.id), timeLeft - 1, numOthers, allValves ) + (current.rate * (timeLeft - 1)) ) } // Don't open a valve and go to all the other places. maxValue = max(maxValue, current.leadTo.map { allValves[it]!! } .maxOf { maxAddtlPoints( it, opened, timeLeft - 1, numOthers, allValves ) }) cache[cacheKey] = maxValue return maxValue } private fun parseLine(line: String): Valve { val split = line.split(" ") val id = split[1] val rateStr = split[4].split("=")[1] val rate = rateStr.substring(0, rateStr.length - 1).toInt() val leadTo = line.split("to valves ", "to valve ")[1].split(", ").toSet() return Valve(id, rate, leadTo) } data class Valve(val id: String, val rate: Int, val leadTo: Set<String>) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,633
euler
Apache License 2.0
src/main/kotlin/asaad/DayThree.kt
Asaad27
573,138,684
false
{"Kotlin": 23483}
package asaad import java.io.File class DayThree(filePath: String) { private val file = File(filePath) private val input = readInput(file) private fun readInput(file: File) = file.readLines() private fun Char.toPriority(): Int = when { this.isLowerCase() -> this - 'a' + 1 this.isUpperCase() -> this - 'A' + 27 else -> throw Exception("char $this has no priority") } private fun solve1() = input.fold(0) { acc, s -> acc + RuckSack(s).repeatedItem().toPriority() } private fun solve2() = input.chunked(3){ chunk -> chunk.map { it.toSet() } .reduce { acc, chars -> acc.intersect(chars) } .firstOrNull() }.fold(0) { acc, s -> acc + s?.toPriority()!! } fun result() { println("\tpart 1: ${solve1()}") println("\tpart 2: ${solve2()}") } private class RuckSack(ruckSack: String) { private val compartments: List<Set<Char>> init { val ruckSize = ruckSack.length compartments = listOf( ruckSack.substring(0 until ruckSize / 2).toHashSet(), ruckSack.substring(ruckSize / 2 until ruckSize).toHashSet() ) } fun repeatedItem(): Char { val intersection = compartments[0].intersect(compartments[1].toSet()) if (intersection.size > 1) throw Exception("there is more than one repeated element in the compartments") return intersection.first() } } }
0
Kotlin
0
0
16f018731f39d1233ee22d3325c9933270d9976c
1,558
adventOfCode2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FurthestBuilding.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <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 java.util.PriorityQueue import java.util.Queue import kotlin.math.max import kotlin.math.min /** * Furthest Building You Can Reach * @see <a href="https://leetcode.com/problems/furthest-building-you-can-reach/">Source</a> */ fun interface FurthestBuilding { operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int } /** * Approach 1: Min-Heap * Time complexity : O(N log N) or O(N log L). * Space complexity : O(N) or O(L). */ class MinHeap : FurthestBuilding { override operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int { // Create a priority queue with a comparator that makes it behave as a min-heap. val ladderAllocations: Queue<Int> = PriorityQueue { a, b -> a - b } var b = bricks for (i in 0 until heights.size - 1) { val climb = heights[i + 1] - heights[i] // If this is actually a "jump down", skip it. if (climb <= 0) { continue } // Otherwise, allocate a ladder for this climb. ladderAllocations.add(climb) // If we haven't gone over the number of ladders, nothing else to do. if (ladderAllocations.size <= ladders) { continue } // Otherwise, we will need to take a climb out of ladder_allocations b -= ladderAllocations.remove() // If this caused bricks to go negative, we can't get to i + 1 if (b < 0) { return i } } // If we got to here, this means we had enough materials to cover every climb. return heights.size - 1 } } /** * Approach 2: Max-Heap * Time complexity : O(N log N). * Space complexity : O(N). */ class MaxHeap : FurthestBuilding { override operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int { // Create a priority queue with a comparator that makes it behave as a max-heap. val brickAllocations: Queue<Int> = PriorityQueue { a: Int, b: Int -> b - a } var b = bricks var l = ladders for (i in 0 until heights.size - 1) { val climb = heights[i + 1] - heights[i] // If this is actually a "jump down", skip it. if (climb <= 0) { continue } // Otherwise, allocate a ladder for this climb. brickAllocations.add(climb) b -= climb // If we've used all the bricks, and have no ladders remaining, then // we can't go any further. if (b < 0 && l == 0) { return i } // Otherwise, if we've run out of bricks, we should replace the largest // brick allocation with a ladder. if (b < 0) { b += brickAllocations.remove() l-- } } // If we got to here, this means we had enough materials to cover every climb. return heights.size - 1 } } /** * Approach 3: Binary Search for Final Reachable Building * Time complexity : O(N log² N). * Space complexity : O(N). */ class FinalReachableBuilding : FurthestBuilding { override operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int { // Do a binary search on the heights array to find the final reachable building. // Do a binary search on the heights array to find the final reachable building. var lo = 0 var hi: Int = heights.size - 1 while (lo < hi) { val mid = lo + (hi - lo + 1) / 2 if (isReachable(mid, heights, bricks, ladders)) { lo = mid } else { hi = mid - 1 } } return hi // Note that return lo would be equivalent. } private fun isReachable(buildingIndex: Int, heights: IntArray, bricks: Int, ladders: Int): Boolean { // Make a list of all the climbs we need to do to reach buildingIndex. var b = bricks var l = ladders val climbs: MutableList<Int> = ArrayList() for (i in 0 until buildingIndex) { val h1 = heights[i] val h2 = heights[i + 1] if (h2 <= h1) { continue } climbs.add(h2 - h1) } climbs.sort() // And now determine whether or not all of these climbs can be covered with the // given bricks and ladders. for (climb in climbs) { // If there are bricks left, use those. when { climb <= b -> { b -= climb // Otherwise, you'll have to use a ladder. } l >= 1 -> { l -= 1 // And if there are no ladders either, we can't reach buildingIndex. } else -> { return false } } } return true } } /** * Approach 4: Improved Binary Search for Final Reachable Building * Time complexity : O(N log N). * Space complexity : O(N). */ class ImprovedFinalReachableBuilding : FurthestBuilding { override operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int { // Make a sorted list of all the climbs. val sortedClimbs: MutableList<IntArray> = ArrayList() for (i in 0 until heights.size - 1) { val climb = heights[i + 1] - heights[i] if (climb <= 0) { continue } sortedClimbs.add(intArrayOf(climb, i + 1)) } sortedClimbs.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] } // Now do the binary search, same as before. var lo = 0 var hi: Int = heights.size - 1 while (lo < hi) { val mid = lo + (hi - lo + 1) / 2 if (isReachable(mid, sortedClimbs, bricks, ladders)) { lo = mid } else { hi = mid - 1 } } return hi // Note that return lo would be equivalent. } private fun isReachable(buildingIndex: Int, climbs: List<IntArray>, bricks: Int, ladders: Int): Boolean { var b = bricks var l = ladders for (climbEntry in climbs) { // Extract the information for this climb val climb = climbEntry[0] val index = climbEntry[1] // Check if this climb is within the range. if (index > buildingIndex) { continue } // Allocate bricks if enough remain; otherwise, allocate a ladder if // at least one remains. when { climb <= b -> { b -= climb } l >= 1 -> { l -= 1 } else -> { return false } } } return true } } /** * Approach 5: Binary Search on Threshold (Advanced) * Time complexity : O(N log(maxClimb)). * Space complexity : O(1). */ class BSThreshold : FurthestBuilding { override operator fun invoke(heights: IntArray, bricks: Int, ladders: Int): Int { var lo = Int.MAX_VALUE var hi = Int.MIN_VALUE for (i in 0 until heights.size - 1) { val climb = heights[i + 1] - heights[i] if (climb <= 0) { continue } lo = min(lo, climb) hi = max(hi, climb) } if (lo == Int.MAX_VALUE) { return heights.size - 1 } while (lo <= hi) { val mid = lo + (hi - lo) / 2 val result = solveWithGivenThreshold(heights, bricks, ladders, mid) val indexReached = result[0] val laddersRemaining = result[1] val bricksRemaining = result[2] if (indexReached == heights.size - 1) { return heights.size - 1 } if (laddersRemaining > 0) { hi = mid - 1 continue } // Otherwise, check whether this is the "too low" or "just right" case. val nextClimb = heights[indexReached + 1] - heights[indexReached] lo = if (nextClimb > bricksRemaining && mid > bricksRemaining) { return indexReached } else { mid + 1 } } return -1 // It always returns before here. But gotta keep Java happy. } private fun solveWithGivenThreshold(heights: IntArray, bricks: Int, ladders: Int, k: Int): IntArray { var bricksCount = bricks var laddersCount = ladders var laddersUsedOnThreshold = 0 for (i in 0 until heights.size - 1) { val climb = heights[i + 1] - heights[i] if (climb <= 0) { continue } // Make resource allocations when { climb == k -> { laddersUsedOnThreshold++ laddersCount-- } climb > k -> { laddersCount-- } else -> { bricksCount -= climb } } // Handle negative resources if (laddersCount < 0) { bricksCount -= if (laddersUsedOnThreshold >= 1) { laddersUsedOnThreshold-- laddersCount++ k } else { return intArrayOf(i, laddersCount, bricksCount) } } if (bricksCount < 0) { return intArrayOf(i, laddersCount, bricksCount) } } return intArrayOf(heights.size - 1, laddersCount, bricksCount) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
10,549
kotlab
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2023/Day16.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 16 - The Floor Will Be Lava * Problem Description: http://adventofcode.com/2023/day/16 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day16/ */ package com.ginsberg.advent2023 import com.ginsberg.advent2023.Point2D.Companion.EAST import com.ginsberg.advent2023.Point2D.Companion.NORTH import com.ginsberg.advent2023.Point2D.Companion.SOUTH import com.ginsberg.advent2023.Point2D.Companion.WEST class Day16(input: List<String>) { private val grid: Array<CharArray> = input.map { it.toCharArray() }.toTypedArray() private val movements = mapOf( '-' to NORTH to listOf(EAST, WEST), '-' to SOUTH to listOf(EAST, WEST), '|' to EAST to listOf(NORTH, SOUTH), '|' to WEST to listOf(NORTH, SOUTH), '\\' to NORTH to listOf(WEST), '\\' to WEST to listOf(NORTH), '\\' to SOUTH to listOf(EAST), '\\' to EAST to listOf(SOUTH), '/' to NORTH to listOf(EAST), '/' to WEST to listOf(SOUTH), '/' to SOUTH to listOf(WEST), '/' to EAST to listOf(NORTH) ) fun solvePart1(): Int = energize(Point2D(0, 0), EAST) fun solvePart2(): Int = listOf( grid.first().indices.map { Point2D(it, 0) to SOUTH }, grid.first().indices.map { Point2D(it, grid.lastIndex) to NORTH }, grid.indices.map { Point2D(0, it) to EAST }, grid.indices.map { Point2D(grid.first().lastIndex, it) to WEST } ) .flatten() .maxOf { energize(it.first, it.second) } private fun energize(startPoint: Point2D, startDirection: Point2D): Int { val seen = mutableSetOf(startPoint to startDirection) val queue = ArrayDeque<Pair<Point2D, Point2D>>().apply { add(startPoint to startDirection) } while (queue.isNotEmpty()) { val (place, direction) = queue.removeFirst() val nextDirections = movements[grid[place] to direction] ?: listOf(direction) nextDirections.forEach { nextDirection -> val nextPlace = place + nextDirection val nextPair = nextPlace to nextDirection if (nextPair !in seen && grid.isSafe(nextPlace)) { queue.add(nextPair) seen += nextPair } } } return seen.map { it.first }.toSet().size } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
2,499
advent-2023-kotlin
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[643]子数组最大平均数 I.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。 // // // // 示例: // // //输入:[1,12,-5,-6,50,3], k = 4 //输出:12.75 //解释:最大平均数 (12-5-6+50)/4 = 51/4 = 12.75 // // // // // 提示: // // // 1 <= k <= n <= 30,000。 // 所给数据范围 [-10,000,10,000]。 // // Related Topics 数组 // 👍 164 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findMaxAverage(nums: IntArray, k: Int): Double { //滑动窗口 时间复杂度 O(n) //返回值 和 k 长度窗口和 var res = 0.0 var sum = 0.0 //获取初始前 k 和赋值 res for (i in 0 until k){ sum += nums[i] } res = sum/k for (i in k until nums.size){ sum = sum + nums[i] - nums[i-k] res = Math.max(res,sum/k) } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,040
MyLeetCode
Apache License 2.0
src/day07/Day07.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
package day07 import readInput fun main() { val totalSize = 70000000 val requiredSpace = 30000000 var mapDirectoryToSizeLimited = listOf<Int>() var mapDirectoryToSize = listOf<Int>() val root = Directory("/") fun findDirectoriesWithSize(iterateDirectory: Directory, maxSize: Int) { if (iterateDirectory.getDirectorySize() <= maxSize) { mapDirectoryToSizeLimited = mapDirectoryToSizeLimited.plus(iterateDirectory.getDirectorySize()) } if (iterateDirectory.subDirectories.isNotEmpty()) { for (d in iterateDirectory.subDirectories) { findDirectoriesWithSize(d, maxSize) } } } fun fillMapDirectoryToSize(iterateDirectory: Directory) { mapDirectoryToSize = mapDirectoryToSize.plus(iterateDirectory.getDirectorySize()) if (iterateDirectory.subDirectories.isNotEmpty()) { for (d in iterateDirectory.subDirectories) { fillMapDirectoryToSize(d) } } } fun solvePuzzle(input: List<String>) { var currentDirectory = root val iterator = input.iterator() while (iterator.hasNext()) { val line = iterator.next() if (line.startsWith("$")) { val command = line.split("$")[1] if (command.trim().contains("cd") && command.split(" ")[2] != "..") { // read in directory name val directoryName = command.split(" ")[2] if (directoryName != "/") { currentDirectory = currentDirectory.subDirectories.find { it.name == directoryName } ?: throw RuntimeException("ERROR 1") } } else if (command.trim().contains("cd") && command.split(" ")[2] == "..") { currentDirectory = currentDirectory.parentDirectory ?: throw RuntimeException("ERROR 2") } else if (command.trim().contains("ls")){ // read in new directories and files continue } } else { // we are now reading in files and subdirectories if (line.startsWith("dir")) { currentDirectory.addSubdirectory(line.split(" ")[1]) } else if (line[0].isDigit()) { val size = line.split(" ")[0].toInt() val filename = line.split(" ")[1] currentDirectory.addFile(filename, size) } } } } fun part1(input: List<String>): Int { solvePuzzle(input) findDirectoriesWithSize(root, 100000) return mapDirectoryToSizeLimited.sum() } fun part2(input: List<String>): Int { solvePuzzle(input) fillMapDirectoryToSize(root) mapDirectoryToSize = mapDirectoryToSize.sorted() val requiredFreeSpace = requiredSpace - (totalSize - root.getDirectorySize()) return mapDirectoryToSize.find { it >= requiredFreeSpace } ?: throw RuntimeException("ERROR 3") } // val testInput = // "\$ cd /\n" + // "\$ ls\n" + // "dir a\n" + // "14848514 b.txt\n" + // "8504156 c.dat\n" + // "dir d\n" + // "\$ cd a\n" + // "\$ ls\n" + // "dir e\n" + // "29116 f\n" + // "2557 g\n" + // "62596 h.lst\n" + // "\$ cd e\n" + // "\$ ls\n" + // "584 i\n" + // "\$ cd ..\n" + // "\$ cd ..\n" + // "\$ cd d\n" + // "\$ ls\n" + // "4060174 j\n" + // "8033020 d.log\n" + // "5626152 d.ext\n" + // "7214296 k" // println(part1(testInput.split("\n"))) // println(part2(testInput.split("\n"))) val input = readInput("07") println("Part1:") println(part1(input)) println("Part2:") println(part2(input)) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
4,048
AdventOfCode2022
Apache License 2.0
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/trie/Trie.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.trie class Trie<Key> { private val storedLists: MutableSet<List<Key>> = mutableSetOf() val lists get() = storedLists.toList() val count get() = storedLists.count() val isEmpty get() = storedLists.isEmpty() val isNotEmpty get() = !isEmpty private val root = TrieNode<Key>(key = null, parent = null) fun insert(list: List<Key>) { var current = root list.forEach { element -> if (current.children[element] == null) { current.children[element] = TrieNode(element, current) } current = current.children[element]!! } current.isTerminating = true storedLists.add(list) } fun contains(list: List<Key>): Boolean { var current = root list.forEach { element -> val child = current.children[element] ?: return false current = child } return current.isTerminating } fun remove(list: List<Key>) { var current = root list.forEach { element -> val child = current.children[element] ?: return current = child } if (!current.isTerminating) return storedLists.remove(list) current.isTerminating = false while (current.parent != null && current.children.isEmpty() && !current.isTerminating) { current.parent!!.children.remove(current.key) current = current.parent!! } } fun collections(prefix: List<Key>): List<List<Key>> { var current = root prefix.forEach { element -> val child = current.children[element] ?: return emptyList() current = child } return collections(prefix, current) } private fun collections(prefix: List<Key>, node: TrieNode<Key>?): List<List<Key>> { val results = mutableListOf<List<Key>>() if (node?.isTerminating == true) { results.add(prefix) } node?.children?.forEach { (key, node) -> results.addAll(collections(prefix + key, node)) } return results } }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
2,203
KAHelpers
MIT License
src/day2/day2s.kt
bienenjakob
573,125,960
false
{"Kotlin": 53763}
package day2 import inputTextOfDay import testTextOfDay const val rock = 1 const val paper = 2 const val scissors = 3 const val loose = 0 const val draw = 3 const val win = 6 fun part1s(text: String): Int = text.lines().sumOf { when (it) { // rock "A X" -> rock + draw "A Y" -> paper + win "A Z" -> scissors + loose // paper "B X" -> rock + loose "B Y" -> paper + draw "B Z" -> scissors + win // scissors "C X" -> rock + win "C Y" -> paper + loose else -> scissors + draw } } fun part2s(text: String): Int = text.lines().sumOf { when (it) { // rock "A X" -> loose + scissors "A Y" -> draw + rock "A Z" -> win + paper // paper "B X" -> loose + rock "B Y" -> draw + paper "B Z" -> win + scissors // scissors "C X" -> loose + paper "C Y" -> draw + scissors else -> win + rock } } fun main() { val day = 2 val test = testTextOfDay(day) check(part1s(test) == 15) val input = inputTextOfDay(day) println(part1s(input)) println(part2s(input)) }
0
Kotlin
0
0
6ff34edab6f7b4b0630fb2760120725bed725daa
1,178
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day7.kt
tpepper0408
317,612,203
false
null
package days class Day7 : Day<Int>(7) { override fun partOne(): Int { val colourMap = HashMap<String, List<Pair<String, Int>>>() inputList.map { row -> val (colour, childrenString) = row.split("bags contain") .map { it.trim() } val children: List<Pair<String, Int>> = childrenString.split(',') .map { it.trim() } .map { findChildren(it) }.flatten() colourMap.put(colour, children) } val coloursThatContainShinyGold = checkForColour(colourMap, "shiny gold") return coloursThatContainShinyGold.size } private fun findChildren(it: String): List<Pair<String, Int>> { return it.split(',') .map { if (it.startsWith("no")) { return@map Pair("", 0) } val number = it[0].toString().toInt() val (colour) = Regex("([a-z ]*?) bag") .find(it)!! .destructured Pair(colour.trim(), number) } } fun checkForColour(colourMap: HashMap<String, List<Pair<String, Int>>>, colourToCheck: String): HashSet<String> { val retval = HashSet<String>() for (childColour in colourMap.keys) { val children = colourMap.get(childColour)!! for (child in children) { if (child.first == colourToCheck) { retval.add(childColour) retval.addAll(checkForColour(colourMap, childColour)) } } } return retval } override fun partTwo(): Int { val colourMap = HashMap<String, List<Pair<String, Int>>>() inputList.map { row -> val (colour, childrenString) = row.split("bags contain") .map { it.trim() } val children: List<Pair<String, Int>> = childrenString.split(',') .map { it.trim() } .map { findChildren(it) }.flatten() colourMap.put(colour, children) } return getNumberOfChildren(colourMap, "shiny gold") } private fun getNumberOfChildren(colourMap: HashMap<String, List<Pair<String, Int>>>, colourName: String): Int { var numberOfBags = 0 val children = colourMap.get(colourName)!! for (child in children) { if (child.first == "") { continue } numberOfBags += child.second numberOfBags += child.second * getNumberOfChildren(colourMap, child.first) } return numberOfBags } }
0
Kotlin
0
0
67c65a9e93e85eeb56b57d2588844e43241d9319
2,705
aoc2020
Creative Commons Zero v1.0 Universal
src/day01.kt
skuhtic
572,645,300
false
{"Kotlin": 36109}
fun main() { day01.execute(forceBothParts = true) } val day01 = object : Day<Int>(1, 24000, 45000) { override val testInput: InputData get() = """ 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 """.trimIndent().lines() override fun part1(input: InputData): Int = input .splitByEmpty() .maxOf { elf -> elf.sumOf { it.toInt() } } override fun part2(input: InputData): Int = input .splitByEmpty() .map { e -> e.sumOf { it.toInt() } } .sortedDescending().take(3).sum() } fun InputData.splitByEmpty(): List<List<String>> = this.flatMapIndexed { i, s -> when { i == 0 || i == this.lastIndex -> listOf(i) s.isEmpty() -> listOf(i - 1, i + 1) else -> emptyList() } }.windowed(2, 2) { (from, to) -> this.slice(from..to) }
0
Kotlin
0
0
8de2933df90259cf53c9cb190624d1fb18566868
1,060
aoc-2022
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/day3/TobogganTrajectory.kt
Pkshields
318,658,287
false
null
package dev.paulshields.aoc.day3 import dev.paulshields.aoc.common.divideRoundingUp import dev.paulshields.aoc.common.readFileAsStringList fun main() { println(" ** Day 3: Toboggan Trajectory ** \n") val map = readFileAsStringList("/day3/Map.txt") val result = generateSlopePath(1, 3, map) .calculateNumberOfTreesHit(map) println("The toboggan will hit $result trees!") val treesHitInOneOne = generateSlopePath(1, 1, map).calculateNumberOfTreesHit(map) val treesHitInOneFive = generateSlopePath(1, 5, map).calculateNumberOfTreesHit(map) val treesHitInOneSeven = generateSlopePath(1, 7, map).calculateNumberOfTreesHit(map) val treesHitInTwoOne = generateSlopePath(2, 1, map).calculateNumberOfTreesHit(map) val part2Result = treesHitInOneOne.toLong() * result * treesHitInOneFive * treesHitInOneSeven * treesHitInTwoOne println("The answer to part 2 is $part2Result!") } fun generateSlopePath(down: Int, right: Int, map: List<String>): List<SlopeStep> { if (map.isEmpty()) return emptyList() val mapLineLength = map[0].length val numberStepsDown = divideRoundingUp(map.size, down) return (0 until numberStepsDown) .map { SlopeStep((right * it) % mapLineLength, down * it) } } fun List<SlopeStep>.calculateNumberOfTreesHit(map: List<String>) = this .map { map[it.y][it.x] == '#' } .filter { it } .count() data class SlopeStep(val x: Int, val y: Int)
0
Kotlin
0
0
a7bd42ee17fed44766cfdeb04d41459becd95803
1,463
AdventOfCode2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReorganizeString.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT import java.util.PriorityQueue /** * 767. Reorganize String * @see <a href="https://leetcode.com/problems/reorganize-string/">Source</a> */ internal fun interface ReorganizeString { operator fun invoke(s: String): String } /** * Approach 1: Counting and Priority Queue */ class ReorganizeStringPQ : ReorganizeString { override operator fun invoke(s: String): String { val charCounts = IntArray(ALPHABET_LETTERS_COUNT) for (c in s.toCharArray()) { charCounts[c.code - 'a'.code] = charCounts[c.code - 'a'.code] + 1 } // Max heap ordered by character counts val pq: PriorityQueue<IntArray> = PriorityQueue<IntArray> { a, b -> b[1].compareTo(a[1]) } for (i in 0 until ALPHABET_LETTERS_COUNT) { if (charCounts[i] > 0) { pq.offer(intArrayOf(i + 'a'.code, charCounts[i])) } } val sb = StringBuilder() while (pq.isNotEmpty()) { val first = pq.poll() if (sb.isEmpty() || first[0] != sb[sb.length - 1].code) { sb.append(first[0].toChar()) if (--first[1] > 0) { pq.offer(first) } } else { if (pq.isEmpty()) { return "" } val second = pq.poll() sb.append(second[0]) if (--second[1] > 0) { pq.offer(second) } pq.offer(first) } } return sb.toString() } } /** * Approach 2: Counting and Odd/Even */ class ReorganizeStringCounting : ReorganizeString { override operator fun invoke(s: String): String { val charCounts = IntArray(ALPHABET_LETTERS_COUNT) for (c in s.toCharArray()) { charCounts[c.code - 'a'.code]++ } var maxCount = 0 var letter = 0 for (i in charCounts.indices) { if (charCounts[i] > maxCount) { maxCount = charCounts[i] letter = i } } if (maxCount > (s.length + 1) / 2) { return "" } val ans = CharArray(s.length) var index = 0 // Place the most frequent letter while (charCounts[letter] != 0) { ans[index] = (letter + 'a'.code).toChar() index += 2 charCounts[letter]-- } // Place rest of the letters in any order for (i in charCounts.indices) { while (charCounts[i] > 0) { if (index >= s.length) { index = 1 } ans[index] = (i + 'a'.code).toChar() index += 2 charCounts[i]-- } } return String(ans) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,545
kotlab
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/greedy/NaiveHuffmanEncode.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.greedy /** * abacabad * 4 14 * a: 0 * b: 10 * c: 110 * d: 111 * 01001100100111 */ fun main() { val s = "abacabad" val letterToFreq = getLetterToFrequency(s = s) val letterWeightStack = getLetterWeightStack(letterToFreq = letterToFreq) val huffmanResult = huffman(letterWeightStack = letterWeightStack) val dictionary = getDictionary(huffmanResult = huffmanResult) val encodedString = encodeString(stringToEncode = s, dictionary = dictionary) println("${dictionary.keys.size} ${encodedString.length}") dictionary.forEach { println("${it.key}: ${it.value}") } println(encodedString) } private fun getLetterToFrequency(s: String): Map<String, Int> { val letterToFreq = HashMap<String, Int>() for (l in s) { val letter = l.toString() if (letterToFreq.containsKey(letter)) { letterToFreq[letter] = letterToFreq[letter]!!.plus(1) } else { letterToFreq[letter] = 1 } } return letterToFreq } private fun getLetterWeightStack(letterToFreq: Map<String, Int>): MutableList<LetterWeight> { return letterToFreq.map { LetterWeight(it.key, it.value) }.toMutableList() } private fun getMinLetterWeight(letterWeightStack: MutableList<LetterWeight>): LetterWeight { var min = 0; for (i in letterWeightStack.indices) { if (letterWeightStack[i].weight < letterWeightStack[min].weight) { min = i } } return letterWeightStack.removeAt(min) } private fun huffman(letterWeightStack: MutableList<LetterWeight>): List<List<String>> { val huffmanResult = mutableListOf<List<String>>() if (letterWeightStack.size == 1) { val letterWeight = getMinLetterWeight(letterWeightStack) huffmanResult.add(listOf(letterWeight.letter, "0")) return huffmanResult } while (letterWeightStack.size > 1) { val leftLetterWeight = getMinLetterWeight(letterWeightStack) val rightLetterWeight = getMinLetterWeight(letterWeightStack) val newLetter = leftLetterWeight.letter.plus(rightLetterWeight.letter) val newWeight = leftLetterWeight.weight.plus(rightLetterWeight.weight) val newLetterWeight = LetterWeight(letter = newLetter, weight = newWeight) letterWeightStack.add(newLetterWeight) huffmanResult.add(listOf(leftLetterWeight.letter, "0")) huffmanResult.add(listOf(rightLetterWeight.letter, "1")) } return huffmanResult } private fun getDictionary(huffmanResult: List<List<String>>): Map<String, String> { val dictionary = mutableMapOf<String, String>() for (innerList in huffmanResult) { val letters = innerList[0] val code = innerList[1] letters.forEach { dictionary.merge(it.toString(), code) { a, b -> b.plus(a) } } } return dictionary } private fun encodeString(stringToEncode: String, dictionary: Map<String, String>): String { val stringBuilder = StringBuilder() stringToEncode.forEach { stringBuilder.append(dictionary[it.toString()]) } return stringBuilder.toString() } data class LetterWeight( val letter: String, val weight: Int )
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
3,203
algs4-leprosorium
MIT License
src/day02/Day02.kt
kerchen
573,125,453
false
{"Kotlin": 137233}
package day02 import readInput enum class OpponentShape { ROCK(), PAPER(), SCISSORS(); companion object { fun getShape(shape: String): OpponentShape = when (shape) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS else -> throw Exception("Unexpected shape") } } } enum class Outcome { WIN { override fun score(): Int = 6 }, LOSE { override fun score(): Int = 0 }, DRAW { override fun score(): Int = 3 }; abstract fun score(): Int companion object { fun getOutcome(outcome: String): Outcome = when(outcome) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> throw Exception("Unexpected outcome") } } } enum class SelfShape { ROCK { override fun outcome(opponentShape: OpponentShape): Outcome = when(opponentShape) { OpponentShape.ROCK -> Outcome.DRAW OpponentShape.PAPER -> Outcome.LOSE OpponentShape.SCISSORS -> Outcome.WIN } override fun score(opponentShape: OpponentShape): Int = 1 + outcome(opponentShape).score() }, PAPER { override fun outcome(opponentShape: OpponentShape): Outcome = when(opponentShape) { OpponentShape.ROCK -> Outcome.WIN OpponentShape.PAPER -> Outcome.DRAW OpponentShape.SCISSORS -> Outcome.LOSE } override fun score(opponentShape: OpponentShape): Int = 2 + outcome(opponentShape).score() }, SCISSORS { override fun outcome(opponentShape: OpponentShape): Outcome = when(opponentShape) { OpponentShape.ROCK -> Outcome.LOSE OpponentShape.PAPER -> Outcome.WIN OpponentShape.SCISSORS -> Outcome.DRAW } override fun score(opponentShape: OpponentShape): Int = 3 + outcome(opponentShape).score() }; abstract fun outcome(opponentShape: OpponentShape): Outcome abstract fun score(opponentShape: OpponentShape): Int companion object { fun getShape(shape: String): SelfShape = when (shape) { "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> throw Exception("Unexpected shape") } } } enum class InferredShape { ROCK { override fun score(outcome: Outcome): Int = 1 + outcome.score() }, PAPER { override fun score(outcome: Outcome): Int = 2 + outcome.score() }, SCISSORS { override fun score(outcome: Outcome): Int = 3 + outcome.score() }; abstract fun score(outcome: Outcome): Int companion object { fun getShapeForOutcome(opponentShape: OpponentShape, outcome: Outcome): InferredShape = when(opponentShape) { OpponentShape.ROCK -> when (outcome) { Outcome.LOSE -> SCISSORS Outcome.DRAW -> ROCK Outcome.WIN -> PAPER } OpponentShape.PAPER -> when (outcome) { Outcome.LOSE -> ROCK Outcome.DRAW -> PAPER Outcome.WIN -> SCISSORS } OpponentShape.SCISSORS -> when (outcome) { Outcome.LOSE -> PAPER Outcome.DRAW -> SCISSORS Outcome.WIN -> ROCK } } } } fun main() { fun computeScore(opponentShape: OpponentShape, selfShape: SelfShape): Int = selfShape.score(opponentShape) fun part1(input: List<String>): Int { var total = 0 for (match in input) { val shapes = match.split(" ") total += computeScore(OpponentShape.getShape(shapes[0]), SelfShape.getShape(shapes[1])) } return total } fun part2(input: List<String>): Int { var total = 0 for (match in input) { val values = match.split(" ") val desiredOutcome = Outcome.getOutcome(values[1]) val inferredShape = InferredShape.getShapeForOutcome(OpponentShape.getShape(values[0]), desiredOutcome) total += inferredShape.score(desiredOutcome) } return total } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dc15640ff29ec5f9dceb4046adaf860af892c1a9
4,560
AdventOfCode2022
Apache License 2.0
leetcode/kotlin/most-stones-removed-with-same-row-or-column.kt
PaiZuZe
629,690,446
false
null
class Solution { fun removeStones(stones: Array<IntArray>): Int { val unionFind = IntArray(stones.size) { it } val height = IntArray(stones.size) { 0 } var resp = stones.size for (i in 0 until stones.size) { for (j in 0 until stones.size) { if (isNeighbor(i, j, stones)) { val v = find(unionFind, i) val w = find(unionFind, j) if (v != w) { union(unionFind, height, v, w) resp-- } } } } return stones.size - resp } private fun isNeighbor(v: Int, w: Int, stones: Array<IntArray>): Boolean { val (vX, vY) = stones[v] val (wX, wY) = stones[w] if (vX == wX || vY == wY) { return true } return false } private fun union(unionFind: IntArray, height: IntArray, v: Int, w: Int) { if (height[v] > height[w]) { unionFind[w] = v } else { unionFind[v] = w if (height[v] == height[w]) { height[w] = height[w] + 1 } } } private fun find(unionFind: IntArray, v: Int): Int { if (unionFind[v] != v) { unionFind[v] = find(unionFind, unionFind[v]) } return unionFind[v] } } fun List<Pair<Int, Int>>.printable() = this.joinToString("|") { "${it.first}, ${ it.second }" } fun main () { val a1 = arrayOf<IntArray>( intArrayOf(0, 0), intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, 2) ) val a2 = arrayOf<IntArray>( intArrayOf(0, 0), intArrayOf(0, 2), intArrayOf(1, 1), intArrayOf(2, 0), intArrayOf(2, 2) ) val a3 = arrayOf<IntArray>( intArrayOf(0, 0) ) val sol = Solution() val resp1 = sol.removeStones(a1) println("resp: $resp1, isExpected: ${ resp1 == 5 }") val resp2 = sol.removeStones(a2) println("resp: $resp2, isExpected: ${ resp2 == 3 }") val resp3 = sol.removeStones(a3) println("resp: $resp3, isExpected: ${ resp3 == 0 }") }
0
Kotlin
0
0
175a5cd88959a34bcb4703d8dfe4d895e37463f0
2,259
interprep
MIT License
src/main/kotlin/no/chriswk/aoc2019/Day12.kt
chriswk
225,314,163
false
null
package no.chriswk.aoc2019 class Day12 { companion object { @JvmStatic fun main(args: Array<String>) { val day12 = Day12() report { day12.part1() } report { day12.part2() } } } fun part1(): Int { val locations = parseLocations("day12.txt".fileToLines()) val simulator = Simulator(locations) simulator.step(1000) return simulator.moons.sumBy { it.totalEnergy() } } fun part2(): Long { val bodies = parseLocations("day12.txt".fileToLines()) val simulator = Simulator(bodies) return simulator.findCycle() } fun parseLocations(input: List<String>): List<Point3D> { return input.map { Point3D.fromString(it) } } } class Simulator(val positions: List<Point3D>) { val moons = positions.map { Body(it, Point3D.ZERO) } var t = 0 fun step() { for ((a, b) in moons.combinations(2)) { val (x,y,z) = IntArray(3) { i -> a.location[i].compareTo(b.location[i]) } val dV = Point3D(x,y,z) a.velocity -= dV b.velocity += dV } moons.forEach { it.location += it.velocity } t++ } fun step(n: Int) { repeat(n) { step() } } fun findCycle(): Long { val cycles = IntArray(3) var ok: Boolean do { step() ok = true for (i in 0.until(3)) { if (cycles[i] != 0) { continue } ok = false if (moons.indices.all { j -> val m = moons[j] m.location[i] == positions[j][i] && m.velocity[i] == 0 }) { cycles[i] = t } } } while (!ok) return cycles.fold(1L) { acc, i -> acc / gcd(acc, i.toLong()) * i } } }
0
Kotlin
0
0
14b527889b63952c2fba473a8da4ce37071a65bd
1,923
adventofcode2019
MIT License
day11/src/Day11.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day11(private val path: String) { private var map = mutableListOf<Int>() private var flashMap: BooleanArray private var height = 0 private var width = 0 init { var i = 0 var j = 0 File(path).forEachLine { line -> j = line.length line.forEach { map.add(Character.getNumericValue(it)) } i++ } height = i width = j flashMap = BooleanArray(map.size) { false } } private fun getMapAt(m: List<Int>, x: Int, y: Int): Int { return m[y * width + x] } private fun setMapAt(m: MutableList<Int>, x: Int, y: Int, value: Int) { m[y * width + x] = value } private fun increaseAdjacent(m: MutableList<Int>, f: BooleanArray) { for (y in 0 until height) { for (x in 0 until width) { if (f[y * width + x]) { for (i in -1..1) { for (j in -1..1) { if (i != 0 || j != 0) { if ((x + j in 0 until width) && (y + i in 0 until height)) { setMapAt(m, x + j, y + i, getMapAt(m, x + j, y + i) + 1) } } } } } } } } private fun flash(m: MutableList<Int>, f: BooleanArray) { for (i in 0 until height) { for (j in 0 until width) { var energy = getMapAt(m, j, i) if (energy > 9 && !flashMap[i * width + j]) { f[i * width + j] = true flashMap[i * width + j] = true //increaseAdjacent(m, f) } } } } private fun printMap(m: MutableList<Int>) { for (i in 0 until height) { for (j in 0 until width) { print(getMapAt(m, j, i)) print(" ") } println() } println() } private fun step(): Int { var totalFlashes = 0 // 1. Increase energy val newMap = map.map { it + 1 }.toMutableList() //printMap(newMap) // 2. Flash do { val flashed = BooleanArray(map.size) { false } flash(newMap, flashed) val flashes = flashed.count { it } if (flashes > 0) { increaseAdjacent(newMap, flashed) } totalFlashes += flashes } while (flashes > 0) //printMap(newMap) // 3. Reset newMap.forEachIndexed { index, _ -> flashMap[index] = false if (newMap[index] > 9) { newMap[index] = 0 } } map = newMap return totalFlashes } fun part1(): Int { var totalFlashes = 0 for (s in 1..100) { totalFlashes += step() printMap(map) } return totalFlashes } fun part2(): Int { var step = 0 do { step() step++ val sum = map.sum() } while (sum != 0) return step } } fun main() { val aoc = Day11("day11/input.txt") //println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,384
aoc2021
Apache License 2.0
src/main/kotlin/Puzzle19.kt
namyxc
317,466,668
false
null
object Puzzle19 { @JvmStatic fun main(args: Array<String>) { val input = Puzzle19::class.java.getResource("puzzle19.txt").readText() val calculatedMatchingStringCount = countMatchingStrings(input,Puzzle19::useSameRules) println(calculatedMatchingStringCount) val calculatedMatchingStringCountWithModifiedRules = countMatchingStrings(input,Puzzle19::useModifiedRules) println(calculatedMatchingStringCountWithModifiedRules) } fun countMatchingStrings(input: String, modify: (Int, String) -> String): Int { val rulesAndStrings = input.split("\n\n") val rules = Rules(rulesAndStrings.first().split("\n"), modify) val strings = rulesAndStrings.last().split("\n") return strings.count { string -> rules.accept(string) } } fun useSameRules(index: Int, rules: String) = rules fun useModifiedRules(index: Int, rules: String) = when (index) { 8 -> "42 | 42 8" 11 -> "42 31 | 42 11 31" else -> rules } class Rules(ruleStrings: List<String>, modify: (Int, String) -> String) { private val regexp: Regex? private val ruleCharMap: MutableMap<Int, String> init { val ruleMap = mutableMapOf<Int, List<List<Int>>>() ruleCharMap = mutableMapOf() ruleStrings.forEach{ ruleString -> //1: 2 3 | 3 2 val indexAndRules = ruleString.split(": ") val index = indexAndRules.first().toInt() //1 val originalRules = indexAndRules.last() //2 3 | 3 2 val rules = modify(index, originalRules) if (rules.startsWith("\"")){ ruleCharMap[index] = rules[1].toString() }else { val rulesArray = mutableListOf<List<Int>>() rules.split(" | ").forEach { r -> rulesArray.add(r.split(" ").map { it.toInt() }) } ruleMap[index] = rulesArray } } var couldResolveAnyRules = true while (!ruleCharMap.containsKey(0) && couldResolveAnyRules) { val resolvableRules = ruleMap.filter { rule -> !ruleCharMap.containsKey(rule.key) && rule.value.all { r -> r.all { r2 -> ruleCharMap.containsKey(r2) } } } resolvableRules.forEach { resolvableRule -> val key = resolvableRule.key val value = resolvableRule.value val resolvedValue = value.joinToString("|") { l -> "(" + l.map { ruleNumber -> ruleCharMap[ruleNumber] }.joinToString("") + ")" } ruleCharMap[key] = "($resolvedValue)" } couldResolveAnyRules = resolvableRules.isNotEmpty() } if (ruleCharMap.containsKey(0)) { regexp = ("^" + ruleCharMap[0] + "$").toRegex() }else{ regexp = null } } fun accept(string: String): Boolean { if (regexp != null) return regexp.matches(string) else{ //0 = 8 11 //8 = (42)+ //11 = (42)(31) | 42 42 31 31 //0 = 42{k+}31{k} val regexp42 = ruleCharMap[42] val regexp31 = ruleCharMap[31] var remainingString = string val regexp4231 = "^$regexp42(.+)$regexp31$".toRegex() var matchResult = regexp4231.find(remainingString) val regexp42CapturingGroupCount = regexp42!!.count { it == '(' } + 1 while ( matchResult?.groups?.get(regexp42CapturingGroupCount) != null && remainingString != matchResult.groups[regexp42CapturingGroupCount]!!.value){ remainingString = matchResult.groups[regexp42CapturingGroupCount]!!.value matchResult = regexp4231.find(remainingString) } val regexp42Plus = "^${ruleCharMap[42]}+$".toRegex() return regexp42Plus.matches(remainingString) && remainingString != string } } } }
0
Kotlin
0
0
60fa6991ac204de6a756456406e1f87c3784f0af
4,400
adventOfCode2020
MIT License
Contest/Biweekly Contest 82/Minimum Sum of Squared Difference/MinSumSquaredDiff.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun minSumSquareDiff(nums1: IntArray, nums2: IntArray, k1: Int, k2: Int): Long { val n = nums1.size val differences = IntArray(n) for (i in 0..n-1) { differences[i] = Math.abs(nums1[i]-nums2[i]) } val frequencies: MutableMap<Int, Int> = mutableMapOf() for (difference in differences) { frequencies.put(difference, frequencies.getOrDefault(difference, 0) + 1) } val pq: PriorityQueue<IntArray> = PriorityQueue { a, b -> b[0] - a[0] } for (key in frequencies.keys) { pq.offer(intArrayOf(key, frequencies.get(key)!!)) } var curr = k1 + k2 while (!pq.isEmpty()) { if (curr == 0) { break } val top = pq.poll() val key = top[0] val count = top[1] if (key == 0) { break } var prev = 0 if (!pq.isEmpty()) { prev = pq.peek()[0] } else { pq.offer(intArrayOf(0, 0)) } val diff = key - prev if (count * diff <= curr) { pq.peek()[1] += count curr -= count * diff } else { val equal = curr / count val rest = curr - equal * count val lowerKey = key - equal if (lowerKey == 0) { break } pq.offer(intArrayOf(lowerKey, count-rest)) pq.offer(intArrayOf(lowerKey-1, rest)) curr = 0 } } var ans: Long = 0 while (!pq.isEmpty()) { val top = pq.poll() val key = top[0].toLong() val count = top[1].toLong() ans += key * key * count } return ans } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
2,040
leet-code
MIT License
src/main/kotlin/de/nosswald/aoc/days/Day01.kt
7rebux
722,943,964
false
{"Kotlin": 34890}
package de.nosswald.aoc.days import de.nosswald.aoc.Day // https://adventofcode.com/2023/day/1 object Day01 : Day<Int>(1, "Trebuchet?!") { private val digitsMap = mapOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9, ) override fun partOne(input: List<String>): Int { return input.sumOf { line -> val first = line.first(Char::isDigit) val last = line.last(Char::isDigit) return@sumOf "$first$last".toInt() } } override fun partTwo(input: List<String>): Int { return input.sumOf { line -> val digits = mutableListOf<Int>() var temp = line while (temp.isNotEmpty()) { if (temp.first().isDigit()) { digits += temp.first().digitToInt() } else { digitsMap.forEach { (k, v) -> if (temp.startsWith(k)) { digits += v return@forEach } } } temp = temp.drop(1) } return@sumOf digits.first() * 10 + digits.last() } } @Suppress("spellCheckingInspection") override val partOneTestExamples: Map<List<String>, Int> = mapOf( listOf( "1abc2", "pqr3stu8vwx", "a1b2c3d4e5f", "treb7uchet" ) to 142, ) @Suppress("spellCheckingInspection") override val partTwoTestExamples: Map<List<String>, Int> = mapOf( listOf( "two1nine", "eightwothree", "abcone2threexyz", "xtwone3four", "4nineeightseven2", "zoneight234", "7pqrstsixteen" ) to 281 ) }
0
Kotlin
0
1
398fb9873cceecb2496c79c7adf792bb41ea85d7
1,946
advent-of-code-2023
MIT License
src/Day01.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
fun main() { val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { return input .partitionBy { it.isEmpty() } .maxOfOrNull { elf -> elf.sumOf { it.toInt() } } ?: 0 } private fun part2(input: List<String>): Int { return input.partitionBy { it.isEmpty() } .map { elf -> elf.sumOf { it.toInt() } } .sortedDescending() .take(3) .sum() }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
592
aoc-22
Apache License 2.0
calendar/day14/Day14.kt
starkwan
573,066,100
false
{"Kotlin": 43097}
package day14 import Day import Lines class Day14 : Day() { override fun part1(input: Lines): Any { val wall = Wall(input) val firstSandToFlowOver = { sand: Point -> sand.y >= wall.globalMaxY } return wall.simulate(firstSandToFlowOver) - 1 } override fun part2(input: Lines): Any { val wall = Wall(input) val firstSandToBlockStart = { sand: Point -> sand == wall.startingPoint } return wall.simulate(firstSandToBlockStart) } class Wall(input: Lines) { private val points = mutableSetOf<Point>() val startingPoint = Point(500, 0) var globalMaxY = 0 var floorY = 0 init { input.forEach { it.split("( -> )|,".toRegex()) .map(String::toInt) .windowed(4, 2) .forEach { (x1, y1, x2, y2) -> val minX = minOf(x1, x2) val maxX = maxOf(x1, x2) val minY = minOf(y1, y2) val maxY = maxOf(y1, y2) globalMaxY = maxOf(globalMaxY, maxY) when { x1 == x2 -> for (y in minY..maxY) points.add(Point(x1, y)) y1 == y2 -> for (x in minX..maxX) points.add(Point(x, y1)) else -> error("diagonal rocks!") } } } floorY = globalMaxY + 2 } fun simulate(condition: (Point) -> Boolean): Int { var unit = 1 while (!dropSand(condition)) { unit++ } return unit } private fun dropSand(condition: (Point) -> Boolean): Boolean { var sand = startingPoint var movedSand = fall(sand) while ( sand != movedSand && // the sand is moved movedSand.y < floorY // the moved sand has not fallen over (part1: maxY+1) ) { sand = movedSand movedSand = fall(sand) } points.add(sand) return condition(sand) } private fun fall(p: Point): Point { val nextPoints = listOf( p.copy(y = p.y + 1), p.copy(x = p.x - 1, y = p.y + 1), p.copy(x = p.x + 1, y = p.y + 1) ) nextPoints.forEach { if ( !points.contains(it) && // part 1: not having rock or sand it.y < floorY // part 2: cannot overlap with the floor ) { return it } } return p } } data class Point(val x: Int, val y: Int) }
0
Kotlin
0
0
13fb66c6b98d452e0ebfc5440b0cd283f8b7c352
2,815
advent-of-kotlin-2022
Apache License 2.0
src/Day04.kt
hijst
572,885,261
false
{"Kotlin": 26466}
fun main() { fun IntRange.contains(other: IntRange) = first <= other.first && last >= other.last fun IntRange.overlaps(other: IntRange) = !(first > other.last || last < other.first) fun part1(input: List<Pair<IntRange, IntRange>>): Int = input.count { pair -> pair.first.contains(pair.second) || pair.second.contains(pair.first) } fun part2(input: List<Pair<IntRange, IntRange>>): Int = input.count { pair -> pair.first.overlaps(pair.second) } val testInput = readAssignments("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readAssignments("Day04_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2258fd315b8933642964c3ca4848c0658174a0a5
738
AoC-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/XorAllNums.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <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 /** * 2425. Bitwise XOR of All Pairings * @see <a href="https://leetcode.com/problems/bitwise-xor-of-all-pairings/">Source</a> */ fun interface XorAllNums { operator fun invoke(nums1: IntArray, nums2: IntArray): Int } class XorAllNumsConcise : XorAllNums { override operator fun invoke(nums1: IntArray, nums2: IntArray): Int { var x = 0 var y = 0 for (a in nums1) x = x xor a for (b in nums2) y = y xor b return nums1.size % 2 * y xor nums2.size % 2 * x } } class XorAllNumsSimple : XorAllNums { override operator fun invoke(nums1: IntArray, nums2: IntArray): Int { if (nums1.size % 2 == 0 && nums2.size % 2 == 0) { // if both arrays have even length return 0 } val xorOne = xor(nums1) val xorTwo = xor(nums2) // if both arrays have odd length then xor of both arrays is the answer or else // xor of one even length array is the answer return if (nums1.size % 2 == 1 && nums2.size % 2 == 1) { xorOne xor xorTwo } else if (nums1.size % 2 != 0) { xorTwo } else { xorOne } } private fun xor(nums: IntArray): Int { var res = 0 for (num in nums) { res = res xor num } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,966
kotlab
Apache License 2.0
src/main/kotlin/day2/Solution.kt
krazyglitch
573,086,664
false
{"Kotlin": 31494}
package day2 import util.Utils import java.lang.IllegalArgumentException import java.time.Duration import java.time.LocalDateTime class Solution { /** A = rock, B = paper, C = scissors * * First task: * Assume second parameter maps to rock, paper, scissors. * X = rock, Y = paper, Z = scissors * Calculate score with following table: * * Win: 6 points * Draw: 3 points * Loss: 0 points * * Rock: 1 point * Paper: 2 points * Scissors: 3 points * * Second task: * The second parameter maps to LOSS, DRAW, WIN. * X = loss, Y = draw, Z = win * Use the same logic for scoring */ private fun parseInput(input: String): Pair<Char, Char> { if (input.length == 3) return Pair(input[0], input[2]) throw IllegalArgumentException("$input is not a valid format for a round") } fun part1(data: List<String>): Int { val game = Game() val commands = data.map { parseInput(it) } var sum = 0 commands.forEach { c -> val theirMove = game.getMoveFromChar(c.first) val ourMove = game.getMoveFromChar(c.second) if (theirMove != null) { if (ourMove != null) { val resolution = theirMove.getResolution(ourMove) sum += ourMove.type.score + (resolution?.score ?: 0) } } } return sum } fun part2(data: List<String>): Int { val game = Game() val commands = data.map { parseInput(it) } var sum = 0 commands.forEach{ c -> val theirMove = game.getMoveFromChar(c.first) val resolution = game.getResolutionFromChar(c.second) if (theirMove != null) { if (resolution != null) { val ourMove = theirMove.getMove(resolution) if (ourMove != null) { sum += ourMove.type.score + resolution.score } } } } return sum } } fun main() { val runner = Solution() val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName) println("Solving first part of day 2") var start = LocalDateTime.now() println("The score would be: ${input?.let { runner.part1(it) }} points") var end = LocalDateTime.now() println("Solved first part of day 2") var milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve first part of day 2") println() println("Solving second part of day 2") start = LocalDateTime.now() println("The score would be ${input?.let { runner.part2(it) }} points using the new strategy") end = LocalDateTime.now() println("Solved second part of day 2") milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve second part of day 2") }
0
Kotlin
0
0
db6b25f7668532f24d2737bc680feffc71342491
3,051
advent-of-code2022
MIT License
src/main/kotlin/dev/paulshields/aoc/day6/CustomCustoms.kt
Pkshields
318,658,287
false
null
package dev.paulshields.aoc.day6 import dev.paulshields.aoc.common.readFileAsString fun main() { println(" ** Day 6: Customs Customs ** \n") val delimiterBetweenCustomsForms = "\n\n" val rawAnswersToCustomDeclaration = readFileAsString("/day6/CustomsDeclarationForms.txt") .split(delimiterBetweenCustomsForms) val customsFormsForPart1 = rawAnswersToCustomDeclaration .map(::combineAnswersWhereAnyoneSaidYesIntoCustomsForm) println("There were ${countAllAnsweredQuestions(customsFormsForPart1)} questions answered for part 1!") val customsFormsForPart2 = rawAnswersToCustomDeclaration .map(::combineAnswersWhereEveryoneSaidYesIntoCustomsForm) println("There were ${countAllAnsweredQuestions(customsFormsForPart2)} questions answered for part 2!") } fun combineAnswersWhereAnyoneSaidYesIntoCustomsForm(input: String) = input .replace("\n", "") .toSet() .sorted() .joinToString("") fun combineAnswersWhereEveryoneSaidYesIntoCustomsForm(input: String): String { val eachPersonsAnswers = input .trim() .lines() return eachPersonsAnswers .joinToString("") .toSet() .filter { everyoneAnsweredYesToQuestion(eachPersonsAnswers, it) } .sorted() .joinToString("") } private fun everyoneAnsweredYesToQuestion(eachPersonsAnswers: List<String>, question: Char) = eachPersonsAnswers .count { it.contains(question) } == eachPersonsAnswers.count() fun countAllAnsweredQuestions(customsForms: List<String>) = customsForms .joinToString("") .count()
0
Kotlin
0
0
a7bd42ee17fed44766cfdeb04d41459becd95803
1,586
AdventOfCode2020
MIT License
leetcode/src/tree/Q145.kt
zhangweizhe
387,808,774
false
null
package tree import linkedlist.TreeNode import java.util.* import kotlin.collections.ArrayList fun main() { // 145. 二叉树的后序遍历 // https://leetcode-cn.com/problems/binary-tree-postorder-traversal/ val root = TreeNode(1) root.left = TreeNode(2) root.left?.left = TreeNode(3) root.right = TreeNode(4) root.right?.right = TreeNode(5) println(postorderTraversal3(root)) } fun postorderTraversal(root: TreeNode?): List<Int> { if (root == null) { return ArrayList() } val stack = Stack<TreeNode>() val ret = ArrayList<Int>() var cur = root // 记录上一次处理的节点 var prev:TreeNode? = null while (stack.isNotEmpty() || cur != null) { // 左链加入栈中 while (cur != null && prev != cur) { stack.push(cur) cur = cur.left } val pop = stack.pop() if (pop.right != null && pop.right != prev) { // pop 的右节点不为Null,且 != prev,表示 pop 的右子树还没有遍历 // cur 指向 pop 的右节点,开始遍历右子树 cur = pop.right // 把 pop 加回栈中 stack.push(pop) }else { // pop 没有右节点,或者右节点 == prev,表示 pop 的右子树已经遍历完成,回到了 pop 节点 // 所以把 pop 节点加入结果集中 ret.add(pop.`val`) // prev 指向 pop 节点 prev = pop } } return ret } fun postorderTraversal1(root: TreeNode?): List<Int> { if (root == null) { return ArrayList() } var prev:TreeNode? = null var curr = root val ret = ArrayList<Int>() val stack = Stack<TreeNode>() while (curr != null) { stack.push(curr) curr = curr.left } while (stack.isNotEmpty()) { val pop = stack.pop() if (pop.right != null && pop.right != prev) { stack.push(pop) curr = pop.right while (curr != null) { stack.push(curr) curr = curr.left } }else { ret.add(pop.`val`) prev = pop } } return ret } fun postorderTraversal2(root: TreeNode?): List<Int> { if (root == null) { return ArrayList() } val ret = ArrayList<Int>() val stack = Stack<TreeNode>() var p = root var prev:TreeNode? = null while (p != null || stack.isNotEmpty()) { while (p != null) { stack.push(p) p = p.left } val pop = stack.pop() if (pop.right == null || pop.right == prev) { // pop.right == null 没有右子树 // pop.right == prev,有右子树,右子树遍历过了 // 处理(加入结果集)当前节点 ret.add(pop.`val`) prev = pop }else { // 有右子树,且还没有遍历 p = pop.right stack.push(pop) } } return ret } fun postorderTraversal3(root: TreeNode?): List<Int> { if (root == null) { return ArrayList() } // 左边链先入栈 var cur = root val stack = Stack<TreeNode>() val result = ArrayList<Int>() while (cur != null) { stack.push(cur) cur = cur.left } var prev:TreeNode? = null while (stack.isNotEmpty()) { val pop = stack.pop() if (pop.right == null || pop.right == prev) { // 没有右节点,或者右节点已经访问过 result.add(pop.`val`) prev = pop }else { // 有右节点,且还没访问 stack.push(pop) cur = pop.right while (cur != null) { stack.push(cur) cur = cur.left } } } return result }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
4,077
kotlin-study
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2015/Dec14.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2015 import org.elwaxoro.advent.PuzzleDayTester import kotlin.math.min /** * Reindeer Olympics */ class Dec14 : PuzzleDayTester(14, 2015) { override fun part1(): Any = parse().let { reindeer -> reindeer.maxOf { it.distanceTraveled(2503) } } /** * yikes nobody had ever read this wtf were you thinking doing this instead of a fold or something else non-stupid */ override fun part2(): Any = parse().let { reindeer -> (1..2503L).map { seconds -> reindeer.map { hurr -> hurr to hurr.distanceTraveled(seconds) }.groupBy { it.second }.maxByOrNull { it.key }!!.value.map { (durr, _) -> durr.score++ } } reindeer.maxOf { it.score } } private fun parse() = load().map(Reindeer::parse) data class Reindeer(val name: String, val speed: Long, val flightTime: Long, val restTime: Long, var score: Long = 0) { companion object { fun parse(string: String): Reindeer = string.replace(" can fly ", " ").replace(" km/s for ", " ") .replace(" seconds, but then must rest for ", " ").replace(" seconds.", " ").split(" ") .let { (name, speed, flightTime, restTime) -> Reindeer(name, speed.toLong(), flightTime.toLong(), restTime.toLong()) } } private val totalTime = flightTime + restTime fun distanceTraveled(time: Long): Long { val wholeChunks = (time / totalTime) val wholeChunkDistance = wholeChunks * (speed * flightTime) val remainingChunk = time - (wholeChunks * totalTime) val remainingFlyable = min(remainingChunk, flightTime) val remainingDistance = remainingFlyable * speed return wholeChunkDistance + remainingDistance } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
1,909
advent-of-code
MIT License
src/day7/Code.kt
fcolasuonno
162,470,286
false
null
package day7 import java.io.File fun main(args: Array<String>) { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } sealed class Gate(val output: String) { abstract fun evaluate(values: Map<String, Int>): Int? } fun numberOrValue(input: String, values: Map<String, Int>) = input.toIntOrNull() ?: values[input] class Assign(val input: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input, values) } class And(val input1: String, val input2: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input2, values)?.let { numberOrValue(input1, values)?.and(it) } } class Or(val input1: String, val input2: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input2, values)?.let { numberOrValue(input1, values)?.or(it) } } class LShift(val input1: String, val input2: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input2, values)?.let { numberOrValue(input1, values)?.shl(it) } } class RShift(val input1: String, val input2: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input2, values)?.let { numberOrValue(input1, values)?.shr(it) } } class Not(val input: String, output: String) : Gate(output) { override fun evaluate(values: Map<String, Int>) = numberOrValue(input, values)?.let { it.inv() and 0xffff } } private val lineStructure = """(.+) -> (.+)""".toRegex() private val ops = mutableMapOf<Regex, (List<String>, String) -> Gate>( """([0-9a-z]+)""".toRegex() to { match, out -> Assign(match[1], out) }, """(.+) AND (.+)""".toRegex() to { match, out -> And(match[1], match[2], out) }, """(.+) OR (.+)""".toRegex() to { match, out -> Or(match[1], match[2], out) }, """(.+) LSHIFT (.+)""".toRegex() to { match, out -> LShift(match[1], match[2], out) }, """(.+) RSHIFT (.+)""".toRegex() to { match, out -> RShift(match[1], match[2], out) }, """NOT (.+)""".toRegex() to { match, out -> Not(match[1], out) } ) fun parse(input: List<String>) = input.map { lineStructure.matchEntire(it)?.destructured?.let { val (gate, output) = it if (!ops.any { it.key.matches(gate) }) { println(gate) } ops.mapNotNull { it.key.matchEntire(gate)?.let { result -> it.value(result.groupValues, output) } }.single() } }.requireNoNulls() fun part1(input: List<Gate>): Int? { val values = mutableMapOf<String, Int>() while (input.any { it.evaluate(values) == null }) { input.forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } } input.forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } return values["a"] } fun part2(input: List<Gate>): Int? { var values = mutableMapOf<String, Int>() while (input.any { it.evaluate(values) == null }) { input.forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } } input.forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } val a = values.getValue("a") values = mutableMapOf("b" to a) while (input.filterNot { it.output == "b" }.any { it.evaluate(values) == null }) { input.filterNot { it.output == "b" } .forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } } input.filterNot { it.output == "b" }.forEach { it.evaluate(values)?.let { output -> values[it.output] = output } } return values["a"] }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
3,957
AOC2015
MIT License
src/main/kotlin/year2022/day-23.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2022 import lib.Grid2d import lib.Position import lib.aoc.Day import lib.aoc.Part import lib.math.Itertools import lib.math.Vector fun main() { Day(23, 2022, PartA23(), PartB23()).run() } open class PartA23 : Part() { private lateinit var elfs: MutableSet<Position> private lateinit var directions: MutableList<List<Vector>> override fun parse(text: String) { val grove = Grid2d.ofLines(text.split("\n")) elfs = grove.findAll("#".asIterable()).toMutableSet() directions = mutableListOf( listOf(Vector.at(-1, -1), Vector.at(0, -1), Vector.at(1, -1)), listOf(Vector.at(-1, 1), Vector.at(0, 1), Vector.at(1, 1)), listOf(Vector.at(-1, -1), Vector.at(-1, 0), Vector.at(-1, 1)), listOf(Vector.at(1, -1), Vector.at(1, 0), Vector.at(1, 1)), ) } override fun compute(): String { repeat(10) { doRound() } val (xMin, xMax, yMin, yMax) = findMinMax() return ((xMax + 1 - xMin) * (yMax + 1 - yMin) - elfs.size).toString() } protected fun doRound(): Boolean { val propositions = mutableMapOf<Position, Position?>() elfs.forEach loop@{ elf -> if (directions.flatten().all { elf + it !in elfs }) { return@loop } directions.forEach { directionList -> if (directionList.all { elf + it !in elfs }) { val newPos = elf + directionList[1] if (newPos in propositions) { propositions[newPos] = null } else { propositions[newPos] = elf } return@loop } } } var anyElfMoving = false propositions.filter { (_, elf) -> elf != null }.forEach { (proposition, elf) -> elfs.remove(elf) elfs.add(proposition) anyElfMoving = true } val firstDirection = directions.removeFirst() directions.add(firstDirection) return anyElfMoving } private fun findMinMax(): List<Int> { val yMin = elfs.minOf { it[1] } val yMax = elfs.maxOf { it[1] } val xMin = elfs.minOf { it[0] } val xMax = elfs.maxOf { it[0] } return listOf(xMin, xMax, yMin, yMax) } override val exampleAnswer: String get() = "110" } class PartB23 : PartA23() { override fun compute(): String { for (roundNumber in Itertools.count(1)) { val moving = doRound() if (!moving) { return roundNumber.toString() } } error("should not be reached") } override val exampleAnswer: String get() = "20" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,876
Advent-Of-Code-Kotlin
MIT License
day19/Part2.kt
anthaas
317,622,929
false
null
import java.io.File fun main(args: Array<String>) { val input = File("input2.txt").bufferedReader().use { it.readText() }.split("\n\n") val rules = input[0].split("\n").associate { it.split(": ").let { (left, right) -> left.toInt() to right } }.toMutableMap().toSortedMap() //hack to skip recursion (0 until 5).forEach { val newRule8 = "( " + rules[8] + " )" val newRule11 = "( " + rules[11] + " )" rules[8] = rules[8]!!.replace("8", newRule8) rules[11] = rules[11]!!.replace("11", newRule11) } rules[8] = rules[8]!!.replace("8", "") rules[11] = rules[11]!!.replace("11", "") val inputs = input[1].split("\n") val result = convertToRegex(rules).let { regex -> inputs.count { regex.toRegex().matches(it) } } println(result) } private fun convertToRegex(rules: Map<Int, String>): String { var regexStr = rules[0]!!.removeSurrounding("\"").split(" ").let { listOf("(") + it + ")" } while (regexStr.any { s -> s.toIntOrNull() != null }) { regexStr = regexStr.map { s -> when (s.toIntOrNull()) { null -> listOf(s) else -> rules[s.toInt()]!!.removeSurrounding("\"").split(" ").let { listOf("(") + it + ")" } } }.flatten() } return regexStr.joinToString("") }
0
Kotlin
0
0
aba452e0f6dd207e34d17b29e2c91ee21c1f3e41
1,319
Advent-of-Code-2020
MIT License
src/main/kotlin/aoc2016/GridComputing.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2016 import komu.adventofcode.utils.Direction import komu.adventofcode.utils.Direction.DOWN import komu.adventofcode.utils.Direction.RIGHT import komu.adventofcode.utils.Point import komu.adventofcode.utils.nonEmptyLines fun gridComputing1(input: String) = Grid.parse(input).viablePairs() // Part two is not really feasible to solve with assuming a fully general grid. By eyeballing the // debug output of the grid it's pretty easy to figure out the correct route fun gridComputing2(input: String): Int { val grid = Grid.parse(input) // path to move around the wall to the left side item val path = "ulllllllllllllllllllllllllluuuuuuuuuuuuuuuuuuuuuuuurrrrrrrrrrrrrrrrrrrrrrrrrrrrurl".map { d -> Direction.values().find { it.name.lowercase()[0] == d } ?: error("invalid char '$d' ") } grid.followPath(Point(34, 26), path) grid.dump() // it takes 5 moves to rotate the items to move one to the left return 261 } private class Grid(nodes: List<GridNode>) { private val width = nodes.maxOf { it.point.x } + 1 private val height = nodes.size / width private val nodes = nodes.associateBy { it.point } private var dataLocation = Point(width - 1, 0) fun viablePairs() = nodes.values.sumOf { a -> nodes.values.count { b -> a.isViablePairWith(b) } } private fun move(from: GridNode, to: GridNode) { to.used += from.used from.used = 0 if (from.point == dataLocation) dataLocation = to.point } fun dump() { println((0 until width).joinToString(separator = " ", prefix = " ") { String.format("%-2d", it) }) for (y in 0 until height) { val yLabel = String.format("%2d ", y) println((0 until width).joinToString(separator = "", prefix = yLabel, postfix = yLabel) { x -> val point = Point(x, y) val node = nodes[point]!! val value = if (node.total > 400) "#####" else String.format("%2d%s%-2d", node.used, if (dataLocation == point) '!' else '/', node.total) val right = nodes[point + RIGHT] val next = when { right != null && node.isViablePairWith(right) -> ">" right != null && right.isViablePairWith(node) -> "<" else -> " " } "$value $next " }) println((0 until width).joinToString(prefix = " ", separator = " ") { x -> val point = Point(x, y) val node = nodes[point]!! val down = nodes[point + DOWN] when { down != null && node.isViablePairWith(down) -> "v" down != null && down.isViablePairWith(node) -> "^" else -> " " } }) } } fun followPath(active: Point, path: List<Direction>) { var node = nodes[active] ?: error("no such node: $active") for (d in path) { val newNode = nodes[node.point + d] ?: error("no such node: ${node.point + d}") move(newNode, node) node = newNode } } companion object { private val regex = Regex("""/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+\d+T\s+\d+%""") fun parse(input: String) = Grid(input.nonEmptyLines().filter { it.startsWith("/dev") }.map { parseNode(it) }) private fun parseNode(s: String): GridNode { val (x, y, total, used) = regex.matchEntire(s)?.destructured ?: error("invalid input '$s'") return GridNode(Point(x.toInt(), y.toInt()), total.toInt(), used.toInt()) } } } private data class GridNode(val point: Point, val total: Int, var used: Int) { val avail: Int get() = total - used fun isViablePairWith(b: GridNode): Boolean = used != 0 && this !== b && used <= b.avail }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
4,038
advent-of-code
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/Utils.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms import dev.funkymuse.datastructuresandalgorithms.sort.selectionSort import java.util.Collections internal fun <T> List<T>.swap(i: Int, j: Int): List<T> { if (isInBounds(i) && isInBounds(j)) { Collections.swap(this, i, j) } return this } private fun <T> List<T>.isInBounds(index: Int): Boolean { return index in 0..lastIndex } fun <T> MutableList<T>.swapAt(first: Int, second: Int) { val aux = this[first] this[first] = this[second] this[second] = aux } /** * Given a list of Comparable elements, bring all instances of a given value in the list to the right side of the array. * @receiver MutableList<T> * @param element T */ fun <T : Comparable<T>> MutableList<T>.rightAlign(element: T) { if (size < 2) return var searchIndex = size - 2 while (searchIndex >= 0) { if (this[searchIndex] == element) { var moveIndex = searchIndex while (moveIndex < size - 1 && this[moveIndex + 1] != element) { swapAt(moveIndex, moveIndex + 1) moveIndex++ } } searchIndex-- } } fun <T : Comparable<T>> MutableList<T>.biggestDuplicate(): T? { selectionSort() for (i in (1 until this.size).reversed()) { if (this[i] == this[i - 1]) { return this[i] } } return null } /** * The time complexity of this solution is O(n). * @receiver MutableList<T> */ fun <T : Comparable<T>> MutableList<T>.rev() { var left = 0 var right = this.size - 1 while (left < right) { swapAt(left, right) left++ right-- } } fun <T> Array<T>.swapAt(first: Int, second: Int) { val aux = this[first] this[first] = this[second] this[second] = aux } val ascending = Comparator { first: Int, second: Int -> when { first < second -> -1 first > second -> 1 else -> 0 } } val descending = Comparator { first: Int, second: Int -> when { first < second -> 1 first > second -> -1 else -> 0 } }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
2,128
KAHelpers
MIT License
day07/src/main/kotlin/Main.kt
ickybodclay
159,694,344
false
null
import java.io.File fun main() { val input = File(ClassLoader.getSystemResource("input.txt").file) val stepRegex = Regex("Step ([A-Z]) must be finished before step ([A-Z]) can begin.") val stepMap = mutableMapOf<String, ArrayList<String>>() input.readLines().map { val stepMatch = stepRegex.matchEntire(it)!! val preReq = stepMatch.groups[1]!!.value val step = stepMatch.groups[2]!!.value if (!stepMap.containsKey(step)) { stepMap[step] = ArrayList() } if (!stepMap.containsKey(preReq)) { stepMap[preReq] = ArrayList() } stepMap[step]!!.add(preReq) } val sortedKeys = ArrayList(stepMap.keys.sorted()) val timeToCompleteMap = mutableMapOf<String, Int>() val completedSteps = ArrayList<String>() for (key in sortedKeys) { timeToCompleteMap[key] = timeToCompleteStep(key) } println(timeToCompleteMap) var time = 0 while (completedSteps.size != stepMap.size) { val workersCount = 5 var workersActive = 0 val justCompleted = ArrayList<String>() var workerA = "." var workerB = "." var workerC = "." var workerD = "." var workerE = "." for (key in sortedKeys) { if (workersActive < workersCount && (stepMap[key]!!.isEmpty() || completedSteps.containsAll(stepMap[key]!!))) { when (workersActive) { 0 -> workerA = key 1 -> workerB = key 2 -> workerC = key 3 -> workerD = key 4 -> workerE = key } timeToCompleteMap[key] = timeToCompleteMap[key]!!.minus(1) if (timeToCompleteMap[key]!! <= 0) { justCompleted.add(key) } workersActive++ } } println("${time.toString().padStart(4, '0')}\t$workerA\t$workerB\t$workerC\t$workerD\t$workerE\t$completedSteps") sortedKeys.removeAll(justCompleted) completedSteps.addAll(justCompleted) time++ } println(timeToCompleteMap) println("total time = $time") // for(step in completedSteps) // print(step) // println() } private val charOffset = "A"[0].toInt() // 65 fun timeToCompleteStep(step: String) : Int { return (step[0].toInt() - charOffset + 1) + 60 }
0
Kotlin
0
0
9a055c79d261235cec3093f19f6828997b7a5fba
2,451
aoc2018
Apache License 2.0
src/main/kotlin/13-jun.kt
aladine
276,334,792
false
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
class Solution13jun { fun largestDivisibleSubset(nums: IntArray): List<Int> { if (nums.isEmpty()) return emptyList() var l = Array(nums.size) { _ -> 1 } nums.sort() var maxSoFar = 0 var maxIndex: Int = -1 for ((i, v) in nums.withIndex()) { // or for i in nums.indices for (j in 0 until i) if (v % nums[j] == 0 && l[i] < l[j] + 1) l[i] = l[j] + 1 if (maxSoFar < l[i]) { maxSoFar = l[i] maxIndex = i } } val ans = Array<Int>(maxSoFar) { -1 } var c = 0 while (maxIndex >= 0) { ans.set(c++, nums[maxIndex]) var hasChange = false for (j in maxIndex - 1 downTo 0) { if (nums[maxIndex] % nums[j] == 0 && l[maxIndex] == l[j] + 1) { maxIndex = j hasChange = true break } } if (!hasChange) break } return ans.toList() } // add an array to store the preList of pair(i,j) }
0
C++
1
1
54b7f625f6c4828a72629068d78204514937b2a9
1,141
awesome-leetcode
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1287/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1287 /** * LeetCode page: [1287. Element Appearing More Than 25% In Sorted Array](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/); */ class Solution { /* Complexity: * Time O(LogN) and Space O(1) where N is the size of arr; */ fun findSpecialInteger(arr: IntArray): Int { val threshold = arr.size / 4 + 1 for (index in arr.indices step threshold) { if (count(arr, arr[index]) >= threshold) { return arr[index] } } throw NoSuchElementException() } private fun count(sorted: IntArray, element: Int): Int { val left = leftInsertionIndex(sorted, element) if (left == sorted.size || sorted[left] != element) { return 0 } val right = rightInsertionIndex(sorted, element) return right - left } private fun leftInsertionIndex(sorted: IntArray, target: Int): Int { if (target <= sorted.first()) { return 0 } if (target > sorted.last()) { return sorted.size } var left = 0 var right = sorted.lastIndex while (left < right) { val mid = (left + right) ushr 1 val value = sorted[mid] if (value < target) { left = mid + 1 } else { right = mid } } return left } private fun rightInsertionIndex(sorted: IntArray, target: Int): Int { if (target >= sorted.last()) { return sorted.size } if (target < sorted.first()) { return 0 } var left = 0 var right = sorted.lastIndex while (left < right) { val mid = (left + right) ushr 1 val value = sorted[mid] if (value <= target) { left = mid + 1 } else { right = mid } } return left } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,036
hj-leetcode-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/LetterCombinations.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 17. 电话号码的字母组合 * * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。 * 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 */ class LetterCombinations { companion object { @JvmStatic fun main(args: Array<String>) { LetterCombinations().letterCombinations("23").forEach { println(it) } LetterCombinations().letterCombinations("").forEach { println(it) } LetterCombinations().letterCombinations("2").forEach { println(it) } } } fun letterCombinations(digits: String): List<String> { if (digits.isEmpty()) return arrayListOf() val letterMap = hashMapOf<Int, String>() letterMap[2] = "abc" letterMap[3] = "def" letterMap[4] = "ghi" letterMap[5] = "jkl" letterMap[6] = "mno" letterMap[7] = "pqrs" letterMap[8] = "tuv" letterMap[9] = "wxyz" // 234 val length = digits.length val result = arrayListOf<String>() backtracking(letterMap, 0, digits, StringBuilder(), length, result) return result } private fun backtracking(letterMap: Map<Int, String>, index: Int, digits: String, letterBuilder: StringBuilder, length: Int, result: ArrayList<String>) { if (index == length) { result.add(letterBuilder.toString()) return } val currentLetter = letterMap[digits[index] - '0'] ?: "" val size = currentLetter.length for (i in 0 until size) { letterBuilder.append(currentLetter[i].toString()) backtracking(letterMap, index + 1, digits, letterBuilder, length, result) letterBuilder.deleteCharAt(index) } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,990
daily_algorithm
Apache License 2.0
core/src/main/kotlin/com/bsse2018/salavatov/flt/algorithms/CYK.kt
vsalavatov
241,599,920
false
{"Kotlin": 149462, "ANTLR": 1960}
package com.bsse2018.salavatov.flt.algorithms import com.bsse2018.salavatov.flt.grammars.ContextFreeGrammar import com.bsse2018.salavatov.flt.grammars.ContextFreeGrammar.Companion.Epsilon fun CYKQuery(cnfGrammar: ContextFreeGrammar, query: List<String>): Boolean { if (query.isEmpty()) { return cnfGrammar.rules.contains( ContextFreeGrammar.Rule( cnfGrammar.start, listOf(Epsilon) ) ) } val dp = List(query.size) { List(query.size + 1) { mutableSetOf<String>() } } val symRules = cnfGrammar.rules.filter { it.isTerminal() && !it.to.contains(Epsilon) } val concatRules = cnfGrammar.rules.filter { !it.isTerminal() } symRules.forEach { rule -> val sym = rule.to[0] for (i in query.indices) { if (query[i] == sym) dp[i][i + 1].add(rule.from) } } for (len in 2..query.size) { for (left in 0..(query.size - len)) { val right = left + len concatRules.forEach { rule -> val n1 = rule.to[0] val n2 = rule.to[1] for (border in left until right) { if (dp[left][border].contains(n1) && dp[border][right].contains(n2)) { dp[left][right].add(rule.from) break } } } } } return dp[0][query.size].contains(cnfGrammar.start) }
0
Kotlin
0
1
c1c229c113546ef8080fc9d3568c5024a22b80a5
1,484
bsse-2020-flt
MIT License
src/main/kotlin/io/github/vihangpatil/kotlintricks/range/RangeExtensions.kt
vihangpatil
149,867,318
false
null
package io.github.vihangpatil.kotlintricks.range /** * @param[other] [ClosedRange]<[T]> * @return [Boolean] if this [Comparable]<[T]> overlaps with [other] */ private fun <T : Comparable<T>> ClosedRange<T>.overlapsWith( other: ClosedRange<T> ): Boolean { return (other.start in start..endInclusive || other.endInclusive in start..endInclusive) } /** * @param[other] [ClosedRange]<[T]> * @return [Collection]<[ClosedRange]<[T]>> with [this] and [other] if they do not overlap, or with just one merged * [ClosedRange]<[T]> if they overlap. */ private fun <T : Comparable<T>> ClosedRange<T>.mergeWith( other: ClosedRange<T> ): Collection<ClosedRange<T>> { // if they do not overlap return if (!overlapsWith(other)) { // then return them separately listOf(this, other) } else { // else merge them listOf(minOf(start, other.start)..maxOf(endInclusive, other.endInclusive)) } } /** * @return [Collection]<[ClosedRange]<[T]>> with overlapping [ClosedRange]<[T]> merged. */ fun <T : Comparable<T>> Collection<ClosedRange<T>>.mergeRanges(): Collection<ClosedRange<T>> { // no changes for empty collection or collection with single element if (this.size < 2) { return this } return sortedBy { it.start } // sort by start of range .fold(initial = emptyList()) { list: List<ClosedRange<T>>, element: ClosedRange<T> -> if (list.isEmpty()) { // for first element listOf(element) } else { // Attempt to merge last of the list with the element. // If they are overlapping, [mergeWith] will return collection with single merged element. // Or else, it will return list with two elements. list.last().mergeWith(element) + // drop last element to avoid it to be duplicate list.dropLast(1) } } } /** * @param[asRange] Function to map [E] to [ClosedRange]<[T]>. * @param[asElement] Function to map [ClosedRange]<[T]> to [E]. * @return [Collection]<[E]> with overlapping [ClosedRange]<[T]> merged. */ fun <E, T : Comparable<T>> Collection<E>.mergeBy( asRange: (E) -> ClosedRange<T>, asElement: (ClosedRange<T>) -> E ): Collection<E> { // no changes for empty collection or collection with single element if (this.size < 2) { return this } return sortedBy { element -> // sort by start of range asRange(element).start }.fold(initial = emptyList()) { list: List<E>, element: E -> if (list.isEmpty()) { // for first element listOf(element) } else { // Attempt to merge last of the list with the element. // If they are overlapping, [mergeWith] will return collection with single merged element. // Or else, it will return list with two elements. asRange(list.last()).mergeWith(asRange(element)).map(asElement) + // drop last element to avoid it to be duplicate list.dropLast(1) } } }
0
Kotlin
0
1
d1f3da3796f4339d5c7e964d0d39db2ece2c7290
3,212
kotlin-tricks
MIT License
src/Day10.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
fun main() { fun part1(input: List<String>): Int { val cycles = mutableListOf<Int>() val crt = MutableList(240) { Char(0) } var register = 1 for (c in input) { cycles.add(register) if (c.startsWith("noop")) continue val value = c.split(" ").last().toInt() cycles.add(register) register += value } for ((k, value) in cycles.withIndex()) { val position = k % 240 crt[position] = if (position % 40 in value - 1..value + 1) '$' else '.' } for (row in crt.chunked(40)) { for (c in row) { print(" $c ") } println() } return cycles.mapIndexed { k, value -> (k + 1) * value }.filterIndexed { k, _ -> (k + 1) % 40 == 20 } .sumOf { it } } val input = readInput("Day10") check(part1(input) == 10760) }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
940
kotlin-advent-of-code-22
Apache License 2.0
src/main/kotlin/days/Day01.kt
julia-kim
435,257,054
false
{"Kotlin": 15771}
package days import readInput fun main() { fun part1(input: List<String>): Int { val it = input.map { it.toInt() }.iterator() var count = 0 var previousDepthMeasurement = it.next() while (it.hasNext()) { val depthMeasurement = it.next() if (depthMeasurement > previousDepthMeasurement) count++ previousDepthMeasurement = depthMeasurement } return count } fun part2(input: List<String>): Int { var count = 0 val windows = input.map { it.toInt() }.windowed(3, 1) val it = windows.map { it.sum() }.iterator() var previousSummedMeasurement = it.next() while (it.hasNext()) { val summedMeasurement = it.next() if (summedMeasurement > previousSummedMeasurement) count++ previousSummedMeasurement = summedMeasurement } return count } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 7) check(part2(testInput) == 5) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5febe0d5b9464738f9a7523c0e1d21bd992b9302
1,196
advent-of-code-2021
Apache License 2.0
25.kt
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
class Day25 { val connections = HashMap<String, ArrayList<String>>() fun run() { while (true) { var line = readlnOrNull() ?: break val items = Regex("[a-z]+").findAll(line).map { it.value }.toList() connections[items[0]] = ArrayList(items.subList(1, items.size)) for (c in items.subList(1, items.size)) { if (c !in connections) { connections[c] = ArrayList() } connections[c]!!.add(items[0]) } } val paths = HashMap<Pair<String, String>, Int>() val components = ArrayList(connections.keys) for (i in 0..<(components.size - 1)) { for (j in (i + 1)..<components.size) { val queue = ArrayDeque<String>() val seen = HashSet<String>() queue.add(components[i]) while (queue.isNotEmpty()) { val c = queue.removeFirst() if (c == components[j]) break if (!seen.add(c)) continue for (conn in connections[c]!!) { paths[Pair(c, conn)] = (paths[Pair(c, conn)] ?: 0) + 1 queue.add(conn) } } } } val links = paths.entries.toList().sortedByDescending { it.value }.take(3) for (link in links) { connections[link.key.first]!!.remove(link.key.second) connections[link.key.second]!!.remove(link.key.first) } val queue = ArrayDeque<String>() val seen = HashSet<String>() queue.add(connections.keys.last()) while (queue.isNotEmpty()) { val c = queue.removeFirst() if (!seen.add(c)) continue for (conn in connections[c]!!) { queue.add(conn) } } println(seen.size * (components.size - seen.size)) } } fun main() { Day25().run() }
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
2,008
aoc2023
MIT License
src/main/kotlin/day14/Code.kt
fcolasuonno
317,324,330
false
null
package day14 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) part1(parsed) part2(parsed) } private val lineStructure1 = """mask = (.+)""".toRegex() private val lineStructure2 = """mem\[(\d+)] = (\d+)""".toRegex() fun parse(input: List<String>) = input.map { lineStructure1.matchEntire(it)?.destructured?.let { val (mask) = it.toList() mask } to lineStructure2.matchEntire(it)?.destructured?.let { val (pos, value) = it.toList() pos.toLong() to value.toLong() } }.requireNoNulls() data class Program( val mem: MutableMap<Long, Long> = mutableMapOf(), var andMask: Long = 0L, var orMask: Long = 0L, var float: List<Long> = emptyList() ) fun part1(input: List<Pair<String?, Pair<Long, Long>?>>) { val res = input.fold(Program()) { program, (m, v) -> program.apply { m?.let { mask -> andMask = mask.parse('0').inv() orMask = mask.parse('1') } v?.let { (pos, value) -> mem[pos] = value.and(andMask).or(orMask) } } }.mem.values.sum() println("Part 1 = $res") } fun part2(input: List<Pair<String?, Pair<Long, Long>?>>) { val res = input.fold(Program()) { program, (m, v) -> program.apply { m?.let { mask -> andMask = mask.parse('X').inv() orMask = mask.parse('1') float = mask.withIndex().filter { it.value == 'X' }.map { 2L.shl(it.index) } } v?.let { (pos, value) -> float.fold(listOf(pos.and(andMask).or(orMask))) { acc, l -> acc + acc.map { it + l } }.forEach { mem[it] = value } } } }.mem.values.sum() println("Part 2 = $res") } private fun String.parse(char: Char) = map { if (it == char) '1' else '0' }.joinToString("").toLong(2)
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
2,169
AOC2020
MIT License
src/main/kotlin/adventofcode/year2023/Day02CubeConundrum.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2023 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.product class Day02CubeConundrum(customInput: PuzzleInput? = null) : Puzzle(customInput) { override fun partOne() = input .lines() .map(Game::invoke) .filter { game -> game.isPossible(12, 13, 14) } .sumOf(Game::id) override fun partTwo() = input .lines() .map(Game::invoke) .sumOf(Game::minimumCubePower) companion object { private data class Turn( val red: Int, val green: Int, val blue: Int ) { companion object { operator fun invoke(turn: String): Turn { val red = """(\d+) red""".toRegex().find(turn)?.destructured?.component1()?.toInt() ?: 0 val green = """(\d+) green""".toRegex().find(turn)?.destructured?.component1()?.toInt() ?: 0 val blue = """(\d+) blue""".toRegex().find(turn)?.destructured?.component1()?.toInt() ?: 0 return Turn(red, green, blue) } } } private data class Game( val id: Int, val turns: List<Turn> ) { fun isPossible(red: Int, green: Int, blue: Int) = turns .filterNot { turn -> turn.red <= red && turn.green <= green && turn.blue <= blue } .isEmpty() fun minimumCubePower() = listOf(turns.maxOf(Turn::red), turns.maxOf(Turn::green), turns.maxOf(Turn::blue)).product() companion object { operator fun invoke(input: String): Game { val id = input.split(": ").first().split(" ").last().toInt() val turns = input.split(": ").last().split("; ").map(Turn::invoke) return Game(id, turns) } } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,934
AdventOfCode
MIT License
src/main/kotlin/g2801_2900/s2827_number_of_beautiful_integers_in_the_range/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2801_2900.s2827_number_of_beautiful_integers_in_the_range // #Hard #Dynamic_Programming #Math #2023_12_18_Time_169_ms_(100.00%)_Space_38.7_MB_(100.00%) import kotlin.math.max @Suppress("kotlin:S107") class Solution { private lateinit var dp: Array<Array<Array<Array<IntArray>>>> private var maxLength = 0 fun numberOfBeautifulIntegers(low: Int, high: Int, k: Int): Int { val num1 = low.toString() val num2 = high.toString() maxLength = max(num1.length.toDouble(), num2.length.toDouble()).toInt() dp = Array(4) { Array(maxLength) { Array(maxLength) { Array(maxLength) { IntArray(k) } } } } for (a in dp) { for (b in a) { for (c in b) { for (d in c) { d.fill(-1) } } } } return dp(num1, num2, 0, 3, 0, 0, 0, 0, k) } private fun dp( low: String, high: String, i: Int, mode: Int, odd: Int, even: Int, num: Int, rem: Int, k: Int ): Int { if (i == maxLength) { return if (num % k == 0 && odd == even) 1 else 0 } if (dp[mode][i][odd][even][rem] != -1) { return dp[mode][i][odd][even][rem] } var res = 0 val lowLimit = mode % 2 == 1 val highLimit = mode / 2 == 1 var start = 0 var end = 9 if (lowLimit) { start = digitAt(low, i) } if (highLimit) { end = digitAt(high, i) } for (j in start..end) { var newMode = 0 if (j == start && lowLimit) { newMode += 1 } if (j == end && highLimit) { newMode += 2 } var newEven = even if (num != 0 || j != 0) { newEven += if (j % 2 == 0) 1 else 0 } val newOdd = odd + (if (j % 2 == 1) 1 else 0) res += dp( low, high, i + 1, newMode, newOdd, newEven, num * 10 + j, (num * 10 + j) % k, k ) } dp[mode][i][odd][even][rem] = res return res } private fun digitAt(num: String, i: Int): Int { val index = num.length - maxLength + i return if (index < 0) 0 else num[index].code - '0'.code } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,591
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g1801_1900/s1883_minimum_skips_to_arrive_at_meeting_on_time/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1883_minimum_skips_to_arrive_at_meeting_on_time // #Hard #Array #Dynamic_Programming #2023_06_22_Time_278_ms_(100.00%)_Space_44.2_MB_(100.00%) class Solution { fun minSkips(dist: IntArray, speed: Int, hoursBefore: Int): Int { val len = dist.size // dp[i][j] finish ith road, skip j times; val dp = Array(len) { IntArray(len) } dp[0][0] = dist[0] for (i in 1 until len) { dp[i][0] = (dp[i - 1][0] + speed - 1) / speed * speed + dist[i] } for (i in 1 until len) { for (j in 0..i) { if (j > 0) { dp[i][j] = dp[i - 1][j - 1] + dist[i] } if (j <= i - 1) { dp[i][j] = Math.min( dp[i][j], (dp[i - 1][j] + speed - 1) / speed * speed + dist[i] ) } } } for (i in 0 until len) { if (dp[len - 1][i] <= speed.toLong() * hoursBefore) { return i } } return -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,091
LeetCode-in-Kotlin
MIT License
core-kotlin-modules/core-kotlin-collections-map/src/test/kotlin/com/baeldung/frequencymap/FrequencyMapUnitTest.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.frequencymap import org.junit.Test import java.util.* import kotlin.test.assertEquals class FrequencyMapUnitTest { @Test fun `test frequency map using mutable map method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) assertEquals(expectedMap, frequencyMapUsingMutableMap(list)) } @Test fun `test frequency map using groupingBy() method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = list.groupingBy { it }.eachCount() assertEquals(expectedMap, actualMap) } @Test fun `test frequency map using frequency() method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = mutableMapOf<Int, Int>() for(value in list.distinct()){ actualMap[value] = Collections.frequency(list, value) } assertEquals(expectedMap, actualMap) } @Test fun `test frequency map using treemap method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = frequencyMapUsingTreeMapMethod(list) val sortedList = list.sorted().distinct() assertEquals(expectedMap, actualMap) assertEquals(sortedList, actualMap.keys.toList()) } @Test fun `test frequency map using binary search method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = frequencyMapUsingBinarySearchMethod(list) assertEquals(expectedMap, actualMap) } @Test fun `test frequency map using hashset method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = FrequencyMapUsingHashSetMethod(list) assertEquals(expectedMap, actualMap) } @Test fun `test frequency map using merge() method`() { val list = listOf(1, 2, 1, 3, 2, 4, 4, 7, 9, 7, 3, 2, 1) val expectedMap = mapOf(1 to 3, 2 to 3, 3 to 2, 4 to 2, 7 to 2, 9 to 1) val actualMap = FrequencyMapUsingMergeMethod(list) assertEquals(expectedMap, actualMap) } } fun frequencyMapUsingMutableMap(list: List<Int>): MutableMap<Int, Int> { val map = mutableMapOf<Int, Int>() for (value in list) { val count = map.getOrDefault(value, 0) map[value] = count + 1 } return map } fun frequencyMapUsingTreeMapMethod(list: List<Int>): MutableMap<Int, Int>{ val map = TreeMap<Int, Int>() list.forEach { element -> map[element] = map.getOrDefault(element, 0) + 1 } return map } fun frequencyMapUsingBinarySearchMethod(list: List<Int>): MutableMap<Int, Int>{ val sortedList = list.sorted() val map = mutableMapOf<Int, Int>() sortedList.distinct().forEach { element -> val firstIndex = sortedList.indexOfFirst { it == element } val lastIndex = sortedList.indexOfLast { it == element } val freq = lastIndex - firstIndex + 1 map[element] = freq } return map } fun FrequencyMapUsingHashSetMethod(list: List<Int>): Map<Int, Int> { val set = HashSet(list) val map = mutableMapOf<Int, Int>() for (elem in set) { map[elem] = Collections.frequency(list, elem) } return map } fun FrequencyMapUsingMergeMethod(list: List<Int>): Map<Int, Int> { val map = mutableMapOf<Int, Int>() for (element in list) { map.merge(element, 1) { oldValue, _ -> oldValue + 1 } } return map }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
3,944
kotlin-tutorials
MIT License
src/main/kotlin/g2301_2400/s2398_maximum_number_of_robots_within_budget/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2398_maximum_number_of_robots_within_budget // #Hard #Array #Binary_Search #Heap_Priority_Queue #Prefix_Sum #Sliding_Window #Queue // #2023_07_02_Time_507_ms_(100.00%)_Space_48.9_MB_(100.00%) class Solution { // use sliding window to track the largest in a way that the sliding window only grows. // then the maximum size is the size of the sliding window at the end. // if condition is met, we just grow the sliding window. // if condition is not met, we shift the sliding window with the same size to the next position. // e.g., if [0,3] is valid, next time we will try [0,4]. // if [0,3] is invalid, next time we will try [1,4], // by adjusting the window to [1,3] first in the current round. fun maximumRobots(chargeTimes: IntArray, runningCosts: IntArray, budget: Long): Int { val n = chargeTimes.size // [front, end). val deque = IntArray(n) var front = 0 var end = 0 var sum: Long = 0 var left = 0 var right = 0 while (right < n) { // add right into the sliding window, so the window becomes [left, right]. // update sliding window max and window sum. while (end - front > 0 && chargeTimes[deque[end - 1]] <= chargeTimes[right]) { --end } deque[end++] = right sum += runningCosts[right].toLong() // if the condition is met in the window, do nothing, // so the next window size will become one larger. // if the condition is not met in the window, shrink one from the front, // so the next window size will stay the same. if (chargeTimes[deque[front]] + (right - left + 1) * sum > budget) { while (end - front > 0 && deque[front] <= left) { ++front } sum -= runningCosts[left].toLong() ++left } ++right } return right - left } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,054
LeetCode-in-Kotlin
MIT License
day15/Kotlin/day15.kt
Ad0lphus
353,610,043
false
{"C++": 195638, "Python": 139359, "Kotlin": 80248}
import java.io.* import java.util.* fun print_day_15() { val yellow = "\u001B[33m" val reset = "\u001b[0m" val green = "\u001B[32m" println(yellow + "-".repeat(25) + "Advent of Code - Day 15" + "-".repeat(25) + reset) println(green) val process = Runtime.getRuntime().exec("figlet Chiton -c -f small") val reader = BufferedReader(InputStreamReader(process.inputStream)) reader.forEachLine { println(it) } println(reset) println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n") } fun main() { print_day_15() Day15().part_1() Day15().part_2() println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n") } class Day15 { data class Node(val x:Int = 0, val y:Int = 0, val dist: Int = 0) fun part_1() { val grid = File("../Input/day15.txt").readLines().map { it.toCharArray().map{ it.digitToInt() } } print("Puzzle 1: ") findShortestPath(grid) } private fun findShortestPath(grid: List<List<Int>>) { val pathways = Array(grid.size) { Array(grid[0].size) { Int.MAX_VALUE } } val queue = PriorityQueue<Node> { nodeA, nodeB -> nodeA.dist - nodeB.dist } pathways[0][0] = 0 queue.add(Node(0,0, 0)) while(queue.isNotEmpty()) { val (x, y, dist) = queue.poll() listOf(x to y + 1, x to y - 1, x + 1 to y, x - 1 to y).forEach { (X, Y) -> if (X in grid.indices && Y in grid[0].indices && pathways[X][Y] > dist + grid[X][Y]) { pathways[X][Y] = dist + grid[X][Y] queue.add(Node(X, Y, pathways[X][Y])) } } } println(pathways.last().last()) } fun part_2() { val input = File("../Input/day15.txt").readLines() val totalY = input.size val totalX = input.first().length val grid = (0 until totalY * 5).map { y -> (0 until totalX * 5).map { x -> val baseNum = input[y % totalY][x % totalX].digitToInt() val tileDistance = (x/totalX) + (y/totalY) if (baseNum + tileDistance < 10) baseNum + tileDistance else (baseNum + tileDistance) - 9 } } print("Puzzle 2: ") findShortestPath(grid) } }
0
C++
0
0
02f219ea278d85c7799d739294c664aa5a47719a
2,298
AOC2021
Apache License 2.0