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/main/kotlin/day20/solution.kt
bukajsytlos
433,979,778
false
{"Kotlin": 63913}
package day20 import java.io.File fun main() { val lines = File("src/main/kotlin/day20/input.txt").readLines() val imageEnhancementAlgorithm: BooleanArray = lines[0].map { it == '#' }.toBooleanArray() val imageYSize = lines.size + 2 val imageXSize = lines[2].length + 4 val image = InfiniteImage( Array(imageYSize) { i -> if (i in (0..1) || i in (imageYSize - 2 until imageYSize)) { BooleanArray(imageXSize) } else { (".." + lines[i] + "..").map { it == '#' }.toBooleanArray() } }, false ) val enhancedImage = (0..1).fold(image) { acc, _ -> enhanceImage(acc, imageEnhancementAlgorithm) } println(enhancedImage.innerData.sumOf { imageLine -> imageLine.count { it } }) val enhancedImage2 = (0..49).fold(image) { acc, _ -> enhanceImage(acc, imageEnhancementAlgorithm) } println(enhancedImage2.innerData.sumOf { imageLine -> imageLine.count { it } }) } fun enhanceImage(image: InfiniteImage, imageEnhancementAlgorithm: BooleanArray): InfiniteImage { val imageYResolution = image.innerData.size + 2 val imageXResolution = image.innerData[0].size + 2 val newOuterPixelValue = image.outerPixelValue.not() val newInnerData = Array(imageYResolution) { y -> if (y in (0..1) || y in (imageYResolution - 2 until imageYResolution)) { BooleanArray(imageXResolution) { newOuterPixelValue } } else { BooleanArray(imageXResolution) { x -> if (x in (0..1) || x in (imageXResolution - 2 until imageXResolution)) { newOuterPixelValue } else { val pixelValueArray = BooleanArray(9) pixelValueArray[0] = image.innerData[y - 2][x - 2] pixelValueArray[1] = image.innerData[y - 2][x - 1] pixelValueArray[2] = image.innerData[y - 2][x] pixelValueArray[3] = image.innerData[y - 1][x - 2] pixelValueArray[4] = image.innerData[y - 1][x - 1] pixelValueArray[5] = image.innerData[y - 1][x] pixelValueArray[6] = image.innerData[y][x - 2] pixelValueArray[7] = image.innerData[y][x - 1] pixelValueArray[8] = image.innerData[y][x] imageEnhancementAlgorithm[pixelValueArray.toInt()] } } } } return InfiniteImage( newInnerData, newOuterPixelValue ) } fun BooleanArray.toInt(): Int = this.map { if (it) 1 else 0 }.joinToString("").toInt(2) data class InfiniteImage(val innerData: Array<BooleanArray>, val outerPixelValue: Boolean)
0
Kotlin
0
0
f47d092399c3e395381406b7a0048c0795d332b9
2,746
aoc-2021
MIT License
app/src/y2021/day20/Day20TrenchMap.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day20 import common.* import common.annotations.AoCPuzzle fun main(args: Array<String>) { Day20TrenchMap().solveThem() } @AoCPuzzle(2021, 20) class Day20TrenchMap : AocSolution { override val answers = Answers(samplePart1 = 35, samplePart2 = 3351, part1 = 5622) override fun solvePart1(input: List<String>): Any = input .enhance(2) .litPixel override fun solvePart2(input: List<String>): Any = input .enhance(50) .litPixel private fun List<String>.enhance(steps: Int): Image { return (0 until steps).fold( Image( image = drop(2).joinToString(""), width = drop(2).size, algorithm = first() ) ) { image, _ -> image.enhance() } } } class Image( private val image: String, private val width: Int, private val algorithm: String, private val isBlack: Boolean = true, ) { val litPixel = image.count { it == '#' } fun enhance(): Image = Image( image = buildString { forEachPixel { x, y -> append( getFilterCore(x, y) .replace(BLACK, '0') .replace(WHITE, '1') .toInt(2) .let(algorithm::get) ) } }, width = width + 2, algorithm = algorithm, isBlack = if (algorithm.first() == '#') !isBlack else isBlack ) private fun forEachPixel(action: (x: Int, y: Int) -> Unit) { for (y in -1..(image.length / width)) { for (x in -1..width) { action(x, y) } } } private fun getFilterCore(x: Int, y: Int): String { return buildString { for (dY in -1..1) { for (dX in -1..1) { append(getPixel(x + dX, y + dY)) } } } } override fun toString(): String = buildString { forEachPixel { x, y -> if (x == -1) append("\n") append(getPixel(x, y)) } } private fun getPixel(x: Int, y: Int): Char = when { x < 0 || x >= width -> getPixelFromVoid() else -> image.getOrElse(x + y * width) { getPixelFromVoid() } } private fun getPixelFromVoid(): Char = if (isBlack) BLACK else WHITE companion object { const val BLACK = '.' const val WHITE = '#' } }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
2,488
advent-of-code-2021
Apache License 2.0
src/Day25.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
fun main() { val base = 5 val digits = "012=-" fun snafuToDec(snafu: String): Long { return snafu.fold(0) { carry, digit -> (carry * base) + when(digit) { '=' -> -2 '-' -> -1 else -> digit.digitToInt() } } } fun decToSnafu(dec: Long): String { var snafu = "" var value = dec while (value != 0L) { snafu = digits[value.mod(base)] + snafu value = (value + 2).floorDiv(base) } return snafu } fun part1(input: List<String>): String = decToSnafu(input.fold(0) { a, b -> a + snafuToDec(b) }) val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
819
aoc-2022
Apache License 2.0
src/Day22.kt
MickyOR
578,726,798
false
{"Kotlin": 98785}
import com.sun.source.tree.LiteralTree fun main() { var dRow = listOf<Int>(0, 1, 0, -1) var dCol = listOf<Int>(1, 0, -1, 0) fun parseInstructions(line: String): MutableList<String> { var instructions = mutableListOf<String>() var lst = "" for (c in line) { if (c == 'L' || c == 'R') { if (lst.isNotBlank()) instructions.add(lst) instructions.add(c.toString()) lst = "" } else lst += c } if (lst.isNotBlank()) instructions.add(lst) return instructions } fun part1(input: List<String>): Int { while (input.last().isEmpty()) input.dropLast(1) var r = 0 var c = 0 for (i in input[0].indices) { if (input[0][i] == '.') { c = i break } } var dir = 0 var instructions = parseInstructions(input.last()) input.dropLast(2) for (inst in instructions) { if (inst == "L") dir = (dir + 3) % 4 else if (inst == "R") dir = (dir + 1) % 4 else for (st in 1 .. inst.toInt()) { var a = r + dRow[dir] var b = c + dCol[dir] if (a < 0 || a >= input.size || b < 0 || b >= input[a].length || input[a][b] == ' ') { var wr = r var wc = c var wdir = (dir + 2) % 4 while (wr >= 0 && wr < input.size && wc >= 0 && wc < input[wr].length && input[wr][wc] != ' ') { wr += dRow[wdir] wc += dCol[wdir] } wr += dRow[dir] wc += dCol[dir] assert(wr >= 0 && wr < input.size && wc >= 0 && wc < input[wr].length) if (input[wr][wc] == '#') break a = wr b = wc } else if (input[a][b] == '#') break r = a c = b } } return 1000 * (r+1) + 4 * (c+1) + dir } fun part2(input: List<String>): Int { val faceSize = 50 var face = mutableListOf<MutableList<Char>>() for (line in input) face.add(line.toMutableList()) face = face.dropLast(2).toMutableList() var corners = mutableMapOf<Int, List<Pair<Int, Int>>>() // face -> list of corners {UL, UR, DR, DL} var cnt = 0 for (i in face.indices) { for (j in face[i].indices) { if (face[i][j] == '.' || face[i][j] == '#') { cnt++ corners[cnt] = listOf(Pair(i, j), Pair(i, j+faceSize-1), Pair(i+faceSize-1, j+faceSize-1), Pair(i+faceSize-1, j)) for (r in i until i + faceSize) { for (c in j until j + faceSize) { face[r][c] = (cnt + '0'.code).toChar() } } } } } class Wrap { var oriFace = 0 var corner = 0 var destFace = 0 var destDir = 0 var destCorner = 0 var destCornerDir = 0 fun wrappedPosition(r: Int, c: Int): Pair<Pair<Int, Int>, Int> { var distFromCorner = kotlin.math.abs(r - corners[oriFace]!![corner].first) + kotlin.math.abs(c - corners[oriFace]!![corner].second) var newR = corners[destFace]!![destCorner].first + dRow[destCornerDir] * distFromCorner var newC = corners[destFace]!![destCorner].second + dCol[destCornerDir] * distFromCorner var newDir = destDir return Pair(Pair(newR, newC), newDir) } } var wrapFunction = mutableMapOf< Pair<Int, Int>, Wrap > () // face, dir -> wrap function // face 1, wrap left wrapFunction[Pair(1, 2)] = Wrap().apply { oriFace = 1 corner = 0 destFace = 4 destDir = 0 destCorner = 3 destCornerDir = 3 } // face 1, wrap up wrapFunction[Pair(1, 3)] = Wrap().apply { oriFace = 1 corner = 0 destFace = 6 destDir = 0 destCorner = 0 destCornerDir = 1 } // face 2, wrap up wrapFunction[Pair(2, 3)] = Wrap().apply { oriFace = 2 corner = 0 destFace = 6 destDir = 3 destCorner = 3 destCornerDir = 0 } // face 2, wrap right wrapFunction[Pair(2, 0)] = Wrap().apply { oriFace = 2 corner = 1 destFace = 5 destDir = 2 destCorner = 2 destCornerDir = 3 } // face 2, wrap down wrapFunction[Pair(2, 1)] = Wrap().apply { oriFace = 2 corner = 3 destFace = 3 destDir = 2 destCorner = 1 destCornerDir = 1 } // face 3, wrap right wrapFunction[Pair(3, 0)] = Wrap().apply { oriFace = 3 corner = 1 destFace = 2 destDir = 3 destCorner = 3 destCornerDir = 0 } // face 5, wrap right wrapFunction[Pair(5, 0)] = Wrap().apply { oriFace = 5 corner = 1 destFace = 2 destDir = 2 destCorner = 2 destCornerDir = 3 } // face 5, wrap down wrapFunction[Pair(5, 1)] = Wrap().apply { oriFace = 5 corner = 3 destFace = 6 destDir = 2 destCorner = 1 destCornerDir = 1 } // face 6, wrap right wrapFunction[Pair(6, 0)] = Wrap().apply { oriFace = 6 corner = 1 destFace = 5 destDir = 3 destCorner = 3 destCornerDir = 0 } // face 6, wrap down wrapFunction[Pair(6, 1)] = Wrap().apply { oriFace = 6 corner = 3 destFace = 2 destDir = 1 destCorner = 0 destCornerDir = 0 } // face 6, wrap left wrapFunction[Pair(6, 2)] = Wrap().apply { oriFace = 6 corner = 0 destFace = 1 destDir = 1 destCorner = 0 destCornerDir = 0 } // face 4, wrap left wrapFunction[Pair(4, 2)] = Wrap().apply { oriFace = 4 corner = 0 destFace = 1 destDir = 0 destCorner = 3 destCornerDir = 3 } // face 4, wrap up wrapFunction[Pair(4, 3)] = Wrap().apply { oriFace = 4 corner = 0 destFace = 3 destDir = 0 destCorner = 0 destCornerDir = 1 } // face 3, wrap left wrapFunction[Pair(3, 2)] = Wrap().apply { oriFace = 3 corner = 0 destFace = 4 destDir = 1 destCorner = 0 destCornerDir = 0 } var r = 0 var c = 0 for (i in input[0].indices) { if (input[0][i] == '.') { c = i break } } var dir = 0 var instructions = parseInstructions(input.last()) input.dropLast(2) var visitedPositions = mutableMapOf<Pair<Int, Int>, Char>() fun printBoard(r: Int, c: Int, dir: Int) { println("=======================================================================\n") println("=======================================================================\n") println("=======================================================================\n") println("Board with r = $r, c = $c, dir = $dir") for (i in 0 until input.size - 2) { for (j in input[i].indices) { print( if (i == r && j == c) { 'O' } else if (visitedPositions.containsKey(Pair(i, j))) { visitedPositions[Pair(i, j)] } else { input[i][j] } ) } println() } } var wrapCount = 0 for (inst in instructions) { if (inst == "L") dir = (dir + 3) % 4 else if (inst == "R") dir = (dir + 1) % 4 else for (st in 1 .. inst.toInt()) { visitedPositions[Pair(r, c)] = when (dir) { 0 -> '>' 1 -> 'v' 2 -> '<' else -> '^' } // if (st > 1) printBoard(r, c, dir) var a = r + dRow[dir] var b = c + dCol[dir] if (a < 0 || a >= input.size || b < 0 || b >= input[a].length || input[a][b] == ' ') { var wrap = wrapFunction[Pair((face[r][c] - '0').toInt(), dir)]?.wrappedPosition(r, c) // println("wrap count: ${++wrapCount}") var newR = wrap?.first?.first ?: 0 var newC = wrap?.first?.second ?: 0 var newDir = wrap?.second ?: 0 // println("wraps to $newR, $newC with dir = $newDir") if (input[newR][newC] == '#') { break } a = newR b = newC dir = newDir } else if (input[a][b] == '#') break r = a c = b } // printBoard(r, c, dir) visitedPositions[Pair(r, c)] = when (dir) { 0 -> '>' 1 -> 'v' 2 -> '<' else -> '^' } } return 1000 * (r+1) + 4 * (c+1) + dir } val input = readInput("Day22") part1(input).println() part2(input).println() }
0
Kotlin
0
0
c24e763a1adaf0a35ed2fad8ccc4c315259827f0
10,339
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/aoc19/Day4.kt
tahlers
225,198,917
false
null
package aoc19 object Day4 { fun isValid(s: String): Boolean { val containsDouble = s.toSet().size != s.length val noDecrease = isNotDecreasing(s) return containsDouble && noDecrease } fun isValid2(s: String): Boolean { val hasAtLeastOneSingleDouble = hasAtLeastOneSingleDouble(s) val noDecrease = isNotDecreasing(s) return hasAtLeastOneSingleDouble && noDecrease } private fun isNotDecreasing(s: String): Boolean { return s.fold(-1) { incStatus, char -> val newDigit = char.toInt() if (newDigit < incStatus) return false else newDigit }.let { true } } private fun hasAtLeastOneSingleDouble(s: String): Boolean { data class DoubleStatus(val c: Char, val count: Int) val folded = s.fold(DoubleStatus(s[0], 0)) { status, char -> if (status.c != char && status.count == 2) return true if (status.c == char) { DoubleStatus(char, status.count + 1) } else { DoubleStatus(char, 1) } } return folded.count == 2 } fun numberOfValidCombinations(start: String, end: String): Int { val startNum = start.toInt() val endNum = end.toInt() return (startNum..(endNum + 1)).filter { isValid(it.toString()) }.size } fun numberOfValidCombinations2(start: String, end: String): Int { val startNum = start.toInt() val endNum = end.toInt() return (startNum..(endNum + 1)).filter { isValid2(it.toString()) }.size } }
0
Kotlin
0
0
dae62345fca42dd9d62faadf78784d230b080c6f
1,599
advent-of-code-19
MIT License
2019/02 - 1202 Program Alarm/kotlin/src/app.kt
Adriel-M
225,250,242
false
null
import java.io.File fun getProgram(path: String): List<Int> { val unparsedProgram = File(path).readLines() return unparsedProgram[0].split(",").map { it.toInt() } } fun executeAdd(program: MutableList<Int>, currentIndex: Int) { val indexA = program[currentIndex + 1] val indexB = program[currentIndex + 2] val valA = program[indexA] val valB = program[indexB] val destination = program[currentIndex + 3] program[destination] = valA + valB } fun executeMult(program: MutableList<Int>, currentIndex: Int) { val indexA = program[currentIndex + 1] val indexB = program[currentIndex + 2] val valA = program[indexA] val valB = program[indexB] val destination = program[currentIndex + 3] program[destination] = valA * valB } fun runProgram(program: MutableList<Int>): Int { var currentIndex = 0 loop@ while (program[currentIndex] != 99) { val currentOp = program[currentIndex] currentIndex += when (currentOp) { 1 -> { executeAdd(program, currentIndex) 4 } 2 -> { executeMult(program, currentIndex) 4 } else -> { println("Something broke") break@loop } } } return program[0] } fun runReplacedProgram(program: MutableList<Int>, noun: Int, verb: Int): Int { program[1] = noun program[2] = verb return runProgram(program) } fun runPart1(program: List<Int>): Int { return runReplacedProgram(program.toMutableList(), 12, 2) } fun runPart2(program: List<Int>): Int { for (noun in 0..99) { for (verb in 0..99) { if (runReplacedProgram(program.toMutableList(), noun, verb) == 19690720) { return (100 * noun) + verb } } } return -1 } fun main() { val program = getProgram("../input") println("===== Part 1 =====") println(runPart1(program)) println("===== Part 2 =====") println(runPart2(program)) }
0
Kotlin
0
0
ceb1f27013835f13d99dd44b1cd8d073eade8d67
2,061
advent-of-code
MIT License
src/main/kotlin/adventofcode/year2020/Day21AllergenAssessment.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day21AllergenAssessment(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val foods by lazy { input.lines().map(Food::invoke) } override fun partOne(): Int { val ingredientsToAllergens = foods.ingredientsAllergensMap() return foods.flatMap(Food::ingredients).filter { !ingredientsToAllergens.contains(it) }.size } override fun partTwo() = foods.ingredientsAllergensMap().entries.sortedBy { it.value }.joinToString(",") { it.key } companion object { private data class Food( val ingredients: List<String>, val allergens: List<String> ) { companion object { operator fun invoke(input: String): Food { val ingredients = input.split("(").first().trim().split(" ") val allergens = when { input.contains("(") -> input.split("(").last().replace("contains ", "").replace(")", "").split(", ") else -> emptyList() } return Food(ingredients, allergens) } } } private fun List<Food>.ingredientsAllergensMap() = flatMap { food -> food.allergens.map { allergen -> food.ingredients.last { ingredient -> filter { it.allergens.contains(allergen) }.all { it.ingredients.contains(ingredient) } } to allergen } }.toMap() } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,588
AdventOfCode
MIT License
src/Day01.kt
sms-system
572,903,655
false
{"Kotlin": 4632}
fun main() { fun getListOfCalories(input: List<String>): List<Int> { return input.fold(mutableListOf(0)) { acc, item -> if (item.isBlank()) acc.add(0) else acc[acc.size - 1] = acc.last() + item.toInt() acc } } fun part1(input: List<String>): Int { return getListOfCalories(input) .max() } fun part2(input: List<String>): Int { return getListOfCalories(input) .sortedDescending() .take(3) .sum() } 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
266dd4e52f3b01912fbe2aa23d1ee70d1292827d
748
adventofcode-2022-kotlin
Apache License 2.0
KotlinAdvent2018/week1/src/main/kotlin/net/twisterrob/challenges/adventOfKotlin2018/week1/AStar.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
package net.twisterrob.challenges.adventOfKotlin2018.week1 import net.twisterrob.challenges.adventOfKotlin2018.week1.Map.Cell import net.twisterrob.challenges.adventOfKotlin2018.week1.Map.Cell.End import net.twisterrob.challenges.adventOfKotlin2018.week1.Map.Cell.Path import net.twisterrob.challenges.adventOfKotlin2018.week1.Map.Cell.Start import java.util.PriorityQueue class AStar(private val map: Map) { data class Pos( val row: Int, val col: Int ) private class CellData( val pos: Pos, var totalCostEstimate: Double = 0.0, var distanceFromStart: Double = 0.0, var heuristicToEnd: Double = 0.0, var parent: CellData? = null ) { override fun toString() = "(%2d,%2d^%2d,%2d)[%2.1f-%2.1f]".format( pos.row, pos.col, parent?.pos?.row ?: -1, parent?.pos?.col ?: -1, distanceFromStart, heuristicToEnd ) } private val data: Array<Array<CellData>> = Array(map.rows) { row -> Array(map.cols) { col -> CellData(Pos(row, col)) } } override fun toString() = data.joinToString("\n") { row -> row.joinToString("; ") } /** * @param heuristic between any two valid positions on the map * @param distance distance will be always between two neighboring cells */ fun run(heuristic: (a: Pos, b: Pos) -> Double, distance: Map.(a: Pos, b: Pos) -> Double) { val openCells = PriorityQueue<CellData>(compareBy(CellData::totalCostEstimate)) openCells += findPositionOf(Start) openCells.peek().totalCostEstimate = 0.0 val closedCells = mutableSetOf<CellData>() val target = findPositionOf(End) while (openCells.isNotEmpty()) { val current = openCells.poll()!! if (current !== target) { closedCells += current for (neighbor in current.neighbors()) { if (neighbor in closedCells) continue // performance and correctness: need to remove neighbor from openCells, val isOpen = openCells.remove(neighbor) // because we're mutating it, will be re-added after mutation neighbor.update(current, target, isOpen, heuristic, distance) // (re)adding simulates a heapify to re-sort priority queue // (complexity of algorithm stays the same, except the heap operation will have a 2x) openCells += neighbor } } else { target.backtrackPathToStart().forEach { map.mark(it.pos) } return } } } private fun CellData.update( current: CellData, target: CellData, neighborIsOpen: Boolean, heuristic: (a: Pos, b: Pos) -> Double, distance: Map.(a: Pos, b: Pos) -> Double ) { val newDistance = current.distanceFromStart + map.distance(current.pos, this.pos) if (neighborIsOpen) { if (newDistance < distanceFromStart) { // better total cost than before, use this new path (parent) distanceFromStart = newDistance totalCostEstimate = distanceFromStart + heuristicToEnd parent = current } else { // neighbor's current reachability is better than this one } } else { // reaching this cell for the first time, calculate everything distanceFromStart = newDistance heuristicToEnd = heuristic(this.pos, target.pos) totalCostEstimate = distanceFromStart + heuristicToEnd parent = current } } private fun CellData.backtrackPathToStart() = generateSequence(this) { it.parent } private fun CellData.neighbors(): Sequence<CellData> { operator fun Pos.plus(offset: Offset) = Pos(this.row + offset.row, this.col + offset.col) return NEIGHBOR_DIRECTIONS .asSequence() .map { offset -> pos + offset } .filter { pos -> data.isValidPosition(pos) } .map { (row, col) -> data[row][col] } } private fun findPositionOf(cell: Cell): CellData { var found: CellData? = null data.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, current -> val mapCell = map[rowIndex, colIndex] if (mapCell == cell) { check(found == null) { "Multiple positions contain $cell: $found and $current" } found = current } } } return found ?: error("Cannot find $cell") } companion object { private data class Offset(val row: Int, val col: Int) private val NEIGHBOR_DIRECTIONS = listOf( Offset(-1, -1), Offset(-1, 0), Offset(-1, +1), Offset(0, -1), /* self not included, */ Offset(0, +1), Offset(+1, -1), Offset(+1, 0), Offset(+1, +1) ) private fun Array<Array<CellData>>.isValidPosition(pos: Pos) = pos.row in this.indices && pos.col in this[pos.row].indices private fun Map.mark(pos: Pos) { this[pos.row, pos.col] = Path } } }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
4,472
TWiStErRob
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem1870/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1870 /** * LeetCode page: [1870. Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/); */ class Solution { private val minPossibleSpeed = 1 private val maxPossibleSpeed = 10_000_000 private val valueIfCanNotOnTime = -1 /* Complexity: * Time O(NLogK) and Space O(1) where N is the size of dist and K is the size of possible speed range; */ fun minSpeedOnTime(dist: IntArray, hour: Double): Int { if (canNotOnTime(dist, hour)) { return valueIfCanNotOnTime } var lowerBound = minPossibleSpeed var upperBound = maxPossibleSpeed while (lowerBound < upperBound) { val mid = lowerBound + (upperBound - lowerBound) / 2 if (hour < travelTime(dist, mid)) { lowerBound = mid + 1 } else { upperBound = mid } } return lowerBound } private fun canNotOnTime(dist: IntArray, hour: Double): Boolean { return hour < (dist.size - 1) + (dist.last().toDouble() / maxPossibleSpeed) } private fun travelTime(dist: IntArray, speed: Int): Double { var result = 0.0 for (index in 0 until dist.lastIndex) { result += Math.ceil(dist[index].toDouble() / speed) } result += dist.last().toDouble() / speed return result } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,441
hj-leetcode-kotlin
Apache License 2.0
algorithms_and_data_structure/with_kotlin/algoritms/LinearSearchAlgorithms.kt
ggsant
423,455,976
false
{"Dart": 27223, "Kotlin": 6516}
/** * Idea: Go through the vector, analyzing each position i. If A[i].key equals K, then it found the * position and returns i. If you went through the entire vector and no element equal to K exists, * then return -1. * * Linear search is an algorithm which finds the position of a target value within an array (Usually * unsorted) * * Worst-case performance O(n) Best-case performance O(1) Average performance O(n) Worst-case space * complexity O(1) */ fun main() { val array = intArrayOf(-6, -1, 3, 7, 10, 27, 35, 37, 52) val k1 = 27 val k2 = 2 println("Result for k1 ${linearSearch(array, k1)}") println("Result for k2 ${linearSearch(array, k2)}") } /** * @param array is an array where the element should be found * @param k is an element which should be found * @return index of the element */ fun linearSearch(array: IntArray, k: Int): Int { for (i in array.indices) { if (array[i].compareTo(k) == 0) { return i } } return -1 }
0
Dart
0
1
8ebed6dd46cdbdfada6f19610479191bcc37dd22
1,012
algorithms_analysis_and_data_structure
MIT License
Day3/spiral_memory.kt
fpeterek
155,423,059
false
null
import kotlin.math.abs import kotlin.math.ceil import kotlin.math.sqrt fun findNearestSquareRoot(num: Int): Int { val nearestRoot = ceil(sqrt(num.toDouble())).toInt() return if (nearestRoot % 2 == 0) { nearestRoot + 1 } else { nearestRoot } } fun main(args: Array<String>) { val input = 325489 val nearestRoot = findNearestSquareRoot(input) val rightBottom = nearestRoot * nearestRoot val leftBottom = rightBottom - nearestRoot + 1 val leftTop = leftBottom - nearestRoot + 1 val rightTop = leftTop - nearestRoot + 1 val rightLowest = rightTop - nearestRoot + 2 val horizontalPos = when (input) { in leftTop..leftBottom -> leftTop in rightLowest..rightTop -> rightBottom else -> input } val horizontal = if (horizontalPos >= leftBottom) { val midVal = leftBottom + (nearestRoot / 2.0).toInt() abs(horizontalPos - midVal) } else { val midVal = rightTop + (nearestRoot / 2.0).toInt() abs(horizontalPos - midVal) } val verticalPosition = when (input) { in leftBottom..rightBottom -> leftBottom in leftTop..rightTop -> leftTop else -> input } val vertical = if (verticalPosition < leftTop) { val midVal = rightTop - (nearestRoot / 2.0).toInt() abs(verticalPosition - midVal) } else { val midVal = leftTop + (nearestRoot / 2.0).toInt() abs(verticalPosition - midVal) } println(horizontal + vertical) }
0
Kotlin
0
0
d5bdf89e106cd84bb4ad997363a887c02cb6664b
1,533
Advent-Of-Code
MIT License
AOC2022/src/main/kotlin/AOC7.kt
bsautner
575,496,785
false
{"Kotlin": 16189, "Assembly": 496}
import java.io.File class AOC7 { private val input = File("/home/ben/aoc/input-7.txt") private val list = mutableListOf<String>() private var PWD = Node("root", null) //Present Working Directory var spaceNeeded = 0L var winner = 70000000L fun process() { input.forEachLine { list.add(it) } PWD.nodes["/"] = Node("/", PWD) buildNodeTreeFromCommandList(list, PWD) val answer = getSmallNodesSum(PWD) println("Part 1 $answer") val rootSize = getNodeSize(PWD) spaceNeeded = MAX_HD - rootSize spaceNeeded = UPDATE_SIZE - spaceNeeded smallestDeletableDir(PWD) println("Part 2 $winner") } private fun smallestDeletableDir(node: Node) { if (getNodeSize(node) in (spaceNeeded + 1) until winner) { winner = getNodeSize(node) } node.nodes.values.forEach { smallestDeletableDir(it) } } private fun getSmallNodesSum(node: Node) : Long { var sum = 0L node.nodes.values.forEach { if (getNodeSize(it) <= 100000) { sum += getNodeSize(it) } sum += getSmallNodesSum(it) } return sum } private fun getNodeSize(node: Node) : Long { var size = 0L node.items.forEach { size += it.size } node.nodes.values.forEach { size += getNodeSize(it) } return size } private tailrec fun buildNodeTreeFromCommandList(list: List<String>, pwd: Node?) { if (list.isEmpty()) { return } val line = list.first() val rest = list.drop(1) val parts = line.split(" ") if (isNumeric(parts[0])) { val item = Item(parts[1], parts[0].toLong()) pwd?.items?.add(item) buildNodeTreeFromCommandList(rest, pwd) } else { when (parts[0]) { "dir" -> { pwd?.nodes?.set(parts[1], Node(parts[1], pwd)) buildNodeTreeFromCommandList(rest, pwd) } "$" -> { if (parts[1] == "cd") { if (parts[2] == "..") { buildNodeTreeFromCommandList(rest, pwd?.parent) } else { val node = pwd?.nodes?.get(parts[2]) buildNodeTreeFromCommandList(rest, node) } // pwd = pwd.nodes[parts[2]]!! } else if (parts[1] == "ls") { buildNodeTreeFromCommandList(rest, pwd) } } } } } companion object { private const val MAX_HD = 70000000 private const val UPDATE_SIZE = 30000000 @JvmStatic fun main(args: Array<String>) { AOC7().process() } fun isNumeric(toCheck: String): Boolean { return toCheck.toDoubleOrNull() != null } } } data class Node(private val name: String, val parent: Node?) { val nodes = mutableMapOf<String, Node>() val items = mutableListOf<Item>() } data class Item(private val name: String, val size: Long)
0
Kotlin
0
0
5f53cb1c4214c960f693c4f6a2b432b983b9cb53
3,443
Advent-of-Code-2022
The Unlicense
util/src/main/java/com/arcadan/util/math/QuadraticEquation.kt
ArcaDone
351,158,574
false
null
package com.arcadan.util.math import java.lang.Math.* import kotlin.math.pow data class QuadraticEquation(val a: Double, val b: Double, val c: Double) { data class Complex(val r: Double, val i: Double) { override fun toString() = when { i == 0.0 -> r.toString() r == 0.0 -> "${i}i" else -> "$r + ${i}i" } } data class Solution(val x1: Any, val x2: Any) { override fun toString() = when(x1) { x2 -> "X1,2 = $x1" else -> "X1 = $x1, X2 = $x2" } } val quadraticRoots by lazy { val _2a = a + a val d = b * b - 4.0 * a * c // discriminant if (d < 0.0) { val r = -b / _2a val i = kotlin.math.sqrt(-d) / _2a Solution(Complex(r, i), Complex(r, -i)) } else { // avoid calculating -b +/- sqrt(d), to avoid any // subtractive cancellation when it is near zero. val r = if (b < 0.0) (-b + kotlin.math.sqrt(d)) / _2a else (-b - kotlin.math.sqrt(d)) / _2a Solution(r, c / (a * r)) } } fun obtainYForXValue(x: Double) : Double = ((x.pow(2) * a) + (x * b) + c) }
0
Kotlin
0
2
24133757b19f2b2fea64542347b339f8621284f6
1,196
DodgeTheEnemies
MIT License
tonilopezmr/day6/MemoryBankPartTwo.kt
CloudCoders
112,667,277
false
{"Mathematica": 37090, "Python": 36924, "Scala": 26540, "Kotlin": 24988, "Ruby": 5084, "Java": 4495, "JavaScript": 3440, "MATLAB": 3013}
package day6 import kategory.combine import org.junit.Assert.assertEquals import org.junit.Test class MemoryBankPartTwo { private fun chooseBank(input: List<Int>): Pair<Int, Int> = input.foldRightIndexed(P(0, 0)) { idx, bank, (index, blocks) -> if (bank >= blocks) P(idx, bank) else P(index, blocks) } private fun balance(input: List<Int>): List<Int> { var (index, bank) = chooseBank(input) val distribution = if (bank < input.size) bank else input.size - 1 val blocksForEach = bank / distribution val list = input.toMutableList() val displacement = blocksForEach * distribution list[index] = bank - displacement index++ for (i in 1..distribution) { index %= input.size list[index] = list[index] + blocksForEach index++ } return list } private fun infiniteLoopCircleInI(input: List<Int>): Int { val history = mutableListOf<List<Int>>() var banks = input var count = 0 while (!history.contains(banks)) { history.add(banks) banks = balance(banks) count++ } return count } tailrec private fun infiniteLoopCircleIn(input: List<Int>, history: List<List<Int>> = emptyList(), count: Int = 0): Pair<Int, List<Int>> = if (history.contains(input)) Pair(count, input) else { val newInput = balance(input) infiniteLoopCircleIn(newInput, history.toMutableList().apply { add(input) }, count + 1) } @Test fun `detect infinite loop circle in blocks redistribution`() { val input = listOf(0, 2, 7, 0) val (size, bank) = infiniteLoopCircleIn(input) assertEquals(5, size) assertEquals(listOf(2, 4, 1, 2), bank) } @Test fun `detect the size of the infinite loop sequence`() { val input = listOf(0, 2, 7, 0) val (_, bank) = infiniteLoopCircleIn(input) assertEquals(4, infiniteLoopCircleIn(bank).first) } @Test fun `the result of the infinite loop circle is`() { val input = listOf(0, 5, 10, 0, 11, 14, 13, 4, 11, 8, 8, 7, 1, 4, 12, 11) val (_, bank) = infiniteLoopCircleIn(input) assertEquals(1695, infiniteLoopCircleIn(bank).first) } }
2
Mathematica
0
8
5a52d1e89076eccb55686e4af5848de289309813
2,151
AdventOfCode2017
MIT License
2021/src/test/kotlin/Day13.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day13 { data class Coord(var x: Int, var y: Int) enum class Axis { X, Y } data class Instruction(val axis: Axis, val value: Int) @Test fun `run part 01`() { val (coords, instructions) = getPaper() coords.foldAxis(instructions.first()) val count = coords .distinct() .count() assertEquals(781, count) } @Test fun `run part 02`() { val (coords, instructions) = getPaper() instructions.forEach { coords.foldAxis(it) } assertEquals("###..####.###...##...##....##.###..###.", coords.line(0)) assertEquals("#..#.#....#..#.#..#.#..#....#.#..#.#..#", coords.line(1)) assertEquals("#..#.###..#..#.#....#.......#.#..#.###.", coords.line(2)) assertEquals("###..#....###..#....#.##....#.###..#..#", coords.line(3)) assertEquals("#....#....#.#..#..#.#..#.#..#.#....#..#", coords.line(4)) assertEquals("#....####.#..#..##...###..##..#....###.", coords.line(5)) } private fun List<Coord>.foldAxis(instruction: Instruction) = this .forEach { if (instruction.axis == Axis.X && it.x > instruction.value) it.x = instruction.value - (it.x - instruction.value) if (instruction.axis == Axis.Y && it.y > instruction.value) it.y = instruction.value - (it.y - instruction.value) } private fun List<Coord>.line(index: Int) = (0..this.maxOf { it.x }) .joinToString("") { x -> if (this.contains(Coord(x, index))) "#" else "." } private fun getPaper() = Util.getInputAsListOfString("day13-input.txt") .let { paper -> paper.mapNotNull { if (it.contains(",")) it .split(",") .let { s -> Coord(s[0].toInt(), s[1].toInt()) } else null } to paper.mapNotNull { if (it.startsWith("fold along")) it .split(" ", "=") .let { s -> Instruction(Axis.valueOf(s[2].uppercase()), s[3].toInt()) } else null } } }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,299
adventofcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountSubarrays.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 /** * 2488. Count Subarrays With Median K * @see <a href="https://leetcode.com/problems/count-subarrays-with-median-k/">Source</a> */ fun interface CountSubarrays { operator fun invoke(nums: IntArray, k: Int): Int } class CountSubarraysMap : CountSubarrays { override operator fun invoke(nums: IntArray, k: Int): Int { val prefixSumOfBalance: MutableMap<Int, Int> = HashMap() prefixSumOfBalance[0] = 1 // Dummy value of 0's frequency is 1. var ans = 0 var runningBalance = 0 var found = false for (num in nums) { if (num < k) { --runningBalance } else if (num > k) { ++runningBalance } else { found = true } if (found) { ans += prefixSumOfBalance.getOrDefault(runningBalance, 0) + prefixSumOfBalance.getOrDefault( runningBalance - 1, 0, ) } else { prefixSumOfBalance[runningBalance] = prefixSumOfBalance.getOrDefault(runningBalance, 0) + 1 } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,801
kotlab
Apache License 2.0
day3/src/main/kotlin/part2.kt
Lysoun
725,939,287
false
{"Kotlin": 16038, "OCaml": 224}
package day3 import java.io.File fun computeGearRatio(maybeGearPosition: Pair<Int, Int>, numbers: MutableMap<Pair<Int, Int>, Int>): Int { val neighbourNumbers = listOf( maybeGearPosition.first to maybeGearPosition.second -1, maybeGearPosition.first + 1 to maybeGearPosition.second -1, maybeGearPosition.first - 1 to maybeGearPosition.second -1, maybeGearPosition.first to maybeGearPosition.second +1, maybeGearPosition.first + 1 to maybeGearPosition.second +1, maybeGearPosition.first - 1 to maybeGearPosition.second +1, maybeGearPosition.first + 1 to maybeGearPosition.second, maybeGearPosition.first - 1 to maybeGearPosition.second ).mapNotNull { numbers[it] }.toSet() return if (neighbourNumbers.size == 2) { neighbourNumbers.reduce(Int::times) } else { 0 } } fun main() { val inputFileName = "day3/input.txt" val numbers: MutableMap<Pair<Int, Int>, Int> = mutableMapOf() val hopefullyGears: MutableList<Pair<Int, Int>> = mutableListOf() var lineNumber = 0 File(inputFileName).forEachLine { var number = "" var digitsIndices = mutableListOf<Pair<Int, Int>>() it.forEachIndexed { index, c -> if (c.isDigit()) { number += c.toString() digitsIndices.add(lineNumber to index) } else if(number != "") { digitsIndices.forEach {digitIndex -> numbers[digitIndex] = number.toInt() } number = "" digitsIndices = mutableListOf() } if (c == '*') { hopefullyGears.add(lineNumber to index) } } if(number != "") { digitsIndices.forEach {digitIndex -> numbers[digitIndex] = number.toInt() } number = "" digitsIndices = mutableListOf() } ++lineNumber } println(hopefullyGears.sumOf { computeGearRatio(it, numbers) }) }
0
Kotlin
0
0
96ecbcef1bd29a97f2230457f4e233ca6b1cc108
2,053
advent-of-code-2023
MIT License
src/main/kotlin/io/matrix/SnakesAndLadders.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.matrix class SnakesAndLadders { fun snakesAndLadders(board: Array<IntArray>): Int = executeRecursive(board) fun executeRecursive(board: Array<IntArray>): Int { val visited = mutableSetOf<Int>() var stack = listOf(0) var steps = 0 var found = false while (stack.isNotEmpty() && !found) { if (stack.any { it == board.size * board.size - 1 }) found = true else { visited.addAll(stack) stack = getNextMovements(board, stack, visited) steps++ } } return if (found) steps else -1 } fun execute( board: Array<IntArray>, position: List<Int> = listOf(0), visited: Set<Int> = setOf(), minSolutionFound: MinSolution = MinSolution(), steps: Int = 0): Pair<Int, Set<Int>>? = when { position.any { board.size * board.size - 1 == it } -> minSolutionFound.createMinValue(steps to visited) minSolutionFound.size() < visited.size -> minSolutionFound.value else -> { println(visited) execute(board, getNextMovements(board, position, visited), visited + position, minSolutionFound, steps + 1) } } private fun getNextMovements(board: Array<IntArray>, positionList: List<Int>, visited: Set<Int>) = positionList.flatMap { position -> (board.size * board.size).let { maxSize -> (1..6) .map { position + it } .filter { it in 0 until maxSize } .map { if (board.getValue(it) != -1) board.getValue(it) - 1 else it } .filter { !visited.contains(it) } } } private fun Array<IntArray>.getValue(position: Int) = this[toXCoordinate(position)][toYCoordinate(position)] private fun Array<IntArray>.toXCoordinate(position: Int) = this.size - (position / this.size) - 1 private fun Array<IntArray>.toYCoordinate(position: Int) = if ((position / this.size).rem(2) == 0) position.rem(this.size) else this.size - position.rem(this.size) - 1 data class MinSolution(var value: Pair<Int, Set<Int>>? = null) { fun size() = value?.first ?: Int.MAX_VALUE fun createMinValue(newValue: Pair<Int, Set<Int>>): Pair<Int, Set<Int>> = when { size() < newValue.first -> value!! else -> newValue.also { value = newValue } } } } fun main() { val snakesAndLadders = SnakesAndLadders() listOf( arrayOf( intArrayOf(-1, -1, -1, -1, -1, -1), intArrayOf(-1, -1, -1, -1, -1, -1), intArrayOf(-1, -1, -1, -1, -1, -1), intArrayOf(-1, 35, -1, -1, 13, -1), intArrayOf(-1, -1, -1, -1, -1, -1), intArrayOf(-1, 15, -1, -1, -1, -1)) to 4, arrayOf( intArrayOf(-1, -1, 16, 31, 29, -1), intArrayOf(10, 20, -1, -1, 9, -1), intArrayOf(7, -1, -1, -1, 10, 28), intArrayOf(-1, 16, -1, 16, -1, -1), intArrayOf(28, -1, 5, 25, -1, -1), intArrayOf(-1, 32, 30, -1, -1, -1) ) to 2 ).forEachIndexed { index, (input, value) -> val output = snakesAndLadders.executeRecursive(input) val isValid = output == value if (isValid) println("index $index $output is valid") else println("index $index Except $value but instead got $output") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
3,266
coding
MIT License
lite-math/src/commonMain/kotlin/ppanda/commons/bundle/math/constructs/Fraction.kt
pPanda-beta
305,866,321
false
null
package ppanda.commons.bundle.math.constructs import ppanda.commons.bundle.math.elements.ArithmeticElement import ppanda.commons.bundle.math.groups.Group data class Fraction private constructor( val numerator: Int, val denominator: Int, ) : ArithmeticElement<Fraction> { // TODO: Allow initialization logic to constructor override val additiveGroup: Group<Fraction> by lazy { additionFracGroup } override val multiplicativeGroup: Group<Fraction> by lazy { multFracGroup } override fun toString(): String = "$numerator/$denominator" companion object { val ZERO = Fraction(0, 1) val ONE = Fraction(1, 1) val INFINITY = Fraction(1, 0) fun of(numerator: Int = 0, denominator: Int = 1): Fraction { if (denominator == 0) { return INFINITY } val gcd = gcd(numerator, denominator) return Fraction(numerator / gcd, denominator / gcd) } } } private val additionFracGroup = object : Group<Fraction> { override val identity: Fraction = Fraction.of(0, 1) override fun inverse(x: Fraction) = Fraction.of(0 - (x.numerator), x.denominator) override fun operation(x: Fraction, y: Fraction): Fraction { val lcm = lcm(x.denominator, y.denominator) val part1 = x.numerator * (lcm / x.denominator) val part2 = y.numerator * (lcm / y.denominator) return Fraction.of(part1 + part2, lcm) } } private val multFracGroup = object : Group<Fraction> { override val identity: Fraction = Fraction.of(1, 1) override fun inverse(x: Fraction) = Fraction.of(x.denominator, x.numerator) override fun operation(x: Fraction, y: Fraction) = Fraction.of( x.numerator * y.numerator, x.denominator * y.denominator ) } private fun gcd(a: Int, b: Int): Int { if (b == 0) return a return gcd(b, a % b) } private fun lcm(a: Int, b: Int): Int = a / gcd(a, b) * b
0
Kotlin
0
0
f5b56f4bf3914c0fe32b2e0fc72917e91a06b2a4
1,967
commons-lite
MIT License
codeforces/ozon2020/f.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.ozon2020 import kotlin.random.Random val r = Random(566) fun main() { readLn() val a = readStrings().map { it.toLong() }.shuffled(r) val toCheck = List(1 shl 6) { a[it % a.size] + r.nextInt(3) - 1 }.toSet() val primes = toCheck.flatMap { primes(it) }.toSet().sorted() val ans = primes.fold(a.size.toLong()) { best, p -> a.foldRight(0L) { v, sum -> (sum + if (v <= p) p - v else minOf(v % p, p - v % p)) .takeIf { it < best } ?: return@foldRight best } } println(ans) } private fun primes(v: Long): List<Long> { val primes = mutableListOf<Long>() var x = v for (i in 2..v) { if (x < 2) break if (i * i > x) { primes.add(x) break } while (x % i == 0L) { primes.add(i) x /= i } } return primes } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ")
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
847
competitions
The Unlicense
src/main/kotlin/tr/emreone/adventofcode/days/Day14.kt
EmRe-One
433,772,813
false
{"Kotlin": 118159}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.Logger.logger import tr.emreone.kotlin_utils.automation.Day class Day14 : Day(14, 2021, "Extended Polymerization") { override fun part1(): Int { val template = inputAsList.first() val rules = inputAsList.drop(2).associate { val (pattern, result) = it.split(" -> ") pattern to result } val polymerChain = StringBuilder(template) var currentPolymer = polymerChain.toString() for (i in 0 until 10) { polymerChain.clear() currentPolymer.windowed(2).forEach { pair -> polymerChain.append(pair[0] + rules[pair]!!) } polymerChain.append(currentPolymer.last()) currentPolymer = polymerChain.toString() logger.debug { "Polymer after iteration $i: $currentPolymer" } } val countElements = currentPolymer.groupingBy { it }.eachCount() return countElements.maxOf { it.value } - countElements.minOf { it.value } } override fun part2(): Long { val template = inputAsList.first() val lastPolymer = template.last() val rules = inputAsList.drop(2).map { val (pattern, result) = it.split(" -> ") pattern to result }.toMap() val polymerChain = template.windowed(2).groupingBy { it }.eachCount().map { it.key to it.value.toLong() }.toMap().toMutableMap() for (i in 0 until 40) { val tempChain = polymerChain.toMap().filter { it.value > 0 } for ((key, value) in tempChain) { polymerChain[key] = polymerChain[key]!! - value val newPolymer = rules[key]!! val firstPart = key[0] + newPolymer val secondPart = newPolymer + key[1] polymerChain[firstPart] = polymerChain.getOrDefault(firstPart, 0) + value polymerChain[secondPart] = polymerChain.getOrDefault(secondPart, 0) + value } } val countingElements = mutableMapOf<Char, Long>() for ((key, value) in polymerChain) { countingElements[key[0]] = countingElements.getOrDefault(key[0], 0) + value } countingElements[lastPolymer] = countingElements.getOrDefault(lastPolymer, 0) + 1 return countingElements.maxOf { it.value } - countingElements.minOf { it.value } } }
0
Kotlin
0
0
516718bd31fbf00693752c1eabdfcf3fe2ce903c
2,510
advent-of-code-2021
Apache License 2.0
src/day02/Day02v2.kt
spyroid
433,555,350
false
null
package day02 import readInput fun main() { data class Command(val op: String, val value: Int) open class Engine { var depth = 0 var horizontal = 0 fun input(seq: Sequence<Command>): Engine { seq.forEach { when (it.op) { "forward" -> forward(it.value) "down" -> down(it.value) "up" -> up(it.value) } } return this } open fun forward(value: Int) { horizontal += value } open fun up(value: Int) { depth -= value } open fun down(value: Int) { depth += value } fun magicNumber() = depth * horizontal } class EngineExt : Engine() { var aim = 0 override fun forward(value: Int) { horizontal += value depth += value * aim } override fun down(value: Int) { aim += value } override fun up(value: Int) { aim -= value } } fun part1(seq: Sequence<Command>) = Engine().input(seq).magicNumber() fun part2(seq: Sequence<Command>) = EngineExt().input(seq).magicNumber() fun mapCommand(str: String): Command { val parts = str.split(" ") return Command(parts[0], parts[1].toInt()) } val testSeq = readInput("day02/test").asSequence().map { mapCommand(it) } val seq = readInput("day02/input").asSequence().map { mapCommand(it) } val res1 = part1(testSeq) check(res1 == 150) { "Expected 150 but got $res1" } println("Part1: " + part1(seq)) val res2 = part2(testSeq) check(res2 == 900) { "Expected 900 but got $res2" } println("Part2: " + part2(seq)) }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,791
Advent-of-Code-2021
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CrackingTheSafe.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 kotlin.math.pow fun interface CrackingSafeStrategy { operator fun invoke(n: Int, k: Int): String } class CrackingSafeHierholzersAlgorithm : CrackingSafeStrategy { private val seen: MutableSet<String> = HashSet() private val ans: StringBuilder = StringBuilder() override operator fun invoke(n: Int, k: Int): String { if (n == 1 && k == 1) return "0" val sb = StringBuilder() for (i in 0 until n - 1) sb.append("0") val start = sb.toString() dfs(start, k) ans.append(start) return ans.toString() } private fun dfs(node: String, k: Int) { for (x in 0 until k) { val nei = node + x if (!seen.contains(nei)) { seen.add(nei) dfs(nei.substring(1), k) ans.append(x) } } } } class CrackingSafeInverseBurrowsWheelerTransform : CrackingSafeStrategy { override operator fun invoke(n: Int, k: Int): String { val m = k.toDouble().pow((n - 1).toDouble()).toInt() val p = IntArray(m * k) for (i in 0 until k) for (q in 0 until m) p[i * m + q] = q * k + i val ans = StringBuilder() for (i in 0 until m * k) { var j = i while (p[j] >= 0) { ans.append((j / m).toString()) val v = p[j] p[j] = -1 j = v } } for (i in 0 until n - 1) ans.append("0") return ans.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,167
kotlab
Apache License 2.0
base/sdk-common/src/main/java/com/android/ide/common/util/PathMap.kt
qiangxu1996
255,410,085
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2018 The Android Open Source Project * * 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 com.android.ide.common.util /** * A collection that maps [PathString] instances onto arbitrary data. Provides efficient * algorithms for locating values based on a key prefix and locating the value matching the * longest prefix of a given path. */ interface PathMap<out T> { /** * Returns the sequence of values in this [PathMap]. */ val values: Sequence<T> /** * Returns true iff any key in the map starts with the given prefix. */ fun containsKeyStartingWith(possiblePrefix: PathString): Boolean /** * Returns all entries whose keys start with the given prefix. */ fun findAllStartingWith(possiblePrefix: PathString): Sequence<T> /** * Looks up an exact match for the given key in the map. */ operator fun get(key: PathString): T? /** * Returns true of this map contains a prefix of the given key or the key itself. */ fun containsPrefixOf(key: PathString): Boolean /** * Returns the value associated with the longest prefix of the given key. Returns null if either * the value is null or the map contains no values for the given key. Runs in O(1) with respect * to the number of entries in the map. */ fun findMostSpecific(key: PathString): T? }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
1,907
vmtrace
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem1239/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem1239 /** * LeetCode page: [1239. Maximum Length of a Concatenated String with Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/); */ class Solution { /* Complexity: * Time O(2^N) and Space O(N) where N is the size of arr; */ fun maxLength(arr: List<String>): Int { return findMaxLength(arr) } private fun findMaxLength( lowercaseStrings: List<String>, index: Int = 0, existencePerLowercase: BooleanArray = BooleanArray(26) ): Int { if (index > lowercaseStrings.lastIndex) return getLength(existencePerLowercase) val currStr = lowercaseStrings[index] val existencesAfterAppend = plusButReturnNullIfNotUnique(existencePerLowercase, currStr) return existencesAfterAppend ?.let { maxOf( findMaxLength(lowercaseStrings, index + 1, it), findMaxLength(lowercaseStrings, index + 1, existencePerLowercase) ) } ?: findMaxLength(lowercaseStrings, index + 1, existencePerLowercase) } private fun getLength(existencePerLowercase: BooleanArray) = existencePerLowercase.count { it } private fun plusButReturnNullIfNotUnique(existencePerLowercase: BooleanArray, newString: String): BooleanArray? { val existences = existencePerLowercase.clone() for (char in newString) { val index = char - 'a' if (existences[index]) return null existences[index] = true } return existences } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,658
hj-leetcode-kotlin
Apache License 2.0
practice-4/src/practice4e.kt
jomartigcal
266,662,951
false
null
// Special Permutation // https://codeforces.com/contest/1347/problem/E private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } fun main() { val lines = readInt() for (line in 1..lines) { val number = readInt() if (number < 4) { println("-1") } else { println(getPermutation(number).joinToString(" ")) } } } fun getPermutation(number: Int): List<Int> { val permutations = mutableSetOf<Int>() val numbers = (1..number).map { it } as MutableList val evens = numbers.filter { it % 2 == 0} permutations.addAll(evens) val odds = numbers.filter { it % 2 != 0}.reversed() permutations.add(evens.last()-3) permutations.addAll(odds) return permutations.toList() }
0
Kotlin
0
0
ad1677940fa006e59e9b0f2ce6c6b26e7d76c6c3
894
kotlin-heroes
Apache License 2.0
y2016/src/main/kotlin/adventofcode/y2016/Day19.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution import kotlin.math.log2 object Day19 : AdventSolution(2016, 19, "An Elephant Named Joseph") { //Jospehus problem override fun solvePartOne(input: String): String { val solved = 2 * (input.toInt() - (1 shl log2(input.toDouble()).toInt())) + 1 return solved.toString() } //more complicated pattern, brute force instead override fun solvePartTwo(input: String): String { val elves = (1..input.toInt()).toList() return playElvesGame(elves, ::filterDayTwo).toString() } private fun playElvesGame(elves: List<Int>, filter: (List<Int>) -> List<Int>): Int = if (elves.size == 1) elves[0] else playElvesGame(filter(elves), filter) private fun filterDayTwo(list: List<Int>): List<Int> = list .filterIndexed { index, _ -> index < list.size / 2 || index % 3 == 2 - (list.size % 3) } .let { it.rotate(list.size - it.size) } private fun <T> List<T>.rotate(cut: Int): List<T> = drop(cut) + take(cut) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,084
advent-of-code
MIT License
src/Day08.kt
sabercon
648,989,596
false
null
fun main() { tailrec fun run(instruction: List<Pair<String, Int>>, acc: Int, i: Int, visited: Set<Int>): Pair<Boolean, Int> { if (i in visited) return false to acc if (i == instruction.size) return true to acc val (op, arg) = instruction[i] val (newAcc, j) = when (op) { "acc" -> acc + arg to i + 1 "jmp" -> acc to i + arg "nop" -> acc to i + 1 else -> error("Unknown instruction $op") } return run(instruction, newAcc, j, visited + i) } val input = readLines("Day08").map { val (op, arg) = it.split(" ") op to arg.toInt() } run(input, 0, 0, emptySet()).second.println() for (i in input.indices) { val (op, arg) = input[i] val newOp = when (op) { "jmp" -> "nop" "nop" -> "jmp" else -> continue } val newInput = input.withIndex() .map { (j, instruction) -> if (i == j) newOp to arg else instruction } val (terminated, acc) = run(newInput, 0, 0, emptySet()) if (terminated) { acc.println() break } } }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
1,173
advent-of-code-2020
MIT License
src/day07/Day07Answer1.kt
IThinkIGottaGo
572,833,474
false
{"Kotlin": 72162}
package day07 import readInput /** * Answers from [Advent of Code 2022 Day 7 | Kotlin](https://youtu.be/Q819VW8yxFo) */ fun main() { val day7 = Day7(readInput("day07")) println(day7.part1()) // 1723892 println(day7.part2()) // 8474158 } private val PATTERN = """[$] cd (.*)|(\d+).*""".toRegex() class Day7(lines: List<String>) { private val sizes = buildMap { put("", 0) var cwd = "" for (line in lines) { val match = PATTERN.matchEntire(line) ?: continue match.groups[1]?.value?.let { dir -> cwd = when (dir) { "/" -> "" ".." -> cwd.substringBeforeLast('/', "") else -> if (cwd.isEmpty()) dir else "$cwd/$dir" } } ?: match.groups[2]?.value?.toIntOrNull()?.let { size -> var dir = cwd while (true) { put(dir, getOrElse(dir) { 0 } + size) if (dir.isEmpty()) break dir = dir.substringBeforeLast('/', "") } } } } fun part1(): Int = sizes.values.sumOf { if (it <= 100000) it else 0 } fun part2(): Int { val total = sizes.getValue("") return sizes.values.asSequence().filter { 70000000 - (total - it) >= 30000000 }.min() } }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,360
advent-of-code-2022
Apache License 2.0
src/kotlin/_2022/Task07.kt
MuhammadSaadSiddique
567,431,330
false
{"Kotlin": 20410}
package _2022 import Task import readInput object Task07 : Task { private const val MAX_SPACE = 100_000 private const val NEEDED_SPACE = 30_000_000 private const val TOTAL_SPACE = 70_000_000 override fun partA() = buildFilesystem().root.flatten() .map { it.space() } .filter { space -> space <= MAX_SPACE } .sum() override fun partB() = buildFilesystem().let { fs -> fs.root.flatten() .map { it.space() } .sorted() .first { space -> space >= NEEDED_SPACE - (TOTAL_SPACE - fs.root.space()) } } private fun buildFilesystem() = parseInput().fold(Filesystem()) { fs, input -> fs.parse(input) } data class Filesystem(val root: Directory, var current: Directory?) { constructor() : this(root = Directory("/")) constructor(root: Directory) : this(root = root, current = root) fun parse(input: List<String>): Filesystem = input.let { (arg1, arg2, arg3) -> when (arg1) { "$" -> current = when (arg3) { null -> current "/" -> root ".." -> current?.parent else -> current?.children?.find { it.name == arg3 } } "dir" -> current?.children?.add( Directory(name = arg2, parent = current) ) else -> current?.files?.add(arg1.toInt()) } return this } } data class Directory( val name: String, val parent: Directory? = null, val children: ArrayList<Directory> = ArrayList(), val files: ArrayList<Int> = ArrayList() ) { fun space(): Int = files.sumOf { it } + children.sumOf { it.space() } fun flatten(): List<Directory> = children + children.flatMap { it.flatten() } } private fun parseInput() = readInput("_2022/07") .split('\n') .map { it.split(" ") } operator fun List<String>.component3(): String? = getOrNull(2) }
0
Kotlin
0
0
3893ae1ac096c56e224e798d08d7fee60e299a84
2,180
AdventCode-Kotlin
Apache License 2.0
src/main/kotlin/aoc2020/RainRisk.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.Dir import komu.adventofcode.utils.Direction import komu.adventofcode.utils.Point fun rainRisk1(input: List<String>): Int { val instructions = input.map { ShipInstruction.parse(it) } var direction = Direction.RIGHT var ship = Point.ORIGIN for (inst in instructions) { when (inst.op) { 'N' -> ship = ship.towards(Direction.UP, inst.value) 'E' -> ship = ship.towards(Direction.RIGHT, inst.value) 'S' -> ship = ship.towards(Direction.DOWN, inst.value) 'W' -> ship = ship.towards(Direction.LEFT, inst.value) 'F' -> ship = ship.towards(direction, inst.value) 'L' -> repeat(inst.value / 90) { direction = direction.left } 'R' -> repeat(inst.value / 90) { direction = direction.right } } } return ship.manhattanDistanceFromOrigin } fun rainRisk2(input: List<String>): Int { val instructions = input.map { ShipInstruction.parse(it) } var waypoint = Point(10, 1) var ship = Point.ORIGIN for (inst in instructions) { when (inst.op) { 'N' -> waypoint = waypoint.towards(Dir.NORTH, inst.value) 'E' -> waypoint = waypoint.towards(Dir.EAST, inst.value) 'S' -> waypoint = waypoint.towards(Dir.SOUTH, inst.value) 'W' -> waypoint = waypoint.towards(Dir.WEST, inst.value) 'F' -> ship = Point(ship.x + inst.value * waypoint.x, ship.y + inst.value * waypoint.y) 'L' -> repeat(inst.value / 90) { waypoint = waypoint.rotateCounterClockwise() } 'R' -> repeat(inst.value / 90) { waypoint = waypoint.rotateClockwise() } } } return ship.manhattanDistanceFromOrigin } private data class ShipInstruction(val op: Char, val value: Int) { companion object { private val regex = Regex("""(.)(\d+)""") fun parse(line: String): ShipInstruction { val (_, op, value) = regex.matchEntire(line)?.groupValues ?: error("invalid line '$line'") return ShipInstruction(op[0], value.toInt()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,503
advent-of-code
MIT License
src/main/kotlin/day14.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.Input import shared.Point import shared.XYMap fun main() { val input = Input.day(14) println(day14A(input)) println(day14B(input)) } fun day14A(input: Input): Int { val platform = Platform(input) platform.roll(0, -1) return platform.loadNorthSupportBeams() } fun day14B(input: Input): Int { val platform = Platform(input) val history = mutableListOf<Set<Point>>() val repeat = 1000000000 var count = 0 var cycleFound = false while (count < repeat) { platform.roll(0, -1) platform.roll(-1, 0) platform.roll(0, 1) platform.roll(1, 0) if(history.contains(platform.snapshot()) && !cycleFound) { cycleFound = true val cycle = count - history.indexOf(platform.snapshot()) val rest = repeat - count count += cycle * ((rest / cycle)-1) } else { history.add(platform.snapshot()) } count++ } return platform.loadNorthSupportBeams() } private class Platform(input: Input) { val map = XYMap(input) { it } fun roll(dirX: Int, dirY: Int) { do { val rocks = map.all { it == 'O' }.keys rocks.forEach { val rollsTo = Point(it.x + dirX, it.y + dirY) if(map.getOrNull(rollsTo) == '.') { map[rollsTo] = 'O' map[it] = '.' } } } while (rocks != map.all { it == 'O' }.keys) } fun loadNorthSupportBeams(): Int { return map.all { it == 'O' }.keys.sumOf { map.height - it.y } } fun snapshot() = map.all { it == 'O' }.keys }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
1,690
AdventOfCode2023
MIT License
src/main/kotlin/g0501_0600/s0552_student_attendance_record_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0552_student_attendance_record_ii // #Hard #Dynamic_Programming #2023_01_17_Time_151_ms_(100.00%)_Space_33.3_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun checkRecord(n: Int): Int { if (n == 0 || n == 1 || n == 2) { return n * 3 + n * (n - 1) } val mod: Long = 1000000007 val matrix = arrayOf( longArrayOf(1, 1, 0, 1, 0, 0), longArrayOf(1, 0, 1, 1, 0, 0), longArrayOf(1, 0, 0, 1, 0, 0), longArrayOf(0, 0, 0, 1, 1, 0), longArrayOf(0, 0, 0, 1, 0, 1), longArrayOf(0, 0, 0, 1, 0, 0) ) val e = quickPower(matrix, n - 1) return ( (e[0].sum() + e[1].sum() + e[3].sum()) % mod ).toInt() } private fun quickPower(a: Array<LongArray>, times: Int): Array<LongArray> { var a = a var times = times val n = a.size var e = Array(n) { LongArray(n) } for (i in 0 until n) { e[i][i] = 1 } while (times != 0) { if (times % 2 == 1) { e = multiple(e, a, n) } times = times shr 1 a = multiple(a, a, n) } return e } private fun multiple(a: Array<LongArray>, b: Array<LongArray>, n: Int): Array<LongArray> { val target = Array(n) { LongArray(n) } for (j in 0 until n) { for (k in 0 until n) { for (l in 0 until n) { target[j][k] += a[j][l] * b[l][k] target[j][k] = target[j][k] % 1000000007 } } } return target } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,711
LeetCode-in-Kotlin
MIT License
src/Day10.kt
luiscobo
574,302,765
false
{"Kotlin": 19047}
import java.lang.StringBuilder enum class ProgramInstruction(val cycles: Int) { NOOP(1), ADDX(2) } fun parseInstruction(line: String): Pair<ProgramInstruction, Int> { val components = line.split(" ") if (components[0] == "noop") { return ProgramInstruction.NOOP to 0 } val num = components[1].toInt() return ProgramInstruction.ADDX to num } fun turnOnPixel(crt: MutableList<StringBuilder>, cycle: Int, registerX: Int) { val row = (cycle - 1) / 40 val pixelPos = (cycle - 1) % 40 if (pixelPos in registerX - 1 .. registerX + 1) { crt[row].setCharAt(pixelPos, '#') } } fun initCRT() = MutableList(6) { StringBuilder(".".repeat(40)) } fun renderCRT(crt: MutableList<StringBuilder>) { crt.forEach { println(it) } } const val LAST_CYCLE = 220 fun main() { fun part1(input: List<String>): Int { var importantCycles = 20 var sumSignalStrength = 0 var registerX = 1 var cycles = 0 for (line in input) { val (instr, num) = parseInstruction(line) if ((cycles == importantCycles - 2 && instr == ProgramInstruction.ADDX) || (cycles == importantCycles - 1)){ if (cycles <= LAST_CYCLE) { sumSignalStrength += registerX * importantCycles } importantCycles += 40 } registerX += num cycles += instr.cycles } return sumSignalStrength } fun part2(input: List<String>) { val crt = initCRT() var registerX = 1 var cycles = 1 for (line in input) { val (instr, num) = parseInstruction(line) repeat (instr.cycles) { turnOnPixel(crt, cycles, registerX) cycles++ } registerX += num } renderCRT(crt) } // --------------------------------------------- val input = readInput("day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
c764e5abca0ea40bca0b434bdf1ee2ded6458087
2,055
advent-of-code-2022
Apache License 2.0
src/Day10.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day10A(readFile("Day10"))) println(day10B(readFile("Day10"))) } fun day10B(input: String): String { val ops = input.trim().split("\n") var cycle = 1 var pos = 0 var reg = 1 var screen = "" ops.forEach { op -> if (op == "noop") { println("pos: $pos reg $reg in ${pos in (reg - 1)..(reg + 1)}") screen += if (pos in (reg - 1)..(reg + 1)) "#" else "." screen += if (pos == 39) "\n" else "" cycle++ pos = (pos + 1) % 40 } else { println("pos: $pos reg $reg in ${pos in (reg - 1)..(reg + 1)}") screen += if (pos in (reg - 1)..(reg + 1)) "#" else "." screen += if (pos == 39) "\n" else "" cycle++ pos = (pos + 1) % 40 println("pos: $pos reg $reg in ${pos in (reg - 1)..(reg + 1)}") screen += if (pos in (reg - 1)..(reg + 1)) "#" else "." screen += if (pos == 39) "\n" else "" cycle++ pos = (pos + 1) % 40 reg += op.split(" ")[1].toInt() } } return screen } fun day10A(input: String): Int { val ops = input.trim().split("\n") val cycles = listOf<Int>(20, 60, 100, 140, 180, 220) var signal = 0; var reg = 1 var cycle = 0 ops.forEach { op -> if (op == "noop") { cycle++ if (cycles.contains(cycle)) { signal += reg * cycle } } else { cycle++ if (cycles.contains(cycle)) { signal += reg * cycle } cycle++ if (cycles.contains(cycle)) { signal += reg * cycle } // println(op.split(" ")[1].toInt()) reg += op.split(" ")[1].toInt() } } return signal }
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
1,860
AdventOfCode22
Apache License 2.0
src/main/kotlin/days/Day8.kt
hughjdavey
159,955,618
false
null
package days class Day8 : Day(8) { private val root = parseTree(inputString) override fun partOne(): Any { return metadataSum(root) } override fun partTwo(): Any { return nodeValue(root) } data class AocNode(val header: Pair<Int, Int>, val childNodes: List<AocNode>, val metadata: List<Int>) companion object { fun parseTree(input: String): AocNode { return parseTree(input.split(" ").map { it.trim().toInt() }.iterator()) } private fun parseTree(input: Iterator<Int>): AocNode { val header = input.next() to input.next() val children = (0 until header.first).map { parseTree(input) } val metadata = (0 until header.second).map { input.next() } return AocNode(header, children, metadata) } fun metadataSum(node: AocNode): Int { return node.metadata.sum() + node.childNodes.map { metadataSum(it) }.sum() } fun nodeValue(node: AocNode): Int { return if (node.childNodes.isEmpty()) { node.metadata.sum() } else { node.metadata.filterNot { it == 0 }.map { val childNodeIndex = it - 1 if (childNodeIndex <= node.childNodes.lastIndex) nodeValue(node.childNodes[it - 1]) else 0 }.sum() } } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
1,418
aoc-2018
Creative Commons Zero v1.0 Universal
src/main/kotlin/g0901_1000/s0954_array_of_doubled_pairs/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0954_array_of_doubled_pairs // #Medium #Array #Hash_Table #Sorting #Greedy // #2023_05_02_Time_462_ms_(100.00%)_Space_92.1_MB_(50.00%) class Solution { fun canReorderDoubled(arr: IntArray): Boolean { val max = 0.coerceAtLeast(arr.max()) val min = 0.coerceAtMost(arr.min()) val positive = IntArray(max + 1) val negative = IntArray(-min + 1) for (a in arr) { if (a < 0) { negative[-a]++ } else { positive[a]++ } } return if (positive[0] % 2 != 0) { false } else validateFrequencies(positive, max) && validateFrequencies(negative, -min) } private fun validateFrequencies(frequencies: IntArray, limit: Int): Boolean { for (i in 0..limit) { if (frequencies[i] == 0) { continue } if (2 * i > limit || frequencies[2 * i] < frequencies[i]) { return false } frequencies[2 * i] -= frequencies[i] } return true } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,103
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g0301_0400/s0363_max_sum_of_rectangle_no_larger_than_k/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0301_0400.s0363_max_sum_of_rectangle_no_larger_than_k // #Hard #Array #Dynamic_Programming #Binary_Search #Matrix #Ordered_Set // #2022_11_19_Time_243_ms_(100.00%)_Space_36.1_MB_(100.00%) class Solution { fun maxSumSubmatrix(matrix: Array<IntArray>, k: Int): Int { if (matrix.size == 0 || matrix[0].size == 0) { return 0 } val row = matrix.size val col = matrix[0].size var res = Int.MIN_VALUE for (i in 0 until col) { val sum = IntArray(row) for (j in i until col) { for (r in 0 until row) { sum[r] += matrix[r][j] } var curr = 0 var max = sum[0] for (n in sum) { curr = Math.max(n, curr + n) max = Math.max(curr, max) if (max == k) { return max } } if (max < k) { res = Math.max(max, res) } else { for (a in 0 until row) { var currSum = 0 for (b in a until row) { currSum += sum[b] if (currSum <= k) { res = Math.max(currSum, res) } } } if (res == k) { return res } } } } return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,600
LeetCode-in-Kotlin
MIT License
src/main/kotlin/io/math/IntegerToEnglishWords.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.math import io.utils.runTests import java.lang.StringBuilder private val LESS_THAN_20 = arrayOf("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen") private val TENS = arrayOf("", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety") private val THOUSANDS = arrayOf("", "Thousand", "Million", "Billion") // https://leetcode.com/problems/integer-to-english-words/ class IntegerToEnglishWords { fun execute(number: Int): String { if (number == 0) return "Zero" var current = 0 var input = number val result = StringBuilder() while (input > 0) { val mod = input % 1000 if (mod != 0) result.insert(0, "${helper(mod)} ${THOUSANDS[current]} ") input /= 1000 current++ } return result.toString().trim() } private fun helper(input: Int): String = when { input == 0 -> "" input < 20 -> LESS_THAN_20[input] input < 100 -> "${TENS[input / 10]} ${helper(input % 10)}".trim() else -> "${LESS_THAN_20[input / 100]} Hundred ${helper(input % 100)}".trim() } } fun main() { runTests(listOf( 123 to "One Hundred Twenty Three", 12345 to "Twelve Thousand Three Hundred Forty Five", 1234567 to "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven", 1234567891 to "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One", 50868 to "Fifty Thousand Eight Hundred Sixty Eight" )) { (input, value) -> value to IntegerToEnglishWords().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,690
coding
MIT License
AdventOfCodeDay17/src/nativeMain/kotlin/Day17.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
import kotlin.math.absoluteValue import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt typealias Point = Pair<Int,Int> typealias TargetArea = Pair<IntRange, IntRange> typealias Velocity = Pair<Int, Int> typealias Path = List<Point> class Day17(private val lines:List<String>) { fun solvePart1() = solve(processInput(lines)) .maxOf{path -> path.maxOf{pt -> pt.second}} fun solvePart2() = solve(processInput(lines)).count() private fun solve(target:TargetArea):Sequence<Path> = // to solve one path, given starting point of 0,0 and some velocity vx,vy // do apply point.next(velocity); velocity.next() and collect points // until either in target or after target. If in target, return points // otherwise, return empty list. target.generateStartingVelocities().map{ velocity -> Point(0,0).generatePath(velocity, target) } .filter{path -> path.isNotEmpty()} //.onEach{println(it)} private fun processInput(inputLines:List<String>):Pair<IntRange,IntRange> { val theOnlyLine = inputLines.first() val splits = theOnlyLine.split(": x=", ", y=") val xString = splits[1] val xSplits = xString.split("..") val xRet = xSplits[0].toInt() .. xSplits[1].toInt() val yString = splits[2] val ySplits = yString.split("..") val yRet = ySplits[0].toInt() .. ySplits[1].toInt() return Pair(xRet,yRet) } // helpful extensions operator fun TargetArea.contains(pt:Point):Boolean = this.first.contains(pt.first) && this.second.contains(pt.second) private fun TargetArea.isAfter(pt:Point):Boolean = pt.first > this.first.last || pt.second < this.second.first fun Point.next(velocity:Velocity) = Point(this.first + velocity.first, this.second+velocity.second) fun Velocity.next() = Velocity( when { this.first > 0 -> this.first-1 this.first < 0 -> this.first+1 else -> this.first }, this.second-1) private fun Point.generatePath(velocity:Velocity, target:TargetArea):Path{ var workingPoint = this var workingVelocity = velocity val ret = mutableListOf(workingPoint) do { workingPoint = workingPoint.next(workingVelocity) workingVelocity = workingVelocity.next() ret.add(workingPoint) } while (workingPoint !in target && !target.isAfter(workingPoint)) return if (target.isAfter(workingPoint)) emptyList() else ret } // given a target area, generate a sequence of velocities // // I know that it must be > 0,0 // and < TargetArea.lasX+1 and > TargetArea.lastY-1 // so, that is my pool of initial velocities private fun TargetArea.generateStartingVelocities() = sequence { val target = this@generateStartingVelocities // val minXStep = ceil(calculateXStep(target.first.first)) // .toInt()/2 // val maxXStep = floor(calculateXStep(target.first.last)) // .toInt()*2 // val minYStep = ceil(calculateYStep(minXStep,target.second.first)) // .toInt()/2 // val maxYStep = floor(calculateYStep(maxXStep, target.second.last)) // .toInt()*2 val xRange = 0..target.first.last val yRange = target.second.first..target.second.first.absoluteValue (yRange).forEach { y -> (xRange).forEach { x -> yield(Velocity(x,y)) } } } // using the Power series for addition (1+2+3+...) // = n*(n+1)/2 // and the quadratic equation to solve for given distance X // in integer number of Steps. private fun calculateXStep(xDistance:Int)= (sqrt(1+8*xDistance.toDouble())/2)-1 private fun calculateYStep(step:Int, yDistance:Int):Double // we are starting y at 0. We have some target y at ty // we are going up to some maxY which takes some steps s1. Then // we are going from maxY to tt in the remaining steps. // So, we have two power series = (2.0*yDistance+step*(step+1))/(2*(1+step)) }
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
4,277
AdventOfCode2021
The Unlicense
test/leetcode/LetterCombinationsOfAPhoneNumber.kt
andrej-dyck
340,964,799
false
null
package leetcode import lib.StringArrayArg import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.converter.ConvertWith import org.junit.jupiter.params.provider.CsvSource /** * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ * * 17. Letter Combinations of a Phone Number * [Medium] * * Given a string containing digits from 2-9 inclusive, return all possible letter combinations * that the number could represent. * Return the answer in any order. * * A mapping of digit to letters (just like on the telephone buttons) is given below. * Note that 1 does not map to any letters. * * Constraints: * - 0 <= digits.length <= 4 * - digits[i] is a digit in the range ['2', '9']. */ fun letterCombinations(digits: String) = when { digits.none() -> emptySequence() else -> digits.asSequence().map(::digitLetters).combinations() } fun Sequence<String>.combinations(): Sequence<String> = when { none() -> sequenceOf("") else -> drop(1).combinations().flatMap { l -> first().map { "$it$l" } } } fun digitLetters(digit: Char) = when (digit) { '2' -> "abc" '3' -> "def" '4' -> "ghi" '5' -> "jkl" '6' -> "mno" '7' -> "pqrs" '8' -> "tuv" '9' -> "wxyz" '0' -> " " else -> "" } /** * Unit Tests */ class LetterCombinationsOfAPhoneNumberTest { @ParameterizedTest @CsvSource( "''; []", "2; [a,b,c]", "3; [d,e,f]", "4; [g,h,i]", "5; [j,k,l]", "6; [m,n,o]", "7; [p,q,r,s]", "8; [t,u,v]", "9; [w,x,y,z]", "0; [' ']", "23; [ad,ae,af,bd,be,bf,cd,ce,cf]", delimiter = ';' ) fun `all combinations of phone digits to letters`( digits: String, @ConvertWith(StringArrayArg::class) expectedLetterCombinations: Array<String> ) { assertThat( letterCombinations(digits).toList() ).containsExactlyInAnyOrderElementsOf( expectedLetterCombinations.toList() ) } @ParameterizedTest @CsvSource( "222; abc", "43556; hello", "568546; kotlin", "435560568546; hello kotlin", delimiter = ';' ) fun `phone digits can build words`(digits: String, word: String) { assertThat( letterCombinations(digits).firstOrNull { it == word } ).contains( word ) } }
0
Kotlin
0
0
3e3baf8454c34793d9771f05f330e2668fda7e9d
2,488
coding-challenges
MIT License
src/Day01.kt
roxanapirlea
572,665,040
false
{"Kotlin": 27613}
fun main() { fun getFoodByElf(input: String): List<Long> = input.split("${System.lineSeparator()}${System.lineSeparator()}") .map { foodByElf -> foodByElf.split(System.lineSeparator()) .map { foodItem -> foodItem.toLong() } .reduce { acc, item -> acc + item } } fun part1(input: String): Long { return getFoodByElf(input).max() } fun part2(input: String): Long { return getFoodByElf(input).sortedDescending().take(3).reduce { acc, food -> acc + food } } // test if implementation meets criteria from the description, like: val testInput = readText("Day01_test").trim() check(part1(testInput) == 24000L) check(part2(testInput) == 45000L) val input = readText("Day01").trim() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6c4ae6a70678ca361404edabd1e7d1ed11accf32
876
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MissingNumberInProgression.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 /** * 1228. Missing Number In Arithmetic Progression * @see <a href="https://leetcode.com/problems/missing-number-in-arithmetic-progression/">Source</a> */ fun interface MissingNumberInProgression { operator fun invoke(arr: IntArray): Int } /** * Approach 1: Linear search * Time complexity : O(n). * Space complexity : O(1). */ class MNLinearSearch : MissingNumberInProgression { override operator fun invoke(arr: IntArray): Int { if (arr.isEmpty() || arr.size < 2) return 0 val n = arr.size val diff = arr.last().minus(arr.first()).div(n) var expected = arr.first() for (value in arr) { if (value != expected) return expected expected += diff } return expected } } /** * Approach 2: Binary Search * Time complexity : O(log n). * Space complexity : O(1). */ class MNBinarySearch : MissingNumberInProgression { override operator fun invoke(arr: IntArray): Int { if (arr.isEmpty() || arr.size < 2) return 0 val n = arr.size val diff = arr.last().minus(arr.first()).div(n) var lo = 0 var hi = n - 1 while (lo < hi) { val mid = lo.plus(hi).div(2) if (arr[mid] == arr.first() + mid * diff) { lo = mid + 1 } else { hi = mid } } return arr.first() + diff * lo } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,058
kotlab
Apache License 2.0
kotlin/0518-coin-change-ii.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * DP with O(n) memory */ class Solution { fun change(amount: Int, coins: IntArray): Int { val dp = IntArray(amount + 1) dp[0] = 1 for (coin in coins) { for (i in 1..amount) { if (i - coin >= 0) dp[i] += dp[i - coin] } } return dp[amount] } } /* * DP with O(n^2) memory */ class Solution { fun change(amount: Int, coins: IntArray): Int { val dp = Array(coins.size) { IntArray(amount + 1) } for (i in 0 until coins.size) dp[i][0] = 1 for (i in 0..coins.lastIndex) { for (j in 1..amount) { if (i > 0) { dp[i][j] += dp[i - 1][j] } if (j - coins[i] >= 0) dp[i][j] += dp[i][j - coins[i]] } } return dp[coins.lastIndex][amount] } } /* * DFS + Memo */ class Solution { fun change(amount: Int, coins: IntArray): Int { val cache = Array(coins.size) { IntArray(amount + 1) {-1} } fun dfs(i: Int, a: Int): Int { if (a == amount) return 1 if (a > amount) return 0 if (i == coins.size) return 0 if (cache[i][a] != -1) return cache[i][a] cache[i][a] = dfs(i, a + coins[i]) + dfs(i + 1, a) return cache[i][a] } return dfs(0, 0) } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,503
leetcode
MIT License
src/Day01.kt
rmyhal
573,210,876
false
{"Kotlin": 17741}
import java.util.* import kotlin.math.max fun main() { fun part1(input: List<String>): Long { return maxCalories(input) } fun part2(input: List<String>): Long { return max3Calories(input) } val input = readInput("Day01") println(part1(input)) println(part2(input)) } private fun maxCalories(input: List<String>): Long { var elfIndex = 0 var elfCalories = 0L var maxCalories = 0L for (i in input.indices) { if (input[i].isEmpty()) { maxCalories = max(maxCalories, elfCalories) elfIndex++ elfCalories = 0 } else { elfCalories += input[i].toLong() } } maxCalories = max(maxCalories, elfCalories) return maxCalories } private fun max3Calories(input: List<String>): Long { val queue = PriorityQueue<Long>(3) var elfIndex = 0 var elfCalories = 0L for (i in input.indices) { if (input[i].isEmpty()) { if (queue.size < 3) { queue.offer(elfCalories) } else if (elfCalories > queue.peek()) { queue.poll() queue.offer(elfCalories) } elfIndex++ elfCalories = 0L } else { elfCalories += input[i].toLong() } } return queue.sum() }
0
Kotlin
0
0
e08b65e632ace32b494716c7908ad4a0f5c6d7ef
1,177
AoC22
Apache License 2.0
2019/src/main/kotlin/com/github/jrhenderson1988/adventofcode2019/day10/Space.kt
jrhenderson1988
289,786,400
false
{"Kotlin": 216891, "Java": 166355, "Go": 158613, "Rust": 124111, "Scala": 113820, "Elixir": 112109, "Python": 91752, "Shell": 37}
package com.github.jrhenderson1988.adventofcode2019.day10 import com.github.jrhenderson1988.adventofcode2019.angle import com.github.jrhenderson1988.adventofcode2019.manhattanDistance import com.github.jrhenderson1988.adventofcode2019.pointsBetween class Space(map: String) { private val asteroids = parseAsteroidCoordinates(map) fun maximumVisibleAsteroidsFromBestAsteroid() = calculateTotalAsteroidsVisibleFromEachAsteroid() .values .max() fun calculateNthDestroyedAsteroid(n: Int): Pair<Int, Int> { val base = calculateTotalAsteroidsVisibleFromEachAsteroid().maxBy { it.value }!!.key val toDestroy = mutableListOf<Pair<Pair<Int, Int>, Double>>() asteroids .filter { it != base } .groupBy { angle(base, it) } .forEach { (angle, asteroids) -> asteroids.sortedBy { manhattanDistance(base, it) } .forEachIndexed { index, asteroid -> toDestroy.add(Pair(asteroid, angle + (360 * index))) } } if (n >= toDestroy.size) { error("Asteroid $n does not exist") } return toDestroy.sortedBy { it.second }.map { it.first }[n] } fun calculateTotalAsteroidsVisibleFromEachAsteroid() = asteroids .map { it to totalAsteroidsVisibleFrom(it) } .toMap() fun totalAsteroidsVisibleFrom(target: Pair<Int, Int>): Int { return asteroids .map { other -> if (target != other && isAsteroidVisible(target, other)) 1 else 0 } .sum() } fun isAsteroidVisible(a: Pair<Int, Int>, b: Pair<Int, Int>) = pointsBetween(a, b).intersect(asteroids).isEmpty() companion object { fun parseAsteroidCoordinates(map: String): Set<Pair<Int, Int>> { val coordinates = mutableSetOf<Pair<Int, Int>>() map.lines() .forEachIndexed { y, line -> line.forEachIndexed { x, ch -> if (ch == '#') { coordinates.add(Pair(x, y)) } } } return coordinates } } }
0
Kotlin
0
0
7b56f99deccc3790c6c15a6fe98a57892bff9e51
2,245
advent-of-code
Apache License 2.0
proyek-submission-mpk-2.0.2/src/main/kotlin/com/dicoding/exam/latihanopsional2/App.kt
gilarc
716,165,676
false
{"Kotlin": 77659, "JavaScript": 252}
/**************************************************************************************************** * Perhatian * * * * Agar dapat diperiksa dengan baik, hindari beberapa hal berikut: * * * * 1. Mengubah kode yang berada di dalam fungsi main() * * 2. Mengubah atau menghapus kode yang sudah ada secara default * * 3. Membuat fungsi baru yang bukan merupakan tugas latihan * * 4. Mengubah struktur project (menghapus, mengedit, dan memindahkan package) * * * ***************************************************************************************************/ package com.dicoding.exam.latihanopsional2 /** * TODO * Lengkapi fungsi di bawah dengan ketentuan sebagai berikut: * - Fungsi menerima input Integer dengan panjang digit 2-9. * - Fungsi harus mengembalikan Integer yang merupakan hasil penjumlahan dari angka terkecil dan angka terbesar dari nilai yang diinput. * * Contoh: * Input = minAndMax(987234) -> Output = 11 | Penjelasan: Angka terkecil= 2, angka terbesar=9 -> 2+9 -> 11 * Input = minAndMax(8812334) -> Output = 9 | Penjelasan: Angka terkecil= 1, angka terbesar=8 -> 1+8 -> 9 * Input = minAndMax(10) -> Output = 1 | Penjelasan: Angka terkecil= 0, angka terbesar=1 -> 0+1 -> 1 * * Modul terkait: Kotlin Fundamental & Collections * */ fun minAndMax(number: Int): Int { val digits = generateSequence(number) { it / 10 } .takeWhile { it > 0 } .map { it % 10 } .toList() if (digits.isEmpty()) return 0 val (minValue, maxValue) = digits.fold(Pair(digits[0], digits[0])) { (min, max), digit -> Pair(min.coerceAtMost(digit), max.coerceAtLeast(digit)) } return minValue + maxValue } fun main() { println(minAndMax(987234) == 11) println(minAndMax(8812334) == 9) println(minAndMax(10) == 1) }
0
Kotlin
0
0
c4e7af027d018681ae47bf7d176b6145581b1fdb
2,356
myDicodingSubmissions
MIT License
2020/day5/day5.kt
flwyd
426,866,266
false
{"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398}
/* * Copyright 2021 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ package day5 import kotlin.time.ExperimentalTime import kotlin.time.TimeSource import kotlin.time.measureTimedValue /* Input: 7 F or B then 3 L or R representing 7-digit binary row # and 3-digit binary column #. * Output seat ID is 8 * row + col. * This implementation doesn't use binary operators because the problem description got me in the * mental space of splitting ranges in two, which is more awkward than I expected. */ fun seatIds(input: Sequence<String>): Sequence<Int> { return input .map { line -> var rows = 0..127 line.asSequence().take(7).forEach { val size = rows.last - rows.first + 1 rows = when (it) { 'F' -> rows.first..rows.last - size / 2 'B' -> rows.first + size / 2..rows.last else -> throw IllegalArgumentException("Unexpected $it in $line") } } var cols = 0..7 line.asSequence().drop(7).forEach { val size = cols.last - cols.first + 1 cols = when (it) { 'L' -> cols.first..cols.last - size / 2 'R' -> cols.first + size / 2..cols.last else -> throw IllegalArgumentException("Unexpected $it in $line") } } if (rows.first != rows.last || cols.first != cols.last) { throw IllegalArgumentException("Left over $rows, $cols from $line") } rows.first to cols.first } .map { it.first * 8 + it.second } } /* Return the largest seat ID. */ object Part1 { fun solve(input: Sequence<String>): String { return seatIds(input).maxOrNull()?.toString() ?: "Empty input" } } /* Return the missing seat ID, with some at the beginning and end not in the available set. */ object Part2 { fun solve(input: Sequence<String>): String { val sorted = seatIds(input).toList().sorted() for ((index, id) in sorted.withIndex()) { if (id - index != sorted.first()) { return (id - 1).toString() } } return "Open seat ID not found" } } @ExperimentalTime @Suppress("UNUSED_PARAMETER") fun main(args: Array<String>) { val lines = generateSequence(::readLine).toList() print("part1: ") TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } print("part2: ") TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let { println(it.value) System.err.println("Completed in ${it.duration}") } }
0
Julia
1
5
f2d6dbb67d41f8f2898dbbc6a98477d05473888f
2,658
adventofcode
MIT License
src/main/kotlin/Day005.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
class Day005 { data class Instruction(val count: Int, val source: Int, val target: Int) fun part1(lines: List<String>): String { val numberOfContainers = lines.first { it.trim().startsWith("1") }.trim().last().digitToInt() val containers = List(numberOfContainers) { ArrayDeque<Char>() } createContainers(lines, containers as MutableList<ArrayDeque<Char>>) val instructions: List<Instruction> = getInstructions(lines) instructions.forEach { instruction -> repeat(instruction.count) { if (containers[instruction.source - 1].isNotEmpty()) { containers[instruction.target - 1].addFirst(containers[instruction.source - 1].removeFirst()) } } } return containers.map { it.first() }.joinToString("") } fun part2(lines: List<String>): String { val numberOfContainers = lines.first { it.trim().startsWith("1") }.trim().last().digitToInt() val containers = List(numberOfContainers) { ArrayDeque<Char>() }.toMutableList() createContainers(lines, containers) val instructions: List<Instruction> = getInstructions(lines) instructions.forEach { instr -> containers[instr.target - 1].addAll(0, containers[instr.source - 1].take(instr.count)) repeat(instr.count) { containers[instr.source - 1].removeFirst() } } return containers.map { it.first() }.joinToString("") } private fun getInstructions(lines: List<String>): List<Instruction> { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() val instructions: List<Instruction> = lines .dropWhile { !it.trim().startsWith("move") } .map { val matchResult = regex.find(it) val (count, source, target) = matchResult!!.destructured Instruction(count.toInt(), source.toInt(), target.toInt()) } return instructions } private fun createContainers( lines: List<String>, containers: MutableList<ArrayDeque<Char>>, ) { lines .takeWhile { !it.trim().startsWith("1") } .map { line -> line.slice(1..line.length step 4) .mapIndexed { containerNumber, value -> if (value.isLetter()) containers[containerNumber].addLast(value) } } } }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
2,471
aoc-2022-kotlin
Apache License 2.0
app/src/main/java/com/tripletres/platformscience/domain/ShipmentDriverAssignation.kt
daniel553
540,959,283
false
{"Kotlin": 95616}
package com.tripletres.platformscience.domain import com.tripletres.platformscience.domain.algorithm.IAssignationAlgorithm import com.tripletres.platformscience.domain.model.Driver import com.tripletres.platformscience.domain.model.Shipment import com.tripletres.platformscience.util.commonFactors import com.tripletres.platformscience.util.isEven /** * Shipment driver assignation class, allows to perform driver assignation * to shipment with given algorithm. */ class ShipmentDriverAssignation( private val algorithm: IAssignationAlgorithm ) { /** * Execute the algorithm given with a set of drivers and shipments * @param drivers list with driver's names * @param shipments list with address * * @return list of drivers with shipment assigned */ fun execute( drivers: List<Driver>, shipments: List<Shipment> ): List<Driver> { //Prepare all suitability scores for driver by shipments val input = prepareShipmentToDriverAssignation(drivers, shipments) //Execute algorithm and return value return algorithm.getBestMatching(input) } /** * Prepares the shipment to driver assignation as a 2D array for algorithm */ private fun prepareShipmentToDriverAssignation( drivers: List<Driver>, shipments: List<Shipment> ): MutableList<MutableList<SuitabilityScore>> { val driversAssigned = mutableListOf<Driver>() val allSuitabilityScores = MutableList<MutableList<SuitabilityScore>>(shipments.size) { mutableListOf()} //mutableListOf<MutableList<SuitabilityScore>>() //Prepare drivers name with vowels and consonants val preparedDrivers = drivers.map { driver -> prepareDriverName(driver) } //Determine suitability score fore each shipment shipments.forEachIndexed { i, shipment -> //Get common factors for shipments val shipmentsCF = shipment.address.length.commonFactors() // For all suitability score for current shipment address and a set of drivers val allSS = getSuitabilityScore( shipment = shipment, shipmentCommonFactors = shipmentsCF, drivers = preparedDrivers, ssFactor = if (shipment.address.length.isEven()) //If shipment's destination street name length SuitabilityScoreFactor.EVEN else SuitabilityScoreFactor.ODD ) allSuitabilityScores[i] = (allSS) } return allSuitabilityScores } private fun getBestMatchingSuitabilityScore(suitabilityScores: List<SuitabilityScore>): List<Driver> { //Order suitability score list val ssList = suitabilityScores.toMutableList<SuitabilityScore>() ssList.sortBy { it.ss } //Get elements with best matching driver val drivers = ssList.distinctBy { it.driver }.map { it.driver.copy(shipment = it.shipment) } val shipments = ssList.distinctBy { it.shipment }.map { it.driver.copy(shipment = it.shipment) } //Return driver with shipment assigned return drivers } /** * Super secret algorithm, allows to get an array with SS according to certain factors */ private fun getSuitabilityScore( shipment: Shipment, drivers: List<DriverPrepared>, ssFactor: SuitabilityScoreFactor, shipmentCommonFactors: List<Int> ): MutableList<SuitabilityScore> { val ssList = mutableListOf<SuitabilityScore>() ssList.addAll(drivers.map { driver -> //Calculate ss with vowels and consonants var ss = when (ssFactor) { SuitabilityScoreFactor.EVEN -> driver.vowels * SuitabilityScoreFactor.EVEN.value() SuitabilityScoreFactor.ODD -> driver.consonants * SuitabilityScoreFactor.ODD.value() } //Add common factors besides 1 to 50% over base (1.5 multiplier) ss *= if (driver.commonFactor.intersect(shipmentCommonFactors.toSet()).any()) 1.5f else 1f SuitabilityScore(driver.driver, shipment, ss) }) return ssList } /** * Prepare driver's name with vowels and consonants and common factors */ private fun prepareDriverName(driver: Driver): DriverPrepared { val vowels = charArrayOf('A', 'E', 'I', 'O', 'U') //Prepare like -> NAME SURNAME -> NAMESURNAME val name = driver.name.trim().uppercase().filter { it.isLetter() } //Count all vowels val countVowels = name.toCharArray().count { letter -> vowels.contains(letter) } //Count all consonants val countConsonants = name.length - countVowels //Common factors of name's length val commonFactors = driver.name.length.commonFactors() return DriverPrepared(driver, name, countVowels, countConsonants, commonFactors) } internal data class DriverPrepared( val driver: Driver, val name: String, val vowels: Int, val consonants: Int, val commonFactor: List<Int> ) data class SuitabilityScore( val driver: Driver, val shipment: Shipment, var ss: Float ) internal enum class SuitabilityScoreFactor { EVEN { override fun value(): Float = 1.5f }, ODD { override fun value(): Float = 1.0f }; abstract fun value(): Float } }
0
Kotlin
0
0
2ea5962dc0ad349ae97b277ab4ecf9e9a0aee1e6
5,572
PlatformScience
FSF All Permissive License
src/Day06.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
fun main() { fun part1(input: String, windowSize: Int = 4): Int { input.windowed(windowSize) { window -> val set = mutableSetOf<Char>() set.addAll(window.asSequence()) set.size }.forEachIndexed { index, value -> if (value == windowSize) return index + windowSize } return -1 } fun part2(input: String): Int = part1(input, 14) // test if implementation meets criteria from the description, like: check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input[0])) println(part2(input[0])) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
1,107
AdventOfCode
Apache License 2.0
src/main/kotlin/tr/emreone/adventofcode/days/Day18.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.extensions.MutableMapGrid import tr.emreone.kotlin_utils.extensions.area import tr.emreone.kotlin_utils.extensions.formatted import tr.emreone.kotlin_utils.math.* import java.util.LinkedList import kotlin.collections.forEach import kotlin.math.abs class Day18 : Day(18, 2023, "Lavaduct Lagoon") { override fun part1(): Int { val instructions = inputAsList.map { val (d, s, _) = it.split(' ') val dir = when (d) { "R" -> Direction4.EAST "D" -> Direction4.SOUTH "L" -> Direction4.WEST else -> Direction4.NORTH } val steps = s.toInt() dir to steps } val map: MutableMapGrid<String> = mutableMapOf() var pos = origin instructions.forEach { (d, s) -> val end = pos + (d.vector * s) (pos..end).forEach { map[it] = "#" } pos = end } val area = map.area val bigger = area + 1 println(map.size) println(bigger.size) val q = LinkedList<Point>() q.add(bigger.upperLeft) val seen = mutableSetOf<Point>() while (q.isNotEmpty()) { val c = q.removeFirst() seen += c q += c.directNeighbors().filter { it !in q && it in bigger && it !in map && it !in seen } } map.formatted(area = bigger) { x, c -> when { x in seen -> "~" else -> "#" } } println(seen.size) return bigger.size - seen.size } override fun part2(): Long { val instructions = inputAsList.map { val (_, _, c) = it.split(' ') // c is the color in braces in hex with 6 digits // e.g. c = (#159ABC) val dir = when (c.dropLast(1).last()) { '0' -> Direction4.EAST '1' -> Direction4.SOUTH '2' -> Direction4.WEST else -> Direction4.NORTH } val steps = c .drop(2) // remove (# .dropLast(2) // remove x) .toInt(16) dir to steps } val boundary = instructions.sumOf { it.second.toLong() } val corners = instructions.runningFold(origin) { acc, instruction -> acc + (instruction.first * instruction.second) } require(corners.first() == corners.last()) { "not a closed loop" } // area by Shoelace algorithm // https://en.wikipedia.org/wiki/Shoelace_formula // https://youtu.be/0KjG8Pg6LGk?si=qC_1iX1YhQlGvI1o val area = abs( corners .zipWithNext() .sumOf { (ci, cj) -> ci.x.toLong() * cj.y - cj.x.toLong() * ci.y } ) / 2 // according to Pick's theorem: A = i + b / 2 - 1 // https://en.wikipedia.org/wiki/Pick%27s_theorem val inside = area - boundary / 2 + 1 return inside + boundary } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
3,188
advent-of-code-2023
Apache License 2.0
src/questions/FormatPhoneNumber.kt
realpacific
234,499,820
false
null
package questions /** * Given a phone number should format in the form of abc-def-ijk. Last two part can be of 2 digits */ fun main() { solution("00-44 48 5555 83612").also { println(it) } solution("00-44 48 5555 8361").also { println(it) } solution("00-44 48 5555 836122").also { println(it) } solution("00-44 48 5555").also { println(it) } solution("00-4").also { println(it) } solution("00").also { println(it) } solution("0 0 ").also { println(it) } } fun solution(S: String): String { val digits = S.toCharArray().filter { Character.isDigit(it) } if (digits.size < 3) { return digits.joinToString("") } val remainder = digits.size % 3 if (remainder == 0) { return formatPhoneNumber(digits).toString() } else { val division = digits.size / 3 if (remainder == 2) { val numberOfItemsToTake = division * 3 val formattableTo3digits = digits.subList(0, numberOfItemsToTake) return formatPhoneNumber(formattableTo3digits) .append("-") .append(digits[numberOfItemsToTake]) .append(digits[numberOfItemsToTake + 1]).toString() } else { val numberOfItemsToTake = (division - 1) * 3 val formattableTo3digits = digits.subList(0, numberOfItemsToTake) return formatPhoneNumber(formattableTo3digits) .append("-") .append(digits[numberOfItemsToTake + 0]) .append(digits[numberOfItemsToTake + 1]) .append("-") .append(digits[numberOfItemsToTake + 2]) .append(digits[numberOfItemsToTake + 3]) .toString() } } } fun formatPhoneNumber(digits: List<Char>): StringBuilder { val sb = StringBuilder() digits.forEachIndexed { index, c -> sb.append(c) if ((index + 1) % 3 == 0 && index < digits.lastIndex) { sb.append("-") } } return sb }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,067
algorithms
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-18.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.BooleanGrid import com.github.ferinagy.adventOfCode.Coord2D import com.github.ferinagy.adventOfCode.toBooleanGrid import com.github.ferinagy.adventOfCode.contains import com.github.ferinagy.adventOfCode.get import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "18-input") val test1 = readInputLines(2015, "18-test1") println("Part1:") part1(test1, 4).println() part1(input, 100).println() println() println("Part2:") part2(test1, 5).println() part2(input, 100).println() } private fun part1(input: List<String>, steps: Int): Int { var grid = input.toBooleanGrid { it == '#' } repeat(steps) { grid = grid.update() } return grid.count() } private fun part2(input: List<String>, steps: Int): Int { var grid = input.toBooleanGrid { it == '#' }.stuckCorners() repeat(steps) { grid = grid.update().stuckCorners() } return grid.count() } private fun BooleanGrid.update(): BooleanGrid = mapIndexed { coord: Coord2D, b: Boolean -> val adjacent = coord.adjacent(true).count { it in this && this[it] } b && adjacent in 2..3 || !b && adjacent == 3 } private fun BooleanGrid.stuckCorners() = apply { this[0, 0] = true this[0, height - 1] = true this[width - 1, 0] = true this[width - 1, height - 1] = true }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,499
advent-of-code
MIT License
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/QuickSort.kt
AlexRogalskiy
331,076,596
false
null
/* * Copyright (C) 2021. <NAME>. All Rights Reserved. * * 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 io.nullables.api.playground.algorithms /** * Developed by <NAME> in 1959, with his work published in 1961, Quicksort is an efficient sort algorithm using * divide and conquer approach. Quicksort first divides a large array into two smaller sub-arrays: the low elements * and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are: * 1) Pick an element, called a pivot, from the array. * 2) Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, * while all elements with values greater than the pivot come after it (equal values can go either way). * After this partitioning, the pivot is in its final position. This is called the partition operation. * 3) Recursively apply the above steps to the sub-array of elements with smaller values and separately to * the sub-array of elements with greater values. */ @ComparisonSort @UnstableSort class QuickSort : AbstractSortStrategy() { override fun <T : Comparable<T>> perform(arr: Array<T>) { sort(arr, 0, arr.size - 1) } private fun <T : Comparable<T>> sort(arr: Array<T>, lo: Int, hi: Int) { if (hi <= lo) return val j = partition(arr, lo, hi) sort(arr, lo, j - 1) sort(arr, j + 1, hi) } private fun <T : Comparable<T>> partition(arr: Array<T>, lo: Int, hi: Int): Int { var i = lo var j = hi + 1 val v = arr[lo] while (true) { while (arr[++i] < v) { if (i == hi) break } while (v < arr[--j]) { if (j == lo) break } if (j <= i) break arr.exch(j, i) } arr.exch(j, lo) return j } }
13
Kotlin
2
2
d7173ec1d9ef227308d926e71335b530c43c92a8
2,391
gradle-kotlin-sample
Apache License 2.0
src/net/sheltem/aoc/y2015/Day06.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2015 import net.sheltem.common.PositionInt import net.sheltem.aoc.y2015.Action.OFF import net.sheltem.aoc.y2015.Action.ON import net.sheltem.aoc.y2015.Action.TOGGLE import java.lang.Integer.max suspend fun main() { Day06().run() } class Day06 : Day<Int>(998996, 1001996) { override suspend fun part1(input: List<String>): Int = buildLightMap().followInstructions(input.map { it.toInstruction() }).sumOf { row -> row.count { it } } override suspend fun part2(input: List<String>): Int = buildIntLightMap().followIntInstructions(input.map { it.toInstruction() }).sumOf { it.sum() } } private fun String.toInstruction(): Instruction { val (minX, minY, maxX, maxY) = Regex("\\d+").findAll(this).toList().map { it.value.toInt() } return when { startsWith("turn on") -> Instruction(minX to minY, maxX to maxY, ON) startsWith("turn off") -> Instruction(minX to minY, maxX to maxY, OFF) startsWith("toggle") -> Instruction(minX to minY, maxX to maxY, TOGGLE) else -> error("Unknown input") } } private fun Array<BooleanArray>.followInstructions(instructions: List<Instruction>) = apply { instructions.forEach { for (x in it.start.first..it.end.first) { for (y in it.start.second..it.end.second) { this[y][x] = this[y][x].applyAction(it.action) } } } } private fun Array<IntArray>.followIntInstructions(instructions: List<Instruction>) = apply { instructions.forEach {inst -> for (x in inst.start.first..inst.end.first) { for (y in inst.start.second..inst.end.second) { this[y][x] = this[y][x].applyAction(inst.action) } } } } private fun buildIntLightMap(): Array<IntArray> = Array(1000) { IntArray(1000) { 0 } } private fun buildLightMap(): Array<BooleanArray> = Array(1000) { BooleanArray(1000) { false } } private class Instruction(val start: PositionInt, val end: PositionInt, val action: Action) private fun Boolean.applyAction(action: Action) = when (action) { ON -> true OFF -> false TOGGLE -> !this } private fun Int.applyAction(action: Action) = when (action) { ON -> this + 1 OFF -> max(this - 1, 0) TOGGLE -> this + 2 } private enum class Action { ON, OFF, TOGGLE; }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,370
aoc
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day05.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 5 * Problem Description: http://adventofcode.com/2021/day/5 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsText class Day05(override val input: String = resourceAsText("22day05.txt")) : BaseDay<String, String, String> { private val stacks: List<List<String>> private val instructions: List<List<Int>> init { val parts = input.split("\n\n") val tempStacks = parts.first().lines().map { it.chunked(4).map { s -> s.replace("[", "").replace("]", "").trim() }.toMutableList() }.dropLast(1) stacks = (0 until tempStacks.maxOf { it.size }).map { col -> tempStacks.mapNotNull { if (it.getOrNull(col).isNullOrBlank()) null else it[col] } } val tempInstr = parts[1].lines() instructions = tempInstr.map { val line = it.split(" ") listOf(line[1].toInt(), line[3].toInt() - 1, line[5].toInt() - 1) } } override fun solvePart1(): String { val boxes = stacks.map { it.toMutableList() } instructions.forEach { (number, from, to) -> repeat(number) { boxes[to].add(0, boxes[from].removeAt(0)) } } return boxes.joinToString("") { it.first() } } override fun solvePart2(): String { val boxes = stacks.map { it.toMutableList() } instructions.forEach { (number, from, to) -> (number downTo 1).forEach { b -> boxes[to].add(0, boxes[from].removeAt(b - 1)) } } return boxes.joinToString("") { it.first() } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
1,733
advent-of-kotlin
Apache License 2.0
src/Day10.kt
joy32812
573,132,774
false
{"Kotlin": 62766}
fun main() { fun part1(input: List<String>): Int { var x = 1 var cycle = 0 var ans = 0 fun checkCycle() { if ((cycle - 20) % 40 == 0) { ans += cycle * x } } input.forEach { line -> val splits = line.split(" ") val command = splits[0] if (command == "noop") { cycle ++ checkCycle() } else { cycle ++ checkCycle() cycle ++ checkCycle() x += splits[1].toInt() } } return ans } fun part2(input: List<String>): Int { var x = 1 var cycle = 0 val crt = Array(6) { Array(40) { '.' } } fun checkCycle() { val z = cycle - 1 val i = z / 40 val j = z % 40 if (j in (x - 1 .. x + 1)) { crt[i][j] = '#' } } input.forEach { line -> val splits = line.split(" ") val command = splits[0] if (command == "noop") { cycle ++ checkCycle() } else { cycle ++ checkCycle() cycle ++ checkCycle() x += splits[1].toInt() } } crt.forEach { println(it.joinToString("")) } return 0 } println(part1(readInput("data/Day10_test"))) println(part1(readInput("data/Day10"))) println(part2(readInput("data/Day10_test"))) println(part2(readInput("data/Day10"))) }
0
Kotlin
0
0
5e87958ebb415083801b4d03ceb6465f7ae56002
1,670
aoc-2022-in-kotlin
Apache License 2.0
src/Day06.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
fun main() { fun detectMarker(input: String, length: Int): Int { return input.windowed(size=length, step=1) .withIndex() .first { it.value.toSet().size == it.value.length }.index + length } fun part1(input: String): Int { return detectMarker(input, 4) } fun part2(input: String): Int { return detectMarker(input, 14) } // test if implementation meets criteria from the description, like: check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input.first())) println(part2(input.first())) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
1,170
advent-of-code-2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/Djikstra.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* println("Test") val verticeA = Vertice("A") val verticeB = Vertice("B") val verticeC = Vertice("C") val verticeD = Vertice("D") val verticeE = Vertice("E") val verticeF = Vertice("F") val graph = WeightedDirectedGraph( listOf( verticeA, verticeB, verticeC, verticeD, verticeE, verticeF ) ) // https://www.baeldung.com/java-dijkstra: graph.addEdge(verticeA, verticeB, 10) graph.addEdge(verticeA, verticeC, 15) graph.addEdge(verticeB, verticeD, 12) graph.addEdge(verticeB, verticeF, 15) graph.addEdge(verticeC, verticeE, 10) graph.addEdge(verticeD, verticeE, 2) graph.addEdge(verticeD, verticeF, 1) graph.addEdge(verticeF, verticeE, 5) val djikstra = Djikstra() djikstra.shortestPaths(verticeA, graph) djikstra.printMinPath(verticeA, verticeB, graph) djikstra.printMinPath(verticeA, verticeC, graph) djikstra.printMinPath(verticeA, verticeD, graph) djikstra.printMinPath(verticeA, verticeE, graph) djikstra.printMinPath(verticeA, verticeF, graph) data class Vertice( val value: String, var distance: Int = Integer.MAX_VALUE, var prev: Vertice? = null ) { override fun equals(other: Any?): Boolean { val oth = other as? Vertice ?: return false return value == oth.value } override fun hashCode(): Int { return value.hashCode() } } /*: Comparable<Vertice> { override fun compareTo(other: Vertice): Int { return distance - other.distance } } */ data class Edge( val from: Vertice, val to: Vertice, val weight: Int ) data class WeightedDirectedGraph(val vertices: List<Vertice>) { var edges: MutableMap<Vertice, MutableList<Edge>> = mutableMapOf() fun addEdge(from: Vertice, to: Vertice, weight: Int) { val edge = Edge(from, to, weight) val list = edges.getOrDefault(from, mutableListOf()) list.add(edge) edges[from] = list } } class Djikstra() { /* Shortest path with weighted positive edges between start node and all other nodes. 1. construct weighted directed graph with edges 2. set start dist to 0, other to max int/Infinity 3. init min pq (sort by vertice distance) 4. add start vertice to pq 5. while !pq.isEmpty: (E+V) poll min check neighbours: if from.distance + edge weight < to.distance: update to.distance & put in pq (log V) runtime: O((E+V) log V) https://inst.eecs.berkeley.edu/~cs61bl/r//cur/graphs/dijkstra-algorithm-runtime.html?topic=lab24.topic&step=4&course= Using PQ (array: V * V = V^2, heap: V log V + E log V = remove min + remove/add neighbor nodes prio) */ fun shortestPaths(from: Vertice, graph: WeightedDirectedGraph) { graph.vertices.forEach { it.distance = Int.MAX_VALUE } from.distance = 0 val cmp: Comparator<Vertice> = compareBy { it.distance } //val pq = PriorityQueue<Vertice>(11, cmp) val pq = TreeSet<Vertice>(cmp) // Oder treeset für remove/update, IndexedPQ? pq.add(from) while (!pq.isEmpty()) { val min = pq.pollFirst() //pq.poll() // V log V (remove) if (min.distance == Int.MAX_VALUE) continue graph.edges[min]?.forEach { // E log V (insert) val curDist = min.distance + it.weight if (curDist < it.to.distance) { it.to.distance = curDist it.to.prev = min if (pq.contains(it.to)) pq.remove(it.to) pq.add(it.to) } } } } fun printMinPath(from: Vertice, to: Vertice, graph: WeightedDirectedGraph) { val distance = to.distance val stack = Stack<Vertice>() var cur: Vertice? = to while (cur != null) { stack.push(cur) cur = cur.prev } while (!stack.isEmpty()) { println("${stack.pop().value} -> ") } println("Distance: $distance") } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
4,105
KotlinAlgs
MIT License
src/main/aoc2021/Day22.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 class Day22(input: List<String>) { data class Cuboid(val xr: IntRange, val yr: IntRange, val zr: IntRange) { // The ranges are continuous and fairly large, avoid using count() which iterates over the whole range. private fun IntRange.size(): Int = last - first + 1 fun size() = xr.size().toLong() * yr.size() * zr.size() fun isInInitializationArea(): Boolean { return xr.first >= -50 && zr.last <= 50 && yr.first >= -50 && yr.last <= 50 && zr.first >= -50 && zr.last <= 50 } private fun IntRange.overlaps(other: IntRange) = first in other || other.first in this private fun overlaps(other: Cuboid) = xr.overlaps(other.xr) && yr.overlaps(other.yr) && zr.overlaps(other.zr) /** * Subtracting one cuboid from another results in 0-6 smaller cuboids that doesn't cover the subtrahend * * 2D illustration of subtracting a small cuboid from a larger one * +---------+ * | :C: | * | +-+ | In three dimensions there is also a E and F part in front and * | A | | B | behind the subtrahend. Depending on how the subtrahend covers * | +-+ | the minuend any, or all of A-F could be non-existing. * | :D: | * +---------+ * */ fun minus(other: Cuboid): List<Cuboid> { if (!overlaps(other)) { return listOf(this) // No overlap, nothing removed } val ret = mutableListOf<Cuboid>() // Create the A and B cuboids if needed. var xStart = xr.first if (xr.first < other.xr.first) { ret.add(Cuboid(xr.first until other.xr.first, yr, zr)) xStart = other.xr.first } var xEnd = xr.last if (other.xr.last < xr.last) { ret.add(Cuboid(other.xr.last + 1..xr.last, yr, zr)) xEnd = other.xr.last } // Create the C and D cuboids if needed. var yStart = yr.first if (yr.first < other.yr.first) { ret.add(Cuboid(xStart..xEnd, yr.first until other.yr.first, zr)) yStart = other.yr.first } var yEnd = yr.last if (other.yr.last < yr.last) { ret.add(Cuboid(xStart..xEnd, other.yr.last + 1..yr.last, zr)) yEnd = other.yr.last } // Create the E and F cuboids if needed. if (zr.first < other.zr.first) { ret.add(Cuboid(xStart..xEnd, yStart..yEnd, zr.first until other.zr.first)) } if (other.zr.last < zr.last) { ret.add(Cuboid(xStart..xEnd, yStart..yEnd, other.zr.last + 1..zr.last)) } return ret } // Subtract this cuboid from all cuboids in 'subtractFrom' and return the list of remaining cuboids. fun subtractFrom(subtractFrom: List<Cuboid>): List<Cuboid> { return subtractFrom.flatMap { it.minus(this) } } // Creates the union of all cuboids in 'current' (which has no overlapping cuboids) and this cuboid, // which may overlap one or many cuboids in 'current' fun unionWith(current: List<Cuboid>): List<Cuboid> { var toBeAdded = listOf(this) current.filter { it.overlaps(this) } // Take the cuboids in 'current' that overlaps this cuboid, .forEach { cuboidWithOverlap -> // and subtract the overlap from the cuboids that will be added toBeAdded = cuboidWithOverlap.subtractFrom(toBeAdded) } return current + toBeAdded } } sealed class Instruction(val cuboid: Cuboid) { class On(cuboid: Cuboid) : Instruction(cuboid) class Off(cuboid: Cuboid) : Instruction(cuboid) fun isPartOfInitialization() = cuboid.isInInitializationArea() } private fun String.toIntRange() = split("..").let { (a, b) -> a.toInt()..b.toInt() } val steps = input.map { line -> val parts = line.split(",").map { it.substringAfter("=").toIntRange() } when (line[1]) { // second letter of the line 'n' -> Instruction.On(Cuboid(parts[0], parts[1], parts[2])) else -> Instruction.Off(Cuboid(parts[0], parts[1], parts[2])) } } private fun solve(instructions: List<Instruction>): Long { var currentlyOn = listOf<Cuboid>() instructions.forEach { currentlyOn = when (it) { is Instruction.On -> it.cuboid.unionWith(currentlyOn) is Instruction.Off -> it.cuboid.subtractFrom(currentlyOn) } } return currentlyOn.sumOf { it.size() } } fun solvePart1(): Long { return solve(steps.filter { it.isPartOfInitialization() }) } fun solvePart2(): Long { return solve(steps) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
5,039
aoc
MIT License
src/main/kotlin/abc/187-e.kt
kirimin
197,707,422
false
null
package abc import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val ab = (0 until n - 1).map { sc.next().toInt() to sc.next().toInt() } val q = sc.nextInt() val tex = (0 until q).map { Triple(sc.next().toInt(), sc.next().toInt(), sc.next().toLong()) } println(problem187e(n, ab, q, tex)) } fun problem187e(n: Int, ab: List<Pair<Int, Int>>, q: Int, tex: List<Triple<Int, Int, Long>>): String { val root = ab[0].first val tree = Array(n + 1) { mutableListOf<Int>() } for (i in 0 until n - 1) { val (a, b) = ab[i] tree[a].add(b) tree[b].add(a) } val queue = ArrayDeque<Int>() queue.offer(root) val distances = IntArray(n + 1) { -1 } distances[root] = 0 while(!queue.isEmpty()) { val current = queue.poll() for (j in 0 until tree[current].size) { val next = tree[current][j] if (distances[next] != -1) continue distances[next] = distances[current] + 1 queue.offer(next) } } val treeNums = Array(n + 1) { 0L } for (i in 0 until q) { val (ti, ei, xi) = tex[i] val (a, b) = ab[ei - 1] if (distances[a] > distances[b]) { if (ti == 2) { treeNums[root] += xi treeNums[a] -= xi } else { treeNums[a] += xi } } else { if (ti == 1) { treeNums[root] += xi treeNums[b] -= xi } else { treeNums[b] += xi } } } val ansTree = Array(n + 1) { 0L } val deque = ArrayDeque<Int>() deque.offer(root) ansTree[root] = treeNums[root] while (deque.isNotEmpty()) { val current = deque.poll() for (i in 0 until tree[current].size) { val next = tree[current][i] if (distances[next] > distances[current]) { ansTree[next] += ansTree[current] + treeNums[next] deque.offer(next) } } } return ansTree.drop(1).joinToString("\n") }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
2,147
AtCoderLog
The Unlicense
src/MergeTwoLinkedLists.kt
max-f
221,919,191
false
{"Python": 13459, "Kotlin": 8011}
import common.ListNode /** * https://leetcode.com/problems/merge-two-sorted-lists/ * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } * * Example: 1 -> 2 -> 4, 1 -> 3 -> 4 * Result: 1-> 1 -> 2 -> 3 -> 4 -> 4 */ fun main() { val nodeA1 = ListNode(1) val nodeA2 = ListNode(2) val nodeA4 = ListNode(4) val nodeB1 = ListNode(1) val nodeB3 = ListNode(3) val nodeB4 = ListNode(4) nodeA1.next = nodeA2 nodeA2.next = nodeA4 nodeB1.next = nodeB3 nodeB3.next = nodeB4 val m: MergeTwoLinkedLists = MergeTwoLinkedLists() var head = m.mergeTwoLists(nodeA1, nodeB1) while (head != null) { println(head.value) head = head.next } } class MergeTwoLinkedLists { fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? { var head: ListNode? = null var pointer1 = l1 var pointer2 = l2 // 1->3->4, 2 var before: ListNode? = null while (pointer1 != null || pointer2 != null) { if (pointer1 != null && pointer2 == null) { // List 2 no elements anymore if (before != null) { before.next = pointer1 } else { head = pointer1 } before = pointer1 } else if (pointer1 == null && pointer2 != null) { // List 1 no elements anymore if (before != null) { before.next = pointer2 } else { head = pointer2 } before = pointer2 pointer2 = pointer2.next } else if (pointer1 != null && pointer2 != null) { // Compare pointers of both lists var smallerPointer: ListNode? if (pointer1.value <= pointer2.value) { smallerPointer = pointer1 pointer1 = pointer1.next } else { smallerPointer = pointer2 pointer2 = pointer2.next } if (before != null) { before.next = smallerPointer } else { head = smallerPointer } before = smallerPointer } } return head } }
0
Python
0
0
3fc1888484531a1a23b880f9875614e56f846564
2,457
leetcode
MIT License
kotlin/1020-number-of-enclaves.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun numEnclaves(grid: Array<IntArray>): Int { val rows = grid.size val cols = grid[0].size val dirs = arrayOf( intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1) ) val visited = Array(rows){BooleanArray(cols)} fun isValid(r: Int, c: Int) = r in (0 until rows) && c in (0 until cols) && visited[r][c] == false && grid[r][c] == 1 fun isValidBorder(r: Int, c: Int) = (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) && visited[r][c] == false fun dfs(r: Int, c: Int): Int { if (!isValid(r, c)) return 0 visited[r][c] = true var res = 1 for ((dr, dc) in dirs) { res += dfs(r + dr, c + dc) } return res } var totalLand = 0 var borderLand = 0 for (r in 0 until rows) { for (c in 0 until cols) { totalLand += grid[r][c] if (grid[r][c] == 1 && isValidBorder(r, c)) { borderLand += dfs(r, c) } } } return totalLand - borderLand } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,329
leetcode
MIT License
src/main/kotlin/cn/awpaas/learn/day02/Learn-5.kt
afterloe
135,126,786
false
{"Kotlin": 28646}
package cn.awpaas.learn.day02 /** * 过滤是最常进行的操作,那么列举下可能用到的几种常规 过滤操作函数 */ fun toStr(list: List<Any>): String = list.reduce { total, any -> total.toString() + any.toString() }.toString() fun main(args: Array<String>) { var list = mutableListOf<Any>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // 获取前几个元素 println("the 3 first element of collections -> ${toStr(list.take(3))}") var list1 = mutableListOf(1,2,3,4,5,6,7,8,9,10) // 条件获取 val chars = (1..10).toList() println(chars.take(3)) // 1,2,3 println(chars.takeWhile { it%2 == 0 }) // 2,4,6,8,10 println(chars.takeLast(2)) // 9,10 println(chars.takeLastWhile { it > 7 }) // 7,8,9,10 // println("the even number collections -> ${toString(list1.takeWhile { any -> any % 2 == 0})}") var list2 = mutableListOf(1,2,3,4,5,6) var list3 = mutableListOf("a", "b", "c", "d") // [(1, a), (2, b), (3, c), (4, d)] var info = list2.zip(list3) // 将两个集合按照下标进行匹配,并返回,如果两个集合长度不一致,按照短的集合长度 // var listPair = mutableListOf(Pair(1,2), Pair(3,4), Pair(5,6), Pair(7,8)) println(info) println(info.get(1)) println(info.unzip()) // 也可以进行格式的转换和处理 println(list3.zip(list2) { t1, t2 -> t1 + t2}) // 按照条件进行拆分 println(list1.partition { it > 5 }) // add all 相当于 println(list1.plus(list2)) }
0
Kotlin
1
3
e747b4d2b331aa92d97bd8a514d53c9f3c59af6e
1,512
learn-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortingSentence.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.TreeMap /** * 1859. Sorting the Sentence * https://leetcode.com/problems/sorting-the-sentence/ */ fun sortSentenceTree(s: String): String { val map = TreeMap<Int, String>() val str = s.split(" ").toTypedArray() for (st in str) { val len = st.length - 1 val number = Character.getNumericValue(st[len]) val snew = StringBuilder() snew.append(st) snew.replace(len, len + 1, " ") val string = snew.toString() map[number] = string } val string = StringBuilder() for (n in map.keys) { string.append(map[n]) } val i = string.length string.deleteCharAt(i - 1) return string.toString() } fun sortSentence(s: String): String { val list = ArrayList<String>() val sb = StringBuilder() for (c in s.toCharArray()) { if (c != ' ') { sb.append(c) } else { list.add(sb.toString()) sb.setLength(0) } } list.add(sb.toString()) sb.setLength(0) val temp = arrayOfNulls<String>(list.size) for (str in list) { temp[str[str.length - 1] - '0' - 1] = str.substring(0, str.length - 1) } for (str in temp) { sb.append(str) sb.append(' ') } sb.deleteCharAt(sb.length - 1) return sb.toString() }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,970
kotlab
Apache License 2.0
src/Day06.kt
meierjan
572,860,548
false
{"Kotlin": 20066}
import java.util.* private class BufferScanner( val bufferSize: Int = 4 ) { private val queue: ArrayDeque<Char> = ArrayDeque(bufferSize) fun read(char: Char) { queue.addFirst(char) if(queue.size > bufferSize) { queue.removeLast() } } fun scanUniqueness() : Boolean = queue.toSet().size == bufferSize } private fun BufferScanner.scanTextForUniqueSequence(input: String) : Int { for((index, char) in input.toList().withIndex()) { this.read(char) if(this.scanUniqueness()) { return index + 1 } } return -1; } fun day6_part1(input: String): Int = BufferScanner(4).scanTextForUniqueSequence(input) fun day6_part2(input: String): Int = BufferScanner(14).scanTextForUniqueSequence(input) fun main() { val input = readInput("Day06_1").first() // task 1 check(day6_part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(day6_part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(day6_part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(day6_part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) println(day6_part1(input)) // task 2 check(day6_part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(day6_part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(day6_part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(day6_part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(day6_part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) println(day6_part2(input)) }
0
Kotlin
0
0
a7e52209da6427bce8770cc7f458e8ee9548cc14
1,507
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/y2023/day07/Day07.kt
niedrist
726,105,019
false
{"Kotlin": 19919}
package y2023.day07 import BasicDay import util.FileReader val players = FileReader.asStrings("2023/day07.txt").map { val (hand, bid) = it.split(' ') Player(hand.toCharArray().toList(), bid.toInt()) } fun main() = Day07.run() object Day07 : BasicDay() { override fun part1() = solve(false) override fun part2() = solve(true) private fun solve(withJoker: Boolean) = players .sortedWith(compareBy<Player> { it.getType(withJoker) } .thenBy { mapCard(it.hand[0], withJoker) } .thenBy { mapCard(it.hand[1], withJoker) } .thenBy { mapCard(it.hand[2], withJoker) } .thenBy { mapCard(it.hand[3], withJoker) } .thenBy { mapCard(it.hand[4], withJoker) } ) .foldIndexed(0L) { index, acc, player -> acc + ((index + 1) * player.bid) } } fun mapCard(c: Char, withJoker: Boolean): Int { return when (c) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> if (withJoker) 1 else 11 'T' -> 10 else -> c.digitToInt() } }
0
Kotlin
0
1
37e38176d0ee52bef05f093b73b74e47b9011e24
1,076
advent-of-code
Apache License 2.0
src/main/kotlin/days/Day8.kt
tpepper0408
317,612,203
false
null
package days class Day8 : Day<Int>(8) { override fun partOne(): Int { return run(parseInstructions()).first } override fun partTwo(): Int { val instructions = parseInstructions() //if not do some swapping. val interestingIndexes = instructions.mapIndexed { index, instruction -> index to instruction } .filter { (_, instruction) -> instruction.first == "nop" || instruction.first == "jmp" } .map { (index, _) -> index } for (index in interestingIndexes) { val instructionArray = instructions.toTypedArray() instructionArray[index] = when(instructionArray[index].first) { "nop" -> "jmp" to instructionArray[index].second else -> "nop" to instructionArray[index].second } val (accumulated, completed) = run(instructionArray.toList()) if (completed) return accumulated } return 0 } private fun parseInstructions(): List<Pair<String, Int>> { return inputList.map { it.split(" ")[0] to it.split(" ")[1].toInt() } } private fun run(programme: List<Pair<String, Int>>): Pair<Int, Boolean> { val seen = HashSet<Int>() var index = 0 var accumulated = 0 while (index < programme.size) { if (seen.contains(index)) { return Pair(accumulated, false) } else { seen.add(index) } when (programme[index].first) { "nop" -> index++ "acc" -> { accumulated += programme[index].second index++ } "jmp" -> index += programme[index].second } } return Pair(accumulated, true) } }
0
Kotlin
0
0
67c65a9e93e85eeb56b57d2588844e43241d9319
1,846
aoc2020
Creative Commons Zero v1.0 Universal
src/questions/IntegerToRoman.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBe import java.util.* /** * Given an integer, convert it to a roman numeral. * * [Source](https://leetcode.com/problems/integer-to-roman/) */ @UseCommentAsDocumentation private object IntToRoman { private val conversionRules = TreeMap<Int, String>() // important that it is a TreeMap init { // define all conversion rules listOf( 1 to "I", 5 to "V", 10 to "X", 50 to "L", 100 to "C", 500 to "D", 1000 to "M" ).forEach { conversionRules[it.first] = it.second } // define the subtraction rules // // * I can be placed before V (5) and X (10) to make 4 and 9. // * X can be placed before L (50) and C (100) to make 40 and 90. // * C can be placed before D (500) and M (1000) to make 400 and 900. conversionRules[4] = "IV" conversionRules[9] = "IX" conversionRules[40] = "XL" conversionRules[90] = "XC" conversionRules[400] = "CD" conversionRules[900] = "CM" } fun intToRoman(num: Int): String { return _intToRoman(num, "") } private fun _intToRoman(num: Int, result: String): String { if (num == 0) return result // exit case; weird how Romans didn't have the concept of ZERO val lowerKey = findPreviousLowest(num) // find the previous lowest and... val remaining = num - lowerKey // subtract it from num to get the remaining val currentValue = result + conversionRules[lowerKey] // find the translation return _intToRoman(remaining, currentValue) // recurse till it hits the zero } private fun findPreviousLowest(num: Int): Int { if (conversionRules.containsKey(num)) return num // match found return conversionRules.lowerKey(num)!! // since conversionRules is a TreeMap, find the lower match using its method } } fun main() { IntToRoman.intToRoman(3) shouldBe "III" IntToRoman.intToRoman(4) shouldBe "IV" IntToRoman.intToRoman(5) shouldBe "V" IntToRoman.intToRoman(58) shouldBe "LVIII" IntToRoman.intToRoman(1994) shouldBe "MCMXCIV" }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,362
algorithms
MIT License
src/Day01.kt
dominik003
573,083,805
false
{"Kotlin": 9376}
import java.util.* fun main() { fun part1(input: List<String>): Int { var maxVal: Int = Int.MIN_VALUE var cur = 0 input.forEach { if (it == "") { maxVal = if (cur > maxVal) cur else maxVal cur = 0 } else { cur += Integer.parseInt(it) } } return maxVal } fun part2(input: List<String>): Int { val calories = PriorityQueue<Int>() var cur = 0 input.forEach { if (it == "") { calories.add(cur) cur = 0 if (calories.size > 3) { calories.poll() } } else { cur += Integer.parseInt(it) } } return calories.sumOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput(1, true) (testInput as MutableList<String>).add("") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput(1) (input as MutableList<String>).add("") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b64d1d4c96c3dd95235f604807030970a3f52bfa
1,195
advent-of-code-2022
Apache License 2.0
app/src/main/java/com/tripletres/platformscience/domain/algorithm/BranchAndBoundAlgorithm.kt
daniel553
540,959,283
false
{"Kotlin": 95616}
package com.tripletres.platformscience.domain.algorithm import com.tripletres.platformscience.domain.ShipmentDriverAssignation.SuitabilityScore import com.tripletres.platformscience.domain.algorithm.BranchAndBoundAlgorithm.Node import com.tripletres.platformscience.domain.model.Driver import com.tripletres.platformscience.domain.model.Shipment /** * Branch and bound algorithm. Approximation to solve the Assignation problem * * Algorithm execution: * 1. From given matrix of suitability score (between drivers and shipments) * 2. Create a priority queue * 3. Create a root [Node] node dummy and add it to priority queue * 4. Loop until priority queue is empty OR Last Driver has been reached, do: * 4.1 Get lowest ss value node * 4.2 Loop for each driver, do: * 4.3 If unassigned node then * 4.4 Add to the queue -> unassigned nodes ([Node] child) with the path ss and calculate * total ss (see getLowestSSAfterDriverAssignedShipment) and the "path of ss". * 5. Create a list of drivers to return result * * Routine getLowestSSAfterDriverAssignedShipment: * 1. Create a queue of available shipments * 2. Loop for each driver (next one) do: * 2.1. Loop for each shipment do: * 2.1.1 Get the minimum ss when node is not assigned and it's available * 2.2 Accumulate the minimum ss and add to queue the minimum shipment * 3. Return the total minimum cost * * References: * https://www.geeksforgeeks.org/branch-and-bound-algorithm/ * https://tutorialspoint.dev/algorithm/branch-and-bound-algorithm/branch-bound-set-4-job-assignment-problem */ class BranchAndBoundAlgorithm : IAssignationAlgorithm { private var n = 0 override fun getBestMatching(input: MutableList<MutableList<SuitabilityScore>>): List<Driver> { return execute(matrix = prepareInput(input)) } private fun execute(matrix: MutableList<MutableList<SuitabilityScore>>): List<Driver> { //Priority queue for nodes that are "live" val priorityQueue = mutableListOf<Node>() // Initialize nodes with root of search (dummy) val assigned = mutableListOf<Shipment>() val root = Node.dummy() var minOut = root priorityQueue.add(root) //Continue until priority queue has nodes while (priorityQueue.isNotEmpty()) { //Find a node with lowest ss val min = priorityQueue.minByOrNull { it.ss } ?: priorityQueue[0] minOut = min //And remove it from the queue priorityQueue.remove(min) //Get next driver index val i = min.driverIndex + 1 // Start point = 0 //Stop condition: if last driver is reached if (i == n) { return getBuildNodes(min) } else { //For each shipment find unassigned shipments matrix[i].forEachIndexed { j, it -> //If unassigned if (!min.assigned.contains(it.shipment)) { val child = Node.newNode( driver = matrix[i][j].driver, driverIndex = i, // should have here? shipment = matrix[i][j].shipment, assigned = assigned.toMutableList(), parent = min ) //Cost for ancestor nodes including current node child.pathSS = min.pathSS + matrix[i][j].ss //Calculate lower ss (that includes the path ss) child.ss = child.pathSS + getLowestSSAfterDriverAssignedShipment(matrix, i, child.assigned) child.driverIndex = i //Add child node to queue priorityQueue.add(child) } } } } return getBuildNodes(minOut) } private fun getLowestSSAfterDriverAssignedShipment( matrix: MutableList<MutableList<SuitabilityScore>>, driver: Int, assigned: MutableList<Shipment> ): Float { var cost = 0f; //Store available shipment val available = matrix[driver].associate { it.shipment to true } .toMutableMap()//mutableMapOf<Shipment, Boolean>() //Start new driver for (i in driver.plus(1)..n.minus(1)) { var min = Float.MAX_VALUE var minShipment: Shipment? = null //Do for each shipment matrix[i].forEachIndexed { j, it -> //If shipment is unassigned if (!assigned.contains(it.shipment) && available.contains(it.shipment) && it.ss < min ) { //Store shipment number minShipment = matrix[i][j].shipment //Store cost min = matrix[i][j].ss } } // Add cost of next driver cost += min minShipment?.let { sh -> available.remove(sh) } } //Return total cost return cost } /** * Build result from [Node] node * @return List of [Driver] drivers with assigned [Shipment] */ private fun getBuildNodes(min: Node): List<Driver> { val driverList = mutableListOf<Driver>() var aux: Node? = min do { aux?.let { driverList.add(it.driver.copy( shipment = it.shipment, ss = it.driver.ss )) aux = it.parent } if (aux?.parent == null) aux = null //Do not include root } while (aux != null) return driverList.toList() } /** * Auxiliary node class */ data class Node( var parent: Node? = null, var pathSS: Float = 0f, var ss: Float = 0f, var driver: Driver, var driverIndex: Int = 0, var shipment: Shipment, var assigned: MutableList<Shipment> = mutableListOf(), ) { companion object { fun newNode( driver: Driver, driverIndex: Int, shipment: Shipment, assigned: MutableList<Shipment> = mutableListOf(), parent: Node? = null, ): Node { val node = Node( driver = driver, shipment = shipment, assigned = assigned, parent = parent, driverIndex = driverIndex ) node.assigned.add(shipment) return node } fun dummy() = newNode( Driver(0, "DUMMY", null, null), -1, Shipment(0, "")) } } /** * Simple preparation driver x, shipment y */ private fun prepareInput(input: MutableList<MutableList<SuitabilityScore>>): MutableList<MutableList<SuitabilityScore>> { //Drivers must be x, shipments must be y //must be squared nxn n = input.size return if (n > 1 && input[0][0].driver != input[1][0].driver) { input // drivers in x } else { //Need to traspose :/ val dummy = input[0][0].copy() val transpose = MutableList(n) { MutableList(n) { dummy } } println("-------INPUT--------") for (i in 0 until n) { for (j in 0 until n) { transpose[j][i] = input[i][j] print(transpose[i][j].ss) print("f,") } println() } transpose } } }
0
Kotlin
0
0
2ea5962dc0ad349ae97b277ab4ecf9e9a0aee1e6
7,871
PlatformScience
FSF All Permissive License
kotlin/yacht/src/main/kotlin/Yacht.kt
ErikSchierboom
27,632,754
false
{"C++": 14523188, "C": 1712536, "C#": 843402, "JavaScript": 766003, "Java": 570202, "F#": 559855, "Elixir": 504471, "Haskell": 499200, "Shell": 393291, "TypeScript": 381035, "Kotlin": 326721, "Scala": 321830, "Clojure": 303772, "Nim": 283613, "Ruby": 233410, "Elm": 157678, "Crystal": 155384, "Go": 152557, "Gleam": 150059, "Zig": 139897, "Python": 115799, "Makefile": 105638, "COBOL": 86064, "Prolog": 80765, "D": 66683, "CoffeeScript": 66377, "Scheme": 63956, "CMake": 62581, "Visual Basic .NET": 57136, "Rust": 54763, "Julia": 49727, "R": 43757, "Swift": 42546, "WebAssembly": 29203, "Wren": 27102, "Ballerina": 26773, "Fortran": 10325, "PowerShell": 4747, "OCaml": 4629, "Awk": 4125, "Tcl": 2927, "PLSQL": 2402, "Roff": 2089, "Lua": 1038, "Common Lisp": 915, "Assembly": 753, "Reason": 215, "jq": 37, "JSONiq": 16}
object Yacht { fun solve(category: YachtCategory, vararg dices: Int) = when(category) { YachtCategory.ONES -> dices.digitScore(1) YachtCategory.TWOS -> dices.digitScore(2) YachtCategory.THREES -> dices.digitScore(3) YachtCategory.FOURS -> dices.digitScore(4) YachtCategory.FIVES -> dices.digitScore(5) YachtCategory.SIXES -> dices.digitScore(6) YachtCategory.FULL_HOUSE -> dices.fullHouseScore() YachtCategory.FOUR_OF_A_KIND -> dices.fourOfAKindScore() YachtCategory.LITTLE_STRAIGHT -> dices.littleStraightScore() YachtCategory.BIG_STRAIGHT -> dices.bigStraightScore() YachtCategory.YACHT -> dices.yachtScore() YachtCategory.CHOICE -> dices.choiceScore() } private fun IntArray.digitScore(digit: Int) = count { it == digit } * digit private fun IntArray.fullHouseScore() = diceByCount().let { if (2 in it && 3 in it) sum() else 0 } private fun IntArray.fourOfAKindScore() = diceByCount().let { (it[4] ?: it[5] ?: 0) * 4 } private fun IntArray.littleStraightScore() = if (straight() && 6 !in this) 30 else 0 private fun IntArray.bigStraightScore() = if (straight() && 1 !in this) 30 else 0 private fun IntArray.yachtScore() = if (distinct().size == 1) 50 else 0 private fun IntArray.choiceScore() = sum() private fun IntArray.straight() = distinct().size == 5 private fun IntArray.diceByCount() = groupBy { it }.map { it.value.size to it.key }.toMap() }
0
C++
10
29
d84c9d48a2d3adb0c37d7bd93c9a759d172bdd8e
1,495
exercism
Apache License 2.0
src/Day17.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
import kotlin.math.max private const val ROCK_COUNT = 2022 private const val FIELD_WIDTH = 7 private const val ITERATION_COUNT_FOR_PART2 = 1000000000000 fun main() { val testInput = readLine("Day17_test") val testSimulation = RockSimulation(testInput) check(testSimulation.simulate(ROCK_COUNT) == 3068) check(testSimulation.getPart2Result(ITERATION_COUNT_FOR_PART2) == 1514285714288) val input = readLine("Day17") val simulation = RockSimulation(input) println(simulation.simulate(ROCK_COUNT)) println(simulation.getPart2Result(ITERATION_COUNT_FOR_PART2)) } private val ROCKS: List<List<Coords>> = listOf( listOf(Coords(2, 0), Coords(3, 0), Coords(4, 0), Coords(5, 0)), listOf(Coords(3, 0), Coords(2, 1), Coords(3, 1), Coords(4, 1), Coords(3, 2)), listOf(Coords(2, 0), Coords(3, 0), Coords(4, 0), Coords(4, 1), Coords(4, 2)), listOf(Coords(2, 0), Coords(2, 1), Coords(2, 2), Coords(2, 3)), listOf(Coords(2, 0), Coords(3, 0), Coords(2, 1), Coords(3, 1)) ) private class RockSimulation(val windString: String) { private val field: Array<Array<Boolean>> = Array(ROCK_COUNT * 4) { Array(FIELD_WIDTH) { false } } private var maxHeight: Int = -1 private var windCount: Int = 0 // Data for part2 private val rockTypeWindHeightMap = mutableMapOf<Pair<Int, Int>, Int>() private val rockTypeWindRockMap = mutableMapOf<Pair<Int, Int>, Int>() private val rockHeightArray: Array<Int> = Array(ROCK_COUNT) { 0 } private var lastRockDiff = 0 private var lastHeightDiff = 0 private var lastRockNum = 0 private var lastMaxHeight = 0 fun simulate(count: Int): Int { for (i in 0 until count) { simulateOneRock(i % ROCKS.size) val pair = Pair(windCount, i % ROCKS.size) val height: Int? = rockTypeWindHeightMap[pair] val rockNum: Int? = rockTypeWindRockMap[pair] if (height != null && rockNum != null) { lastRockDiff = i - rockNum lastHeightDiff = maxHeight - height lastRockNum = i lastMaxHeight = maxHeight } rockTypeWindHeightMap[pair] = maxHeight rockTypeWindRockMap[pair] = i rockHeightArray[i] = maxHeight } return maxHeight + 1 } fun getPart2Result(iterationCount: Long): Long { val diff = iterationCount - 1L - lastRockNum val cyclesCount: Long = diff / lastRockDiff val cyclesLast = diff % lastRockDiff val heightLast = rockHeightArray[lastRockNum - lastRockDiff + cyclesLast.toInt()] - rockHeightArray[lastRockNum - lastRockDiff] return lastMaxHeight.toLong() + cyclesCount * lastHeightDiff + heightLast.toLong() + 1 } private fun simulateOneRock(rockNumber: Int) { var rockPosition: List<Coords> = ROCKS[rockNumber] .map { Coords(it.x, it.y + maxHeight + 4) } var movedDown = true while (movedDown) { val windDirection: Int = getWindDirection() var newPosition = rockPosition .map { Coords(it.x + windDirection, it.y) } if (isPositionAfterWindCorrect(newPosition)) rockPosition = newPosition newPosition = rockPosition .map { Coords(it.x, it.y - 1) } movedDown = isPositionAfterDescendCorrect(newPosition) if (movedDown) rockPosition = newPosition else { maxHeight = max(maxHeight, rockPosition.maxOf { it.y } ) rockPosition.forEach { field[it.y][it.x] = true } } } } private fun printField() { field.filter { it.any { v -> v } } .reversed() .forEach { print('|') it.forEach { v -> if (v) print('#') else print('.') } println('|') } println("---------") println() } private fun isPositionAfterWindCorrect(newPosition: List<Coords>): Boolean { return newPosition.all { it.x in 0 until FIELD_WIDTH && !field[it.y][it.x] } } private fun isPositionAfterDescendCorrect(newPosition: List<Coords>): Boolean { return newPosition.all { it.y >= 0 && !field[it.y][it.x] } } private fun getWindDirection(): Int { val result = if (windString[windCount] == '<') -1 else 1 windCount++ if (windCount == windString.length) windCount = 0 return result } }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
4,640
AdventOfCode2022
Apache License 2.0
src/main/kotlin/day20.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import kotlin.random.Random fun day20 (lines: List<String>) { val connections = parseConnections(lines) val modules = parseModules(lines, connections) var lowPulses = 0L var highPulses = 0L val rxSource = connections.find { it.second == "rx" }!!.first val rxSourceSources = connections.filter { it.second == rxSource }.map { it.first } val rxSourceSourcesCycles = mutableMapOf<String, Int>() rxSourceSources.forEach { rxSourceSourcesCycles[it] = 0 } for (i in 1..5000) { val pulses = mutableListOf<Pulse>() pulses.add(Pulse("broadcaster", Signal.LOW)) lowPulses++ while (pulses.isNotEmpty()) { val nextPulse = pulses.first() pulses.remove(nextPulse) connections.filter { it.first == nextPulse.source }.forEach { connection -> if (nextPulse.signal == Signal.LOW) { lowPulses++ } else { highPulses++ } if (modules.containsKey(connection.second)) { val module = modules[connection.second]!! val result = module.receivePulse(nextPulse.signal, nextPulse.source) if (result != null) { pulses.add(Pulse(connection.second, result)) if (rxSourceSources.contains(connection.second) && result == Signal.HIGH) { rxSourceSourcesCycles[connection.second] = i } } } } } if (i == 1000) { println("Day 20 part 1: ${lowPulses * highPulses}") } if (rxSourceSourcesCycles.values.count { it > 0 } == rxSourceSourcesCycles.size) { break } } val fewestButtonPresses = rxSourceSourcesCycles.values.fold(1L) { acc, it -> acc * it } println("Day 20 part 2: $fewestButtonPresses") println() } fun parseConnections(lines: List<String>): List<Pair<String, String>> { val connections = mutableListOf<Pair<String, String>>() lines.map { it.replace(" ", "").replace("%", "").replace("&", "") }.forEach { line -> val from = line.split("->")[0] val to = line.split("->")[1].split(",") to.forEach { connections.add(Pair(from, it)) } } return connections } fun parseModules(lines: List<String>, connections: List<Pair<String, String>>): Map<String, Module> { val modules = mutableMapOf<String, Module>() lines.map { it.replace(" ", "") }.forEach { line -> val name = line.split("->")[0] if (name.startsWith("%")) { modules[name.removePrefix("%")] = FlipFlopModule() } else if (name.startsWith("&")) { val inputs = connections.filter { it.second == name.removePrefix("&") } modules[name.removePrefix("&")] = ConjunctionModule(inputs.map { it.first }) } else { modules[name] = BroadcasterModule() } } modules["output"] = OutputModule() return modules } interface Module { fun receivePulse(signal: Signal, source: String): Signal? } enum class Signal { LOW, HIGH } data class Pulse(val source: String, val signal: Signal) class FlipFlopModule : Module { private var on = false override fun receivePulse(signal: Signal, source: String): Signal? { if (signal == Signal.LOW) { on = !on return if (on) { Signal.HIGH } else { Signal.LOW } } return null } } class ConjunctionModule(inputs: List<String>) : Module { private val recentPulses = mutableMapOf<String, Signal>() init { inputs.forEach { recentPulses[it] = Signal.LOW } } override fun receivePulse(signal: Signal, source: String): Signal { recentPulses[source] = signal return if (recentPulses.values.all { it == Signal.HIGH }) { Signal.LOW } else { Signal.HIGH } } } class BroadcasterModule : Module { override fun receivePulse(signal: Signal, source: String): Signal { return signal } } class OutputModule : Module { override fun receivePulse(signal: Signal, source: String): Signal? { return null } }
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
4,397
advent_of_code_2023
MIT License
exercises/src/main/kotlin/solutions/chapter2/Solution.kt
rmolinamir
705,132,794
false
{"Kotlin": 690308, "HTML": 34654, "CSS": 1900, "Shell": 593}
package solutions.chapter2 // Exercise 2.1: Chain Functions typealias FUN<A, B> = (A) -> B infix fun <A, B, C> FUN<A, B>.andThen(c: FUN<B, C>): FUN<A, C> = fun(a: A): C { val b = this return c(b(a)) } // Exercise 2.2: A Functional Stack data class FunStack<T>(private val elements: List<T> = emptyList()) { fun push(aValue: T): FunStack<T> = FunStack(elements.plus(listOf(aValue))) fun pop(): Pair<T, FunStack<T>> = Pair(elements.last(), FunStack(elements.dropLast(1))) fun size(): Int = elements.size } // Exercise 2.3: An RPN Calculator fun calcRpn(exp: String): Double { fun isNumeric(str: String): Boolean { return str.toDoubleOrNull() != null } fun performOperation(operator: String, i: Double, j: Double): Double { return when (operator) { "+" -> j + i "*" -> j * i "-" -> j - i "/" -> j / i else -> throw IllegalArgumentException("Invalid operator: $operator") } } fun operation(stack: FunStack<Double>, current: String): FunStack<Double> { return if (isNumeric(current)) { stack.push(current.toDouble()) } else { val (i, tmpStack1) = stack.pop() val (j, tmpStack2) = tmpStack1.pop() tmpStack2.push(performOperation(current, i, j)) } } return exp.split(" ").fold(FunStack(), ::operation).pop().first }
0
Kotlin
0
0
ccfed75476263e780c5a8c61e02178532cc9f3f4
1,423
fotf
MIT License
src/main/kotlin/no/nav/helsearbeidsgiver/domene/inntektsmelding/v1/BestemmendeFravaersdag.kt
navikt
692,072,545
false
{"Kotlin": 64915}
package no.nav.helsearbeidsgiver.domene.inntektsmelding.v1 import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.ChronoUnit fun bestemmendeFravaersdag( arbeidsgiverperioder: List<Periode>, egenmeldingsperioder: List<Periode>, sykmeldingsperioder: List<Periode>, ): LocalDate { val sisteArbeidsgiverperiode = arbeidsgiverperioder .slaaSammenSammenhengendePerioder { denne, neste -> denne.tom.daysUntil(neste.fom) <= 1 } .lastOrNull() val sisteSykdomsperiode = (egenmeldingsperioder + sykmeldingsperioder) .slaaSammenSammenhengendePerioder( kanSlaasSammen = ::kanSlaasSammenIgnorerHelgegap, ) .fjernPerioderEtterFoersteUtoverAgp() .last() return if (sisteArbeidsgiverperiode != null) { maxOf( sisteArbeidsgiverperiode.fom, sisteSykdomsperiode.fom, ) } else { sisteSykdomsperiode.fom } } private fun List<Periode>.slaaSammenSammenhengendePerioder( kanSlaasSammen: (Periode, Periode) -> Boolean, ): List<Periode> = sortedBy { it.fom } .fold(emptyList()) { slaattSammen, periode -> val forrige = slaattSammen.lastOrNull() if (forrige != null && kanSlaasSammen(forrige, periode)) { val sammenhengende = Periode( fom = forrige.fom, tom = maxOf(forrige.tom, periode.tom), ) slaattSammen.dropLast(1).plus(sammenhengende) } else { slaattSammen.plus(periode) } } private fun List<Periode>.fjernPerioderEtterFoersteUtoverAgp(): List<Periode> = filterIndexed { index, _ -> val antallForegaaendeDager = slice(0..<index) .sumOf { it.fom.daysUntil(it.tom) + 1 } antallForegaaendeDager <= 16 } private fun kanSlaasSammenIgnorerHelgegap(denne: Periode, neste: Periode): Boolean { val dagerAvstand = denne.tom.daysUntil(neste.fom) return when (denne.tom.dayOfWeek) { DayOfWeek.FRIDAY -> dagerAvstand <= 3 DayOfWeek.SATURDAY -> dagerAvstand <= 2 else -> dagerAvstand <= 1 } } private fun LocalDate.daysUntil(other: LocalDate): Int = until(other, ChronoUnit.DAYS).toInt()
1
Kotlin
0
0
57eaaf90ff48a4a5936203bf365e5c56bbb3fb48
2,328
hag-domene-inntektsmelding
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/TwoSumSorted.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.arrays /** * Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, * find two numbers such that they add up to a specific target number. * * Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length. * * Return the indices of the two numbers, index1 and index2, * added by one as an integer array [index1, index2] of length 2. * * The tests are generated such that there is exactly one solution. * You may not use the same element twice. * * Your solution must use only constant extra space. * * Input: numbers = [2,7,11,15], target = 9 * Output: [1,2] * Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. */ // O(n) time | O(1) space fun twoSumSorted(numbers: IntArray, target: Int): IntArray { var low = 0 var high = numbers.size - 1 while (low < high) { val potentialSum = numbers[low] + numbers[high] when { potentialSum < target -> low++ potentialSum > target -> high-- else -> return intArrayOf(low + 1, high + 1) } } return intArrayOf() }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,223
algs4-leprosorium
MIT License
bowlingkata/src/main/kotlin/com/ubertob/fotf/bowlingkata/BowlingGameFP.kt
uberto
654,026,766
false
{"Kotlin": 670097, "HTML": 34654, "CSS": 1900, "Shell": 593}
package com.ubertob.fotf.bowlingkata enum class Pins(val number: Int) { zero(0), one(1), two(2), three(3), four(4), five(5), six(6), seven(7), eight(8), nine(9), ten(10) } data class BowlingGameFP(val rolls: List<Pins>, val scoreFn: (List<Pins>) -> Int) { val score by lazy { scoreFn(rolls) } fun roll(pins: Pins): BowlingGameFP = copy(rolls = rolls + pins) companion object { fun newBowlingGame() = BowlingGameFP(emptyList(), Companion::calcBowlingScoreRec) fun calcBowlingScore(rolls: List<Pins>): Int { fun getRoll(roll: Int): Int = rolls.getOrElse(roll) { Pins.zero }.number fun isStrike(frameIndex: Int): Boolean = getRoll(frameIndex) == 10 fun sumOfBallsInFrame(frameIndex: Int): Int = getRoll(frameIndex) + getRoll(frameIndex + 1) fun spareBonus(frameIndex: Int): Int = getRoll(frameIndex + 2) fun strikeBonus(frameIndex: Int): Int = getRoll(frameIndex + 1) + getRoll(frameIndex + 2) fun isSpare(frameIndex: Int): Boolean = getRoll(frameIndex) + getRoll(frameIndex + 1) == 10 var score = 0 var frameIndex = 0 for (frame in 0..9) { if (isStrike(frameIndex)) { score += 10 + strikeBonus(frameIndex) frameIndex++ } else if (isSpare(frameIndex)) { score += 10 + spareBonus(frameIndex) frameIndex += 2 } else { score += sumOfBallsInFrame(frameIndex) frameIndex += 2 } } return score } fun calcBowlingScoreRec(rolls: List<Pins>): Int { val lastFrame = 10 val noOfPins = 10 fun List<Int>.isStrike(): Boolean = first() == noOfPins fun List<Int>.isSpare(): Boolean = take(2).sum() == noOfPins fun calcFrameScore(frame: Int, rolls: List<Int>): Int = when { frame == lastFrame || rolls.size < 3 -> rolls.sum() rolls.isStrike() -> rolls.take(3).sum() + calcFrameScore(frame + 1, rolls.drop(1)) rolls.isSpare() -> rolls.take(3).sum() + calcFrameScore(frame + 1, rolls.drop(2)) else -> rolls.take(2).sum() + calcFrameScore(frame + 1, rolls.drop(2)) } return calcFrameScore(1, rolls.map(Pins::number)) } } } fun scoreAndLog( fnLog: (Int) -> Unit, fnScore: (List<Int>) -> Int ): (List<Int>) -> Int = { rolls -> fnScore(rolls).also(fnLog) }
1
Kotlin
4
10
0e02c3a3025a6f10d13ae75475d6dae5b12d59bd
2,762
fotf
MIT License
src/main/kotlin/io/github/pshegger/aoc/y2015/Y2015D16.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2015 import io.github.pshegger.aoc.common.BaseSolver class Y2015D16 : BaseSolver() { override val year = 2015 override val day = 16 private val equalityChecker: AnalysisResult.(Int) -> Boolean = { value == it } private val greaterChecker: AnalysisResult.(Int) -> Boolean = { it > value } private val fewerChecker: AnalysisResult.(Int) -> Boolean = { it < value } private val analysisResults = listOf( AnalysisResult("children", 3, equalityChecker), AnalysisResult("cats", 7, greaterChecker), AnalysisResult("samoyeds", 2, equalityChecker), AnalysisResult("pomeranians", 3, fewerChecker), AnalysisResult("akitas", 0, equalityChecker), AnalysisResult("vizslas", 0, equalityChecker), AnalysisResult("goldfish", 5, fewerChecker), AnalysisResult("trees", 3, greaterChecker), AnalysisResult("cars", 2, equalityChecker), AnalysisResult("perfumes", 1, equalityChecker), ) override fun part1(): Int = solve(false).first().number override fun part2(): Int = solve(true).first().number private fun solve(useChecker: Boolean) = analysisResults.fold(parseInput()) { remainingSues, result -> remainingSues.filter { sue -> val owned = sue.compounds[result.name] if (useChecker) { owned == null || result.checker(result, owned) } else { owned == null || owned == result.value } } } private fun parseInput() = readInput { readLines().map { line -> val (nameAndNumber, compoundsStr) = line.split(":", limit = 2) val number = nameAndNumber.split(" ")[1].toInt() val compounds = compoundsStr.split(",") Sue( number, compounds.associate { compound -> val (name, value) = compound.split(":") Pair(name.trim(), value.trim().toInt()) } ) } } private data class AnalysisResult(val name: String, val value: Int, val checker: AnalysisResult.(Int) -> Boolean) private data class Sue(val number: Int, val compounds: Map<String, Int>) }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
2,246
advent-of-code
MIT License
arrays/AntiDiagonals/kotlin/Solution.kt
YaroslavHavrylovych
78,222,218
false
{"Java": 284373, "Kotlin": 35978, "Shell": 2994}
typealias IntArray2d = Array<IntArray> /** * Give a N*N square matrix, return an array of its anti-diagonals. * <br /> * https://www.interviewbit.com/problems/anti-diagonals/ */ fun diagonal(a: IntArray2d): IntArray2d { val n = a.size val res: MutableList<IntArray> = ArrayList(2 * n - 1) var i = 0 while (i < 2 * n - 1) { var ind1 = if (i < n) 0 else i - n + 1 var ind2 = if (i < n) i else n - 1 val row = IntArray(ind2 - ind1 + 1) var ind = 0 while (ind1 < n && ind2 >= 0) { row[ind++] = a[ind1++][ind2--] } res.add(row) i++ } return res.toTypedArray() } //Test fun main() { val param = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9)) val res = diagonal(param) val success = res[0][0] == 1 && res[1].contentEquals(intArrayOf(2, 4)) && res[2].contentEquals(intArrayOf(3, 5, 7)) && res[3].contentEquals(intArrayOf(6, 8)) && res[4][0] == 9 println("Anti Diagonals: ${if (success) "SUCCESS" else "FAIL"}") }
0
Java
0
2
cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd
1,101
codility
MIT License
src/main/kotlin/days/Day17.kt
hughjdavey
317,575,435
false
null
package days import Coord import Coord3 import Coord4 class Day17 : Day(17) { // 401 override fun partOne(): Any { val initialCoords = inputList.mapIndexed { y, s -> s.mapIndexedNotNull { x, c -> if (c == '#') Coord3(x, y, 0) else null } }.flatten() val dimension = PocketDimension(initialCoords) repeat(6) { dimension.cycle() } return ConwayNCube.allNCubes.count { it.active } } // 2224 // todo this take almost 7 minutes to run - improve algorithm! override fun partTwo(): Any { val initialCoords = inputList.mapIndexed { y, s -> s.mapIndexedNotNull { x, c -> if (c == '#') Coord4(x, y, 0, 0) else null } }.flatten() val dimension = PocketDimension(initialCoords) repeat(6) { dimension.cycle() } return ConwayNCube.allNCubes.count { it.active } } class PocketDimension(initial: List<Coord>) { init { ConwayNCube.allNCubes = initial.map { ConwayNCube(it, true) }.toMutableSet() } fun cycle() { ConwayNCube.grow() val cubes = ConwayNCube.allNCubes.toList() cubes.forEach { it.doCycle() } cubes.forEach { it.update() } ConwayNCube.allNCubes = cubes.filter { it.active }.toMutableSet() } } data class ConwayNCube(val coord: Coord, var active: Boolean) { var pendingChange: ((ConwayNCube) -> Unit)? = null fun update() = pendingChange?.let { it(this) } fun doCycle() { val activeNeighbours = getNeighbours().count { it.active } if (active && (activeNeighbours == 2 || activeNeighbours == 3)) { pendingChange = { it.active = true } } else if (!active && activeNeighbours == 3) { pendingChange = { it.active = true } } else { pendingChange = { it.active = false } } } private fun getNeighbours(): List<ConwayNCube> { return coord.getAdjacent().map { adj -> allNCubes.find { it.coord == adj } ?: addCube(ConwayNCube(adj, false)) } } companion object { lateinit var allNCubes: MutableSet<ConwayNCube> fun addCube(cube: ConwayNCube): ConwayNCube { allNCubes.add(cube) return cube } fun grow() { val neighbours = allNCubes.map { c -> c.coord.getAdjacent().map { ConwayNCube(it, false) } }.flatten() allNCubes.addAll(neighbours) } } } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,615
aoc-2020
Creative Commons Zero v1.0 Universal
src/Day04.kt
zodiia
573,067,225
false
{"Kotlin": 11268}
fun main() { fun getRanges(input: List<String>) = input.map { line -> line.split(',').map { range -> range.split('-').map(String::toInt).let { it[0]..it[1] } } } fun IntRange.containedIn(other: IntRange) = first >= other.first && last <= other.last fun part1(input: List<String>) = getRanges(input).count { it[0].containedIn(it[1]) || it[1].containedIn(it[0]) } fun part2(input: List<String>) = getRanges(input).count { it[0].intersect(it[1]).isNotEmpty() } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
4f978c50bb7603adb9ff8a2f0280f8fdbc652bf2
599
aoc-2022
Apache License 2.0
src/day09/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day09 import java.io.File const val workingDir = "src/day09" fun main() { val sample = File("$workingDir/sample.txt") val sample2 = File("$workingDir/sample2.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") // 13 println("Step 1b: ${runStep1(input1)}") println("Step 2a: ${runStep2(sample)}") // 1 println("Step 2a: ${runStep2(sample2)}") // 36 println("Step 2b: ${runStep2(input1)}") } fun runStep1(input: File): String { val rows = mutableListOf(mutableListOf(true)) var headX = 0 var headY = 0 var tailX = 0 var tailY = 0 input.readLines().forEach { val (direction, distance) = it.split(" ") repeat(distance.toInt()) { when (direction) { "R" -> { // handle head val row = rows[headY] if (headX + 1 == row.size) rows.forEach { it.add(false) } headX++ // handle tail if ((headX - tailX) == 2) { tailY = headY tailX++ row[tailX] = true } } "U" -> { // handle head if (headY == 0) { rows.add(0, rows[0].map { false }.toMutableList()) tailY++ } else { headY-- } // handle tail if (tailY - headY == 2) { tailX = headX tailY-- rows[tailY][tailX] = true } } "D" -> { // handle head if (headY + 1 == rows.size) { rows.add(rows[0].map { false }.toMutableList()) headY++ } else { headY++ } // handle tail if (headY - tailY == 2) { tailX = headX tailY++ rows[tailY][tailX] = true } } "L" -> { // handle head val row = rows[headY] if (headX == 0) { rows.forEach { it.add(0, false) } tailX++ } else { headX-- } // handle tail if (tailX - headX == 2) { tailY = headY tailX-- row[tailX] = true } } else -> TODO() } } } return rows.sumOf { it.count { it } }.toString() } data class Position(val x: Int, val y: Int) class Node(private val followedBy: Node?, val setTrue: (Int, Int)->Unit) { fun moveRight() { x++ handleTail() } private fun moveUpRight() { x++ y-- handleTail() } private fun handleTail() { if (followedBy != null) { val dx = x - followedBy.x val dy = y - followedBy.y val delta = Pair(dx, dy) if (dx !in listOf(-1, 0, 1) || dy !in listOf(-1, 0, 1)) when (delta) { Pair(2, 0) -> followedBy.moveRight() Pair(2, -1) -> followedBy.moveUpRight() Pair(2, -2) -> followedBy.moveUpRight() Pair(2, 1) -> followedBy.moveDownRight() Pair(2, 2) -> followedBy.moveDownRight() Pair(-2, -1) -> followedBy.moveUpLeft() Pair(-2, 0) -> followedBy.moveLeft() Pair(-2, -2) -> followedBy.moveUpLeft() Pair(-2, 1) -> followedBy.moveDownLeft() Pair(-2, 2) -> followedBy.moveDownLeft() Pair(1, -2) -> followedBy.moveUpRight() Pair(0, -2) -> followedBy.moveUp() Pair(-1, -2) -> followedBy.moveUpLeft() Pair(-1, 2) -> followedBy.moveDownLeft() Pair(0, 2) -> followedBy.moveDown() Pair(1, 2) -> followedBy.moveDownRight() else -> TODO("Need to handle $delta") } } else setTrue(x, y) } private fun moveUpLeft() { x-- y-- handleTail() } private fun moveDownRight() { y++ x++ handleTail() } private fun moveDownLeft() { y++ x-- handleTail() } fun moveLeft() { x-- handleTail() } fun moveUp() { y-- handleTail() } fun moveDown() { y++ handleTail() } private var x: Int = 0 private var y: Int = 0 } fun runStep2(input: File): String { val seenPositions = mutableSetOf(Position(0, 0)) val setTrue = {x: Int, y: Int -> Unit.also {seenPositions.add(Position(x, y))}} val head = Node(Node(Node(Node(Node(Node(Node(Node(Node(Node(null, setTrue), setTrue), setTrue), setTrue), setTrue), setTrue), setTrue), setTrue), setTrue), setTrue) input.readLines().forEach { val (direction, distance) = it.split(" ") repeat(distance.toInt()) { when (direction) { "R" -> head.moveRight() "U" -> head.moveUp() "D" -> head.moveDown() "L" -> head.moveLeft() else -> TODO() } } } return seenPositions.count().toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
5,824
advent-of-code-2022
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[112]路径总和.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* //给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 // targetSum 。 // // 叶子节点 是指没有子节点的节点。 // // // // 示例 1: // // //输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 //输出:true // // // 示例 2: // // //输入:root = [1,2,3], targetSum = 5 //输出:false // // // 示例 3: // // //输入:root = [1,2], targetSum = 0 //输出:false // // // // // 提示: // // // 树中节点的数目在范围 [0, 5000] 内 // -1000 <= Node.val <= 1000 // -1000 <= targetSum <= 1000 // // Related Topics 树 深度优先搜索 二叉树 // 👍 717 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * 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 hasPathSum(root: TreeNode?, targetSum: Int): Boolean { //方法一 //深度优先遍历 时间复杂度 O(n) //递归结束条件 if (root == null) return false //逻辑处理 进入下层循环 //如果左右子树为空,判断当前值是否等于 targetsum if (root.left == null && root.right == null) return root.`val` == targetSum //数据reverse //继续判断左右子树 return hasPathSum(root.left,targetSum - root.`val`) || hasPathSum(root.right,targetSum - root.`val`) //方法二 广度优先遍历 二叉树层序遍历 //使用队列先进先出 时间复杂度 O(n) if (root == null) return false val queue = LinkedList<TreeNode>() queue.addFirst(root) while (!queue.isEmpty()){ for (i in 0 until queue.size){ var node = queue.removeLast() //当前节点为子节点并且没有左右子树 说明符合 if (node.`val` == targetSum && node.left == null && node.right == null) return true //否则左右节点各自值累加 继续下一层次遍历 if (node.left != null) { node.left.`val` += node.`val` queue.addFirst(node.left) } if (node.right != null) { node.right.`val` += node.`val` queue.addFirst(node.right) } } } return false } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,719
MyLeetCode
Apache License 2.0
src/Day01.kt
aneroid
572,802,061
false
{"Kotlin": 27313}
class Day01(input: List<String>) { private val data = parseInput(input) fun partOne() = data.maxOf { it.sum() } fun partTwo() = data.map { it.sum() } .sortedDescending() .take(3) .sum() private companion object { fun parseInput(input: List<String>): List<List<Int>> = buildList { var group = mutableListOf<Int>() for (line in input) { if (line.isBlank()) { add(group) group = mutableListOf() } else { group.add(line.toInt()) } } add(group) } } } fun main() { val testInput = readInput("Day01_test") check(Day01(testInput).partOne() == 24000) check(Day01(testInput).partTwo() == 45000) // uncomment when ready val input = readInput("Day01") println("partOne: ${Day01(input).partOne()}\n") println("partTwo: ${Day01(input).partTwo()}\n") }
0
Kotlin
0
0
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
1,084
advent-of-code-2022-kotlin
Apache License 2.0
kotlin/src/com/leetcode/37_SudokuSolver.kt
programmerr47
248,502,040
false
null
package com.leetcode /** * Sort of a bitset but inverse and only 9 bits */ class SudokuUnit { //possible value. Just bit mask of where i-th bit is either i value is possible in this cell or not var posValue: Int = INITIAL_MASK private set var possibilities: Int = 9 private set val isEstablished: Boolean get() = possibilities <= 1 val value: Int get() = if (posValue == 0) 1 else (Integer.numberOfTrailingZeros(posValue) + 1) constructor() private constructor(other: SudokuUnit) { posValue = other.posValue possibilities = other.possibilities } fun reset() { posValue = INITIAL_MASK possibilities = 9 } fun set(index: Int) { posValue = 1 shl (index - 1) possibilities = 1 } fun exclude(index: Int) { val exclMask = 1 shl (index - 1) if ((posValue and exclMask) shr (index - 1) == 1) { possibilities-- } posValue = posValue and (exclMask xor INITIAL_MASK) } inline fun iterate(block: (Int) -> Unit) { var iter = posValue var value = 0 while (iter > 0) { val rem = iter % 2 iter = iter shr 1 value++ if (rem == 1) block(value) } } fun copy() = SudokuUnit(this) override fun toString(): String = posValue.toString() private companion object { const val INITIAL_MASK = 511 // 0b111111111 } } class SudokuBoard(private val n: Int = 3) { private val board: Array<Array<SudokuUnit>> init { val size = n * n board = Array(size) { Array(size) { SudokuUnit() } } } fun fill(charBoard: Array<CharArray>) { charBoard.forEachIndexed { i, row -> row.forEachIndexed { j, c -> if (c != '.') { set(board, c - '0', i, j) } } } } fun solveAny() { val dotCoords = ArrayList<Pair<Int, Int>>(n * n) board.forEachIndexed { i, row -> row.forEachIndexed { j, unit -> if (!board[i][j].isEstablished) { dotCoords.add(i to j) } } } dotCoords.sortBy { (i, j) -> board[i][j].possibilities } if (!solve(board, dotCoords, 0)) { throw IllegalStateException("The sudoku is not solvable for the given configuration") } } private fun solve(board: Array<Array<SudokuUnit>>, dotCoords: ArrayList<Pair<Int, Int>>, k: Int): Boolean { if (k > dotCoords.lastIndex) return true val (i, j) = dotCoords[k] if (board[i][j].isEstablished) { return solve(board, dotCoords, k + 1) } else { board[i][j].iterate { posValue -> val snapShot = board.snapshot() val result = kotlin.runCatching { set(snapShot, posValue, i, j) } if (result.isSuccess) { if (solve(snapShot, dotCoords, k + 1)) { snapShot.copyTo(board) return true } } } return false } } private fun Array<Array<SudokuUnit>>.snapshot() = Array(size) { i -> Array(this[i].size) { j -> this[i][j].copy() } } private fun Array<Array<SudokuUnit>>.copyTo(other: Array<Array<SudokuUnit>>) { forEachIndexed { i, row -> row.forEachIndexed { j, unit -> other[i][j] = this[i][j] } } } private fun set(board: Array<Array<SudokuUnit>>, num: Int, i: Int, j: Int) { if (board[i][j].isEstablished && board[i][j].value != num) { throw IllegalStateException("Board is corrupted. Number $num can not be placed on [$i, $j], since there is already number ${board[i][j]} there") } else { board[i][j].set(num) for (k in board.indices) { //excluding num from all places within same row if (k != j) { if (!exclude(board, num, i, k)) { throw IllegalStateException("Board is corrupted. Number $num can not be placed on [$i,$k], since it is already placed in the same row [$i,$j]") } } //excluding num from all places within same col if (k != i) { if (!exclude(board, num, k, j)) { throw IllegalStateException("Board is corrupted. Number $num can not be placed on [$k,$j], since it is already placed in the same column [$i,$j]") } } //excluding num from all places within same square val ki = (i / n) * n + k / n val kj = (j / n) * n + k % n if (ki != i && kj != j) { if (!exclude(board, num, ki, kj)) { throw IllegalStateException("Board is corrupted. Number $num can not be placed on [$ki,$kj], since it is already placed in the same square [${i/n},${j/n}]") } } } } } private fun exclude(board: Array<Array<SudokuUnit>>, num: Int, i: Int, j: Int): Boolean { if (board[i][j].isEstablished && board[i][j].value == num) { return false } else if (!board[i][j].isEstablished) { board[i][j].exclude(num) if (board[i][j].isEstablished) { set(board, board[i][j].value, i, j) } } return true } fun toCharBoard(cBoard: Array<CharArray>) { board.forEachIndexed { i, row -> row.forEachIndexed { j, unit -> cBoard[i][j] = if (board[i][j].isEstablished) { '0' + board[i][j].value } else { '.' } } } } } private class Solution37 { fun solveSudoku(board: Array<CharArray>) { val sudoku = SudokuBoard() sudoku.fill(board) sudoku.solveAny() sudoku.toCharBoard(board) } } fun main() { val solution = Solution37() println(solution.solve( arrayOf( charArrayOf('5','3','.','.','7','.','.','.','.'), charArrayOf('6','.','.','1','9','5','.','.','.'), charArrayOf('.','9','8','.','.','.','.','6','.'), charArrayOf('8','.','.','.','6','.','.','.','3'), charArrayOf('4','.','.','8','.','3','.','.','1'), charArrayOf('7','.','.','.','2','.','.','.','6'), charArrayOf('.','6','.','.','.','.','2','8','.'), charArrayOf('.','.','.','4','1','9','.','.','5'), charArrayOf('.','.','.','.','8','.','.','7','9') ) ).toStr()) println(solution.solve( arrayOf( charArrayOf('.','3','.','.','7','.','.','.','.'), charArrayOf('6','.','.','1','9','5','.','.','.'), charArrayOf('.','9','.','.','.','.','.','6','.'), charArrayOf('8','.','.','.','6','.','.','.','.'), charArrayOf('4','.','.','8','.','3','.','.','1'), charArrayOf('7','.','.','.','2','.','.','.','6'), charArrayOf('.','6','.','.','.','.','2','8','.'), charArrayOf('.','.','.','4','.','9','.','.','5'), charArrayOf('.','.','.','.','8','.','.','7','9') ) ).toStr()) println(solution.solve( arrayOf( charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.'), charArrayOf('.','.','.','.','.','.','.','.','.') ) ).toStr()) } private fun Array<CharArray>.toStr() = joinToString(separator = "\n") { it.joinToString() } private fun Solution37.solve(board: Array<CharArray>): Array<CharArray> = board.also { solveSudoku(it) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
8,390
problemsolving
Apache License 2.0
src/main/kotlin/daySeven/DaySeven.kt
janreppien
573,041,132
false
{"Kotlin": 26432}
package daySeven import AocSolution import java.io.File class DaySeven : AocSolution(7) { private val input = readInput() /** * I am not pound of this */ private fun readInput(): RootDirectory { val file = File("src/main/resources/inputs/daySeven/input.txt") val root = RootDirectory("/") var currentDirectory = root as Directory var readingContent = false file.readLines().forEach { if (readingContent) { if (it[0] == '$') { readingContent = false } else { if (it.contains("dir")) { currentDirectory.content.add(InnerDirectory(it.replace("dir ", ""), currentDirectory)) } else if (it == "$ cd ..") { currentDirectory = (currentDirectory as InnerDirectory).parent } else { val size = it.substringBefore(" ").toInt() val name = it.split(" ")[1].split(".")[0] val extension: String = if (it.contains(".")) { it.split(" ")[1].split(".")[1] } else { "" } currentDirectory.content.add(File(name, extension, size)) } } } if (it[0] == '$') { if (it.subSequence(2, 4) == "cd") { if (it.replace("$ cd ", "").contains("/")) { currentDirectory = root } else if (it == "$ cd ..") { currentDirectory = (currentDirectory as InnerDirectory).parent } else { currentDirectory = currentDirectory.getDirectories().filter { dir -> dir.name.contains( it .replace("$ cd ", "") ) }[0] } } else if (it.subSequence(2, 4) == "ls") { readingContent = true } } } return root } override fun solvePartOne(): String { return findDirectoriesSmallerThen(input, mutableSetOf(), 100000).sumOf { it.getSize() }.toString() } override fun solvePartTwo(): String { val neededSpace = 30000000 - (70000000 - input.getSize()) return findDirectoriesLargerThen(input, mutableSetOf(), neededSpace).minOf { it.getSize() }.toString() } private fun findDirectoriesSmallerThen(start: Directory, directories: MutableSet<Directory>, minSize: Int): MutableSet<Directory> { if (start.getSize() <= minSize) { directories.add(start) } start.getDirectories().forEach { directories.addAll(findDirectoriesSmallerThen(it, directories, minSize)) } return directories } private fun findDirectoriesLargerThen(start: Directory, directories: MutableSet<Directory>, minSize: Int): MutableSet<Directory> { if (start.getSize() >= minSize) { directories.add(start) } start.getDirectories().forEach { directories.addAll(findDirectoriesLargerThen(it, directories, minSize)) } return directories } }
0
Kotlin
0
0
b53f6c253966536a3edc8897d1420a5ceed59aa9
3,440
aoc2022
MIT License
src/main/kotlin/days/day9/Day9.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day9 import days.Day class Day9: Day(false) { override fun partOne(): Any { val inputs = readInput().map { it.split(" ").map { it.toInt() } } val result = mutableListOf<Int>() for (input in inputs) { val listsUnitZero: MutableList<MutableList<Int>> = mutableListOf(input.toMutableList()) while (!listsUnitZero.last().all { it == 0 }) { val differenceList = makeDifferenceList(listsUnitZero.last()) listsUnitZero.add(differenceList) } for (i in listsUnitZero.size-1 downTo 1){ listsUnitZero[i-1].add(listsUnitZero[i].last()+listsUnitZero[i-1].last()) } result.add(listsUnitZero[0].last()) } return result.sum() } override fun partTwo(): Any { val inputs = readInput().map { it.split(" ").map { it.toInt() } } val result = mutableListOf<Int>() for (input in inputs) { val listsUnitZero: MutableList<MutableList<Int>> = mutableListOf(input.toMutableList()) while (!listsUnitZero.last().all { it == 0 }) { val differenceList = makeDifferenceList(listsUnitZero.last()) listsUnitZero.add(differenceList) } for (i in listsUnitZero.size-1 downTo 1){ listsUnitZero[i-1].add(0,listsUnitZero[i-1].first() - listsUnitZero[i].first()) } result.add(listsUnitZero[0].first()) } return result.sum() } private fun makeDifferenceList(input:List<Int>):MutableList<Int> { val result = mutableListOf<Int>() for (i in 0 until input.size-1) { result.add(input[i+1] - input[i]) } return result } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
1,790
advent-of-code_2023
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem567/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem567 /** * LeetCode page: [567. Permutation in String](https://leetcode.com/problems/permutation-in-string/); */ class Solution { /* Complexity: * Time O(|s2|) and Space O(1); */ fun checkInclusion(s1: String, s2: String): Boolean { if (s1.length > s2.length) return false val targetCount = countCharFrequency(s1) val currWindowCount = countCharFrequency(s2, s1.indices) var numMatched = (0 until 26).count { currWindowCount[it] == targetCount[it] } if (numMatched == 26) return true for (index in s1.length until s2.length) { val popCountIndex = s2[index - s1.length] - 'a' currWindowCount[popCountIndex]-- when (currWindowCount[popCountIndex]) { targetCount[popCountIndex] -> numMatched++ targetCount[popCountIndex] - 1 -> numMatched-- } val pushCountIndex = s2[index] - 'a' currWindowCount[pushCountIndex]++ when (currWindowCount[pushCountIndex]) { targetCount[pushCountIndex] -> numMatched++ targetCount[pushCountIndex] + 1 -> numMatched-- } if (numMatched == 26) return true } return false } private fun countCharFrequency( lowercase: String, indexRange: IntRange = lowercase.indices ): IntArray { val count = IntArray(26) for (index in indexRange) { count[lowercase[index] - 'a']++ } return count } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,581
hj-leetcode-kotlin
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/medium/NextPermutation.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 31. 下一个排列 * * 实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 * 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 * 必须 原地 修改,只允许使用额外常数空间。 */ class NextPermutation { companion object { @JvmStatic fun main(args: Array<String>) { val nums = intArrayOf(1, 3, 2) NextPermutation().nextPermutation(nums) nums.forEach { println(it) } } } // nums = [1,2,3] // [1,3,2] fun nextPermutation(nums: IntArray) { val size = nums.size var hasMin = false var i = size - 2 while (i >= 0) { if (nums[i] < nums[i + 1]) { hasMin = true break } i-- } var j = size - 1 if (hasMin) { while (j >= i + 1) { if (nums[i] < nums[j]) { break } j-- } val temp = nums[i] nums[i] = nums[j] nums[j] = temp } var start = i + 1 var end = size - 1 while (start < end) { val temp = nums[start] nums[start++] = nums[end] nums[end--] = temp } } // //注意到下一个排列总是比当前排列要大,除非该排列已经是最大的排列。我们希望找到一种方法,能够找到一个大于当前序列的新序列,且变大的幅度尽可能小。具体地: // //我们需要将一个左边的「较小数」与一个右边的「较大数」交换,以能够让当前排列变大,从而得到下一个排列。 // //同时我们要让这个「较小数」尽量靠右,而「较大数」尽可能小。当交换完成后,「较大数」右边的数需要按照升序重新排列。这样可以在保证新排列大于原来排列的情况下,使变大的幅度尽可能小。 // //以排列 [4,5,2,6,3,1] 为例: // //我们能找到的符合条件的一对「较小数」与「较大数」的组合为 2 与 3,满足「较小数」尽量靠右,而「较大数」尽可能小。 // //当我们完成交换后排列变为 [4,5,3,6,2,1],此时我们可以重排「较小数」右边的序列,序列变为 [4,5,3,1,2,6]。 // //具体地,我们这样描述该算法,对于长度为 n 的排列 a: // //首先从后向前查找第一个顺序对 (i,i+1),满足 a[i] < a[i+1]。这样「较小数」即为 a[i]。此时 [i+1,n) 必然是下降序列。 // //如果找到了顺序对,那么在区间 [i+1,n) 中从后向前查找第一个元素 j 满足 a[i] < a[j]。这样「较大数」即为 a[j]。 // //交换 a[i] 与 a[j],此时可以证明区间 [i+1,n) 必为降序。我们可以直接使用双指针反转区间 [i+1,n) 使其变为升序,而无需对该区间进行排序。 // //如果在步骤 1 找不到顺序对,说明当前序列已经是一个降序序列,即最大的序列,我们直接跳过步骤 2 执行步骤 3,即可得到最小的升序序列。 // // }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
3,376
daily_algorithm
Apache License 2.0
src/main/kotlin/leveinshtein.kt
mxrpr
155,521,178
false
null
package com.mxr.example import kotlin.system.measureNanoTime /** * For learning purposes * * Two solutions: * 1. create Leveinshtein class * 2. extend CharSequence functionality */ class Leveinshtein { fun leveinshteinDistance(lhs: String, rhs: String): Int { if (lhs === rhs) return 0 if (lhs.isEmpty()) return rhs.length if (rhs.isEmpty()) return lhs.length val res = Array(lhs.length){ IntArray(rhs.length)} for (i in 0 until lhs.length) res[i][0] = i for (j in 0 until rhs.length) res[0][j] = j var subst = 0 for (j in 1 until rhs.length) { for (i in 1 until lhs.length) { subst = if (lhs[i] == rhs[j]) 0 else 1 val deletion = res[i-1][j] + 1 val insertion = res[i][j-1] +1 val substitution = res[i-1][j-1] + subst res[i][j] = Math.min(Math.min(deletion, insertion), substitution) } } return res[lhs.length-1][rhs.length-1] } private fun cost(a: Char, b: Char ): Int = if (a == b) 0 else 1 } /** * Extend the CharSequence */ fun CharSequence.leveinshtein(lhs: String): Int{ if (this === lhs) return 0 if (lhs.isEmpty()) return this.length if (this.isEmpty()) return lhs.length val res = Array(lhs.length){ IntArray(this.length)} for (i in 0 until lhs.length) res[i][0] = i for (j in 0 until this.length) res[0][j] = j var subst = 0 for (j in 1 until this.length) { for (i in 1 until lhs.length) { subst = if (lhs[i] == this[j]) 0 else 1 val deletion = res[i-1][j] + 1 val insertion = res[i][j-1] +1 val substitution = res[i-1][j-1] + subst res[i][j] = Math.min(Math.min(deletion, insertion), substitution) } } return res[lhs.length-1][this.length-1] } fun main(args: Array<String>) { val lev = Leveinshtein() var time = measureNanoTime { println(lev.leveinshteinDistance("rosettacode", "raisethysword")) } println("time: $time") time = measureNanoTime { println("rosettacode".leveinshtein("raisethysword")) } println("time: $time") }
0
Kotlin
0
0
0082d8bc92a587138c929f4b5b0d43cfcd2a1e6b
2,262
learning
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day05.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2022 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput /** * [Day 5: Supply Stacks](https://adventofcode.com/2022/day/5). */ object Day05 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day05") val initialStacks = listOf( ArrayDeque(listOf('J', 'H', 'P', 'M', 'S', 'F', 'N', 'V')), ArrayDeque(listOf('S', 'R', 'L', 'M', 'J', 'D', 'Q')), ArrayDeque(listOf('N', 'Q', 'D', 'H', 'C', 'S', 'W', 'B')), ArrayDeque(listOf('R', 'S', 'C', 'L')), ArrayDeque(listOf('M', 'V', 'T', 'P', 'F', 'B')), ArrayDeque(listOf('T', 'R', 'Q', 'N', 'C')), ArrayDeque(listOf('G', 'V', 'R')), ArrayDeque(listOf('C', 'Z', 'S', 'P', 'D', 'L', 'R')), ArrayDeque(listOf('D', 'S', 'J', 'V', 'G', 'P', 'B', 'F')) ) println("Part One: ${part1(initialStacks, input)}") println("Part Two: ${part2(initialStacks, input)}") } } fun part1(initialStacks: List<ArrayDeque<Char>>, input: List<String>): String { val stacks = mutableListOf<ArrayDeque<Char>>() initialStacks.forEach { stacks.add(ArrayDeque(it)) } input.forEach { instruction -> val (count, source, destination) = "\\d+".toRegex().findAll(instruction).toList().map { it.value.toInt() } repeat(count) { val char = stacks[source - 1].removeLast() stacks[destination - 1].addLast(char) } } return buildString { stacks.forEach { append(it.last()) } } } fun part2(initialStacks: List<ArrayDeque<Char>>, input: List<String>): String { val stacks = mutableListOf<ArrayDeque<Char>>() initialStacks.forEach { stacks.add(ArrayDeque(it)) } input.forEach { instruction -> val (count, source, destination) = "\\d+".toRegex().findAll(instruction).toList().map { it.value.toInt() } val chars = mutableListOf<Char>() repeat(count) { chars.add(stacks[source - 1].removeLast()) } stacks[destination - 1].addAll(chars.reversed()) } return buildString { stacks.forEach { append(it.last()) } } } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
2,375
advent-of-code
MIT License
src/main/kotlin/aoc2022/day2.kt
sodaplayer
434,841,315
false
{"Kotlin": 31068}
package aoc2022 import utils.loadInput import utils.partitionWhen // A Rock // B Paper // C Scissors // X Rock // Y Paper // Z Scissors // 0 Lost // 3 Lost // 6 Won fun main() { val lines = loadInput("/2022/day2") .bufferedReader() .readLines() // Part One lines.sumOf { play(it) } .also { println(it) } // Part Two lines.sumOf { play2(it) } .also { println(it) } } fun play(round: String): Int { val (opp, me) = round.split(' ') val outcome = when (opp) { "A" -> when (me) { "X" -> 3 "Y" -> 6 "Z" -> 0 else -> 0 } "B" -> when (me) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> 0 } "C" -> when (me) { "X" -> 6 "Y" -> 0 "Z" -> 3 else -> 0 } else -> 0 } val shape = when (me) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } return shape + outcome } fun play2(round: String): Int { val (opp, me) = round.split(' ') val outcome = when (opp) { "A" -> when (me) { "X" -> 0 + 3 "Y" -> 3 + 1 "Z" -> 6 + 2 else -> 0 } "B" -> when (me) { "X" -> 0 + 1 "Y" -> 3 + 2 "Z" -> 6 + 3 else -> 0 } "C" -> when (me) { "X" -> 0 + 2 "Y" -> 3 + 3 "Z" -> 6 + 1 else -> 0 } else -> 0 } return outcome }
0
Kotlin
0
0
2d72897e1202ee816aa0e4834690a13f5ce19747
1,627
aoc-kotlin
Apache License 2.0
src/main/kotlin/problems/Day12.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems class Day12(override val input: String) : Problem { override val number: Int = 12 private val START = "start" private val END = "end" private val connections: Map<String, Set<String>> = input.lines() .map { line -> line.split("-") } .flatMap { (a, b) -> listOf(Pair(a, b), Pair(b, a)) } // A connects to B and B connects to A .filter { (_, b) -> b != START } // Don't want to go back to START .groupBy { it.first } .mapValues { (_, value) -> value.map { it.second }.toSet() } override fun runPartOne(): String { return allPathsToEnd(START, visitedSmallCaveTwice = true) .count() .toString() } override fun runPartTwo(): String { return allPathsToEnd(START) .count() .toString() } private fun allPathsToEnd( startNode: String, currentPath: List<String> = emptyList(), visited: Set<String> = emptySet(), visitedSmallCaveTwice: Boolean = false ): Set<List<String>> { val newCurrentPath = currentPath + startNode val newVisited = when (startNode) { startNode.lowercase() -> visited + startNode else -> visited } if (startNode == END) { return setOf(newCurrentPath) } return connections[startNode]!!.flatMap { connection -> if (!visited.contains(connection)) { allPathsToEnd(connection, newCurrentPath, newVisited, visitedSmallCaveTwice) } else if (!visitedSmallCaveTwice) { allPathsToEnd(connection, newCurrentPath, newVisited, true) } else { emptySet() } }.toSet() } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
1,778
AdventOfCode2021
MIT License
src/Day02.kt
vlsolodilov
573,277,339
false
{"Kotlin": 19518}
import java.lang.Exception import java.lang.RuntimeException fun main() { fun getScoreOfShape(round: String): Int = when (round.last()) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> throw Exception("Error getScoreOfShape") } fun getScoreOfOutcome(round: String): Int = when (round) { "A Y", "B Z", "C X" -> 6 "A X", "B Y", "C Z" -> 3 else -> 0 } fun part1(input: List<String>): Int = input.sumOf { round -> getScoreOfOutcome(round) + getScoreOfShape(round) } fun getScoreOfShape2(round: String): Int = when (round) { "A Y", "B X", "C Z" -> 1 "A Z", "B Y", "C X" -> 2 "A X", "B Z", "C Y" -> 3 else -> throw Exception("Error getScoreOfShape2") } fun getScoreOfOutcome2(round: String): Int = when (round.last()) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> throw Exception("Error getScoreOfOutcome2") } fun part2(input: List<String>): Int = input.sumOf { round -> getScoreOfOutcome2(round) + getScoreOfShape2(round) } // test if implementation meets criteria from the description, like: 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
b75427b90b64b21fcb72c16452c3683486b48d76
1,506
aoc22
Apache License 2.0
src/Day01.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
fun main() { fun calories(input: List<String>): Sequence<Int> { val it = input.iterator() return generateSequence { var sum: Int? = null while (it.hasNext()) { val next = it.next().takeUnless(String::isEmpty)?.toInt() ?: break sum = (sum ?: 0) + next } sum } } fun part1(input: List<String>): Int = calories(input).max() fun part2(input: List<String>): Int = calories(input).toList().sorted().takeLast(3).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
b30c48f7941eedd4a820d8e1ee5f83598789667b
815
aockt
Apache License 2.0
src/Day03.kt
A55enz10
573,364,112
false
{"Kotlin": 15119}
fun main() { fun charToValue(char: Char): Int { var charNum: Int = char.hashCode() - 96 if (char.isUpperCase()) charNum += 32 + 26 return charNum } fun part1(input: List<String>): Int { var sum = 0 input.forEach { for (i in 0..it.length/2) { val idx = it.indexOf(it[i], it.length / 2) if (idx > 0) { sum += charToValue(it[idx]) break } } } return sum } fun part2(input: List<String>): Int { var sum = 0 for (i in input.indices step 3) { for (j in 0 until input[i].length) { if (i+2 < input.size && input[i+1].contains(input[i][j]) && input[i+2].contains(input[i][j])) { sum += charToValue(input[i][j]) break } } } return sum } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8627efc194d281a0e9c328eb6e0b5f401b759c6c
1,093
advent-of-code-2022
Apache License 2.0
src/main/kotlin/y2022/Day05.kt
jforatier
432,712,749
false
{"Kotlin": 44692}
package y2022 import common.Resources.splitOnEmpty import java.util.* class Day05(private val data: List<String>) { data class Move(val size: Int, val start: Int, val dest: Int) class Cargo(val data: List<String>) { val stacksInput = data.splitOnEmpty() .first() /** * [D] * [N] [C] * [Z] [M] [P] * 1 2 3 */ .reversed() /** * 1 2 3 * [Z] [M] [P] * [N] [C] * [D] */ val size = stacksInput.first().split(" ").filter { it -> it.isNotEmpty() }.last().toInt() val stack: MutableMap<Int, MutableList<String>> = mutableMapOf() val moves = data .dropWhile { !it.startsWith("move") }.map { val splittedValue = it.split(" ") Move(splittedValue[1].toInt(), splittedValue[3].toInt(), splittedValue[5].toInt()) } init { (0 until size).map { mapIndex -> if(stack[mapIndex] == null) { stack.put(mapIndex, mutableListOf()) } stacksInput.drop(1).forEach { // * [Z] [M] [P] val splittedLetters = it.chunked(4) if(mapIndex < splittedLetters.size && splittedLetters[mapIndex].isNotBlank()) { stack[mapIndex]!!.add(splittedLetters[mapIndex] .replace(" ","") .replace("[","") .replace("]","")) } } stack[mapIndex] = stack[mapIndex]!!.reversed().toMutableList() } } fun applyMoves(reversed: Boolean = true): String { var result = "" moves.forEach { move -> val toBeMoved = stack[move.start - 1]!!.take(move.size) repeat(move.size) { stack[move.start - 1]?.removeFirst() } stack[move.dest - 1]?.addAll(0, if (reversed) toBeMoved.reversed() else toBeMoved) } stack.forEach { result += it.value.first() } return result } } fun part1(): String { val cargo = Cargo(data) return cargo.applyMoves(true) } fun part2(): String { val cargo = Cargo(data) return cargo.applyMoves(false) } }
0
Kotlin
0
0
2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae
2,497
advent-of-code-kotlin
MIT License