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/Day22.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
@file:Suppress("PackageDirectoryMismatch") package day22 import readInput private sealed class Instruction { class Move(val amount: Int) : Instruction() class Rotate(val direction: Char) : Instruction() } fun main() { fun part1(input: List<String>): Int { val width = input.maxOf { it.length } // amount of columns, x position val height = input.size - 2 // amount of rows, y position val grid = Array(width) { Array(height) { ' ' } } repeat(height) { y -> val row = input[y] row.forEachIndexed { x, cell -> grid[x][y] = cell } } val instructions = input.last().fold(mutableListOf("")) { acc, cur -> if (cur.isDigit()) { val lastElement = acc.removeLast() acc += (lastElement + cur) } else { acc += listOf(cur.toString(), "") } acc }.filter { it.isNotEmpty() }.map { it -> if (it.length == 1 && !it.first().isDigit()) { Instruction.Rotate(it.first()) } else { Instruction.Move(it.toInt()) } } tailrec fun tryMoveX(currentX: Int, currentY: Int, xDirection: Int): Int? { var normalizedXPosition = (currentX + xDirection) % width if (normalizedXPosition < 0) { normalizedXPosition += width } return when (grid[normalizedXPosition][currentY]) { ' ' -> tryMoveX(normalizedXPosition, currentY, xDirection) '#' -> null else /* '.' */ -> normalizedXPosition } } tailrec fun tryMoveY(currentX: Int, currentY: Int, yDirection: Int): Int? { var normalizedYPosition = (currentY + yDirection) % height if (normalizedYPosition < 0) { normalizedYPosition += height } return when (grid[currentX][normalizedYPosition]) { ' ' -> tryMoveY(currentX, normalizedYPosition, yDirection) '#' -> null else /* '.' */ -> normalizedYPosition } } var currentX = input.first().indexOfFirst { it == '.' } var currentY = 0 var currentXDirection = 1 var currentYDirection = 0 instructions.forEach { instruction -> when (instruction) { is Instruction.Move -> { repeat(instruction.amount) { if (currentXDirection != 0) { val nextX = tryMoveX(currentX, currentY, currentXDirection) ?: return@forEach currentX = nextX } else { val nextY = tryMoveY(currentX, currentY, currentYDirection) ?: return@forEach currentY = nextY } } } is Instruction.Rotate -> { if (instruction.direction == 'L') { // > .. ^ .. < .. v // x: 1 .. 0 ..-1 .. 0 // y: 0 ..-1 .. 0 .. 1 // next x = cur y // next y = inverse cur x val nextX = currentYDirection val nextY = currentXDirection * -1 currentXDirection = nextX currentYDirection = nextY } else { // 'R' // > .. v .. < .. ^ // x: 1 .. 0 ..-1 .. 0 // y: 0 .. 1 .. 0 ..-1 // next x = inverse cur y // next y = cur x val nextX = currentYDirection * -1 val nextY = currentXDirection currentXDirection = nextX currentYDirection = nextY } } } } val directionValue = when { currentXDirection == 1 -> 0 currentYDirection == 1 -> 1 currentXDirection == -1 -> 2 currentYDirection == -1 -> 3 else -> throw IllegalStateException("Unknown direction: $currentXDirection, $currentYDirection") } return 1000 * (currentY + 1) + 4 * (currentX + 1) + directionValue } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val dayNumber = 22 val testInput = readInput("Day${dayNumber}_test") val testResultPart1 = part1(testInput) val testAnswerPart1 = 6032 check(testResultPart1 == testAnswerPart1) { "Part 1: got $testResultPart1 but expected $testAnswerPart1" } val testResultPart2 = part2(testInput) val testAnswerPart2 = 12345 // check(testResultPart2 == testAnswerPart2) { "Part 2: got $testResultPart2 but expected $testAnswerPart2" } val input = readInput("Day$dayNumber") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
5,191
advent-of-code-2022-kotlin
Apache License 2.0
src/Year2022Day10.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
fun main() { fun part1(input: List<String>): Int { val targetCycles = (20..220 step 40) var x = 1 var cycle = 1 var ans = 0 fun dida() { if (++cycle in targetCycles) ans += cycle * x } for (line in input) { if (line.startsWith("addx")) { dida() x += line.substringAfter(" ").toInt() dida() } else { dida() } } return ans } fun part2(input: List<String>) { val g = BooleanArray(240) var x = 1 var cycle = 1 g[0] = true fun dida() { if ((++cycle - 1) % 40 in (x - 1..x + 1)) g[cycle - 1] = true } for (line in input) { if (line.startsWith("addx")) { dida() x += line.substringAfter(" ").toInt() dida() } else { dida() } } for (i in (1..240)) { print(if (g[i - 1]) '#' else '.') if (i % 40 == 0) println() } } check(part1(readLines(true)) == 13140) part2(readLines(true)) val lines = readLines() println(part1(lines)) part2(lines) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
1,306
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/java/com/arindam/kotlin/ds/GFG.kt
arindamxd
192,865,868
false
null
package com.arindam.kotlin.ds /** * Kotlin program to find out all combinations of positive numbers that add up to given number. * * Created by <NAME> on 29/7/19. */ fun main() { val k = 5 findCombinations(k) } /** * @param arr array to store the combination * @param index next location in array * @param num given number * @param reducedNum reduced number */ fun findCombinationsUtil(arr: IntArray, index: Int, num: Int, reducedNum: Int) { // Base condition if (reducedNum < 0) return // If combination is // found, print it if (reducedNum == 0) { for (i in 0 until index) print(arr[i].toString() + " ") println() return } // Find the previous number // stored in arr[]. It helps // in maintaining increasing // order val prev = if (index == 0) 1 else arr[index - 1] // note loop starts from // previous number i.e. at // array location index - 1 for (k in prev..num) { // next element of // array is k arr[index] = k // call recursively with // reduced number findCombinationsUtil(arr, index + 1, num, reducedNum - k) } } /** * Function to find out all combinations of positive numbers that add up to given number. * It uses findCombinationsUtil() * * @param n max n elements */ fun findCombinations(n: Int) { // array to store the combinations // It can contain max n elements val arr = IntArray(n) // find all combinations findCombinationsUtil(arr, 0, n, n) }
0
Kotlin
1
14
d9393b8c211b5d06d81d67455e4b496d01e7c673
1,603
kotlin-development
Apache License 2.0
AoC2021day04-GiantSquid/src/main/kotlin/Main.kt
mcrispim
533,770,397
false
{"Kotlin": 29888}
import java.io.File import java.util.* var numbers: List<Int> = emptyList() var boards: MutableList<Board> = mutableListOf() data class Square(var number: Int, var isChecked: Boolean = false) class Board() { var won: Boolean = false val numbers = mutableSetOf<Int>() val squares = arrayOf( arrayOf(Square(0), Square(0), Square(0), Square(0), Square(0)), arrayOf(Square(0), Square(0), Square(0), Square(0), Square(0)), arrayOf(Square(0), Square(0), Square(0), Square(0), Square(0)), arrayOf(Square(0), Square(0), Square(0), Square(0), Square(0)), arrayOf(Square(0), Square(0), Square(0), Square(0), Square(0)) ) fun printBoard() { for (row in squares.indices) { for (col in squares[row].indices) { print("${squares[row][col].number.toString().format("%d")} ") } println() } } fun isRowChecked(row: Int): Boolean { var allChecked = true for (col in 0..4) { if (!squares[row][col].isChecked) { return false } } return true } fun isColChecked(col: Int): Boolean { var allChecked = true for (row in 0..4) { if (!squares[row][col].isChecked) { return false } } return true } fun whereIs(n: Int): Pair<Int, Int> { for (r in 0..4) { for (c in 0..4) { if (squares[r][c].number == n) { return Pair(r, c) } } } return Pair(0, 0) } fun unmarkedPoints(): Int { var points = 0 for (r in 0..4) { for (c in 0..4) { if (!squares[r][c].isChecked) { points += squares[r][c].number } } } return points } } fun main() { val input = File("bingoData.txt") val scanner = Scanner(input) numbers = scanner.nextLine().split(",").map { it.toInt() } while (scanner.hasNext()) { val board = Board() for (row in 0 .. 4) { for (col in 0..4) { val n = scanner.nextInt() board.squares[row][col].number = n board.numbers.add(n) } } boards.add(board) // board.printBoard() // println("=================") } for (n in numbers) { for ((boardIndex, b) in boards.withIndex()) { if (b.won) { continue } if (n in b.numbers) { val (row, col) = b.whereIs(n) b.squares[row][col].isChecked = true if (b.isRowChecked(row) || b.isColChecked(col)) { println("Board ${boardIndex + 1} ganhou com um score de ${b.unmarkedPoints() * n}") b.won = true continue } } } } }
0
Kotlin
0
0
ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523
2,994
AoC2021
MIT License
src/Day12.kt
frozbiz
573,457,870
false
{"Kotlin": 124645}
import java.util.PriorityQueue class TopoGrid ( val grid: List<List<Char>>, val start: Point, val end: Point, val lowPoints: List<Point> ) { val bestPathVals = mutableMapOf(Pair(start, 0)) fun solve(): Int { var routes = PriorityQueue<Triple<Point, Int, Int>> { triple, triple2 -> if (triple.third != triple2.third) triple.third - triple2.third else triple2.second - triple.second } routes.add(Triple(start,0, start.manhattanDistanceTo(end))) while (bestPathVals[end] == null) { val (route, currLength, _) = routes.poll() val length = currLength + 1 for (option in optionsForRoute(route)) { bestPathVals[option] = length if (option == end) { return length } val bestPossibleLength = length + route.manhattanDistanceTo(end) routes.add(Triple(option, length, bestPossibleLength)) } } return bestPathVals[end]!! } fun solveNaive(): Int { var routes = mutableListOf(start) var length = 0 while (bestPathVals[end] == null) { length += 1 val nextRound = mutableListOf<Point>() for (route in routes) { for (option in optionsForRoute(route)) { bestPathVals[option] = length if (option == end) { return length } nextRound.add(option) } } // printRoutes() routes = nextRound } return bestPathVals[end] ?: -1 } fun solveNaiveAnyAStart(): Int { bestPathVals.putAll(lowPoints.map { Pair(it,0) }) var routes = mutableListOf(start) routes.addAll(lowPoints) var length = 0 while (bestPathVals[end] == null) { length += 1 val nextRound = mutableListOf<Point>() for (route in routes) { for (option in optionsForRoute(route)) { bestPathVals[option] = length if (option == end) { return length } nextRound.add(option) } } // printRoutes() routes = nextRound } return bestPathVals[end] ?: -1 } fun optionsForRoute(route: Point): List<Point> { val currentHeight = get(route)!! val ret = mutableListOf<Point>() for (point in route.cardinalDirectionsFromPoint()) { if (point in bestPathVals) continue get(point)?.let { if (it <= currentHeight + 1) { ret.add(point) } } } return ret } operator fun get(x: Int, y:Int): Char? { return grid.getOrNull(y)?.getOrNull(x) } operator fun get(pt: Point): Char? { return get(pt.x, pt.y) } fun print() { for ((y,row) in grid.withIndex()) println(row.mapIndexed { x, col -> when (Point(x,y)) { start -> 'S' end -> 'E' else -> col } }) } fun printRoutes() { for ((y,row) in grid.withIndex()) println(row.mapIndexed { x, col -> when (Point(x,y)) { in bestPathVals -> bestPathVals[Point(x,y)].toString() start -> 'S' end -> 'E' else -> col } }) } companion object { fun gridWithInput(input: List<String>): TopoGrid { var start = Point(0,0) var end = Point(0,0) val lowPoints = mutableListOf<Point>() val grid = input.mapIndexed { y, s -> s.trim().mapIndexed { x, c -> when (c) { 'S' -> { start = Point(x,y) 'a' } 'E' -> { end = Point(x,y) 'z' } 'a' -> { lowPoints.add(Point(x,y)) c } else -> c } } } return TopoGrid(grid, start, end, lowPoints) } } } fun main() { fun part1(input: List<String>): Int { var grid = TopoGrid.gridWithInput(input) grid.print() println(grid.solve()) grid.printRoutes() println("Explored ${grid.bestPathVals.size} nodes.") grid = TopoGrid.gridWithInput(input) println(grid.solveNaive()) grid.printRoutes() println("Explored ${grid.bestPathVals.size} nodes.") return 1 } fun part2(input: List<String>): Int { val grid = TopoGrid.gridWithInput(input) println(grid.solveNaiveAnyAStart()) grid.printRoutes() println("Explored ${grid.bestPathVals.size} nodes.") return 1 } // test if implementation meets criteria from the description, like: val testInput = listOf( "Sabqponm\n", "abcryxxl\n", "accszExk\n", "acctuvwj\n", "abdefghi\n" ) check(part1(testInput) == 1) check(part2(testInput) == 1) val input = readInput("day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4feef3fa7cd5f3cea1957bed1d1ab5d1eb2bc388
5,596
2022-aoc-kotlin
Apache License 2.0
src/Day01.kt
sushovan86
573,586,806
false
{"Kotlin": 47064}
import java.io.File import java.util.* val EMPTY_LINE_SEPARATOR = System.lineSeparator().repeat(2) fun main() { fun String.splitByEmptyLine() = this.splitToSequence(EMPTY_LINE_SEPARATOR) fun topElvesCalories(numberOfElves: Int, input: String): List<Int> { val priorityQueue = PriorityQueue<Int>() input.splitByEmptyLine() .map { it.lines().sumOf(String::toInt) } .forEach { priorityQueue.add(it) if (priorityQueue.size > numberOfElves) { priorityQueue.poll() } } return priorityQueue.toList() } fun part1(input: String): Int { return topElvesCalories(1, input)[0] } fun part2(input: String): Int { return topElvesCalories(3, input).sum() } // test if implementation meets criteria from the description, like: val testInput = File("resource/Day01_test").readText() check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = File("resource/Day01").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5f85b6a48e3505d06b4ae1027e734e66b324964
1,163
aoc-2022
Apache License 2.0
src/main/kotlin/day4.kt
tianyu
574,561,581
false
{"Kotlin": 49942}
private fun main() { part1("The number of fully overlapping assignments is:") { sectionAssignmentPairs().count { (left, right) -> left in right || right in left } } part2("The number of partially overlapping assignments is:") { sectionAssignmentPairs().count { (left, right) -> left.first in right || left.last in right || right in left } } } private operator fun IntRange.contains(that: IntRange): Boolean = first <= that.first && last >= that.last private fun sectionAssignmentPairs() = sequence { withInputLines("day4.txt") { forEach { line -> val (lo1, hi1, lo2, hi2) = line.split('-', ',').map(String::toInt) yield(lo1..hi1 to lo2..hi2) } } }
0
Kotlin
0
0
6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea
713
AdventOfCode2022
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem76/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem76 /** * LeetCode page: [76. Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/); */ class Solution { /* Complexity: * Time O(M+N) and Space O(N) where M and N are the length of s and t respectively; */ fun minWindow(s: String, t: String): String { val missingCount = t.groupingBy { it }.eachCountTo(hashMapOf()) var missingLength = t.length var minWindow = 0..s.length var latestStart = 0 for (end in s.indices) { if (s[end] !in missingCount) { continue } missingCount[s[end]] = checkNotNull(missingCount[s[end]]) - 1 if (checkNotNull(missingCount[s[end]]) >= 0) { missingLength -= 1 } while (latestStart <= end && (missingCount[s[latestStart]]?.let { it < 0 } != false)) { if (s[latestStart] in missingCount) { missingCount[s[latestStart]] = checkNotNull(missingCount[s[latestStart]]) + 1 } latestStart += 1 } if (missingLength == 0 && end - latestStart < minWindow.last - minWindow.first) { minWindow = latestStart..end } } return if (missingLength > 0) "" else s.slice(minWindow) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,365
hj-leetcode-kotlin
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2023/Day20.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.lcm import com.kingsleyadio.adventofcode.util.readInput fun main() { val (model, inputs) = buildModel() part1(model, inputs) part2(model, inputs) } private fun part1(model: Model, inputs: Inputs) { val signals = IntArray(2) for (i in 1..1000) simulation(model, inputs) { _, _, pulse -> signals[if (pulse) 1 else 0]++ } val result = signals[0] * signals[1] println(result) } private fun part2(model: Model, inputs: Inputs) { model.values.forEach(PulseModule::reset) var presses = 0 val mgName = inputs.getValue("rx").single() val mg = model.getValue(mgName) as ConjunctionModule val xToMg = hashMapOf<String, Int>() while (true) { presses++ simulation(model, inputs) { from, to, pulse -> if (to == mg.name && pulse) xToMg.putIfAbsent(from, presses) } if (xToMg.size == inputs.getValue(mg.name).size) break } val result = xToMg.values.fold(1L) { acc, n -> lcm(acc, n.toLong()) } println(result) } private inline fun simulation(model: Model, inputs: Inputs, onSignal: (String, String, Boolean) -> Unit) { val queue = ArrayDeque<Triple<String, String, Boolean>>() queue.addLast(Triple("button", "broadcaster", false)) while (queue.isNotEmpty()) { val (from, to, pulse) = queue.removeFirst() onSignal(from, to, pulse) val module = model[to] ?: continue val moduleInputs = inputs.getOrDefault(module.name, emptySet()) val newPulse = module.transformPulse(from, pulse, moduleInputs.size) ?: continue for (output in module.outputs) queue.addLast(Triple(module.name, output, newPulse)) } } private fun buildModel(isSample: Boolean = false) = readInput(2023, 20, isSample).useLines { lines -> val inputs = hashMapOf<String, MutableSet<String>>() val model = hashMapOf<String, PulseModule>() for (line in lines) { val (name, other) = line.split(" -> ") val outputs = other.split(", ") val module = when { name.startsWith("%") -> FlipFlopModule(name.drop(1), outputs) name.startsWith("&") -> ConjunctionModule(name.drop(1), outputs) else -> BroadcastModule(name, outputs) } model[module.name] = module for (output in outputs) inputs.getOrPut(output) { hashSetOf() }.add(module.name) } model to inputs } private typealias Model = Map<String, PulseModule> private typealias Inputs = Map<String, Set<String>> private sealed interface PulseModule { val name: String val outputs: List<String> fun transformPulse(from: String, pulse: Boolean, inputSize: Int): Boolean? fun reset() } private data class BroadcastModule(override val name: String, override val outputs: List<String>) : PulseModule { override fun transformPulse(from: String, pulse: Boolean, inputSize: Int) = pulse override fun reset() {} } private data class FlipFlopModule(override val name: String, override val outputs: List<String>) : PulseModule { private var isOn: Boolean = false override fun transformPulse(from: String, pulse: Boolean, inputSize: Int): Boolean? { if (pulse) return null return isOn.not().also { isOn = it } } override fun reset() = run { isOn = false } } private data class ConjunctionModule(override val name: String, override val outputs: List<String>) : PulseModule { private val states = hashMapOf<String, Boolean>() override fun transformPulse(from: String, pulse: Boolean, inputSize: Int): Boolean { states[from] = pulse return states.values.count { it } != inputSize } override fun reset() = states.clear() }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
3,730
adventofcode
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/automata/FSA.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph.automata import ai.hypergraph.kaliningraph.graphs.* import ai.hypergraph.kaliningraph.parsing.Σᐩ import ai.hypergraph.kaliningraph.tokenizeByWhitespace import ai.hypergraph.kaliningraph.types.* typealias Arc = Π3A<Σᐩ> typealias TSA = Set<Arc> fun Arc.pretty() = "$π1 -<$π2>-> $π3" fun Σᐩ.coords(): Pair<Int, Int> = (length / 2 - 1).let { substring(2, it + 2).toInt() to substring(it + 3).toInt() } typealias STC = Triple<Σᐩ, Int, Int> fun STC.coords() = π2 to π3 open class FSA(open val Q: TSA, open val init: Set<Σᐩ>, open val final: Set<Σᐩ>) { open val alphabet by lazy { Q.map { it.π2 }.toSet() } val isNominalizable by lazy { alphabet.any { it.startsWith("[!=]") } } val nominalForm: NOM by lazy { nominalize() } val states by lazy { Q.states } val APSP: Map<Pair<Σᐩ, Σᐩ>, Int> by lazy { graph.APSP.map { (k, v) -> Pair(Pair(k.first.label, k.second.label), v) }.toMap() } val stateCoords: Sequence<STC> by lazy { states.map { it.coords().let { (i, j) -> Triple(it, i, j) } }.asSequence() } val edgeLabels by lazy { Q.groupBy { (a, b, c) -> a to c } .mapValues { (_, v) -> v.map { it.π2 }.toSet().joinToString(",") } } val map: Map<Π2A<Σᐩ>, Set<Σᐩ>> by lazy { Q.groupBy({ (a, b, _) -> a to b }, { (_, _, c) -> c }) .mapValues { (_, v) -> v.toSet() } // .also { it.map { println("${it.key}=${it.value.joinToString(",", "[", "]"){if(it in init) "$it*" else if (it in final) "$it@" else it}}") } } } fun allOutgoingArcs(from: Σᐩ) = Q.filter { it.π1 == from } val graph: LabeledGraph by lazy { LabeledGraph { Q.forEach { (a, b, c) -> a[b] = c } } } fun debug(str: List<Σᐩ>) = (0..str.size).forEachIndexed { i, it -> val states = str.subList(0, it).fold(init) { acc, sym -> val nextStates = acc.flatMap { map[it to sym] ?: emptySet() }.toSet() nextStates } println("Step ($i): ${states.joinToString(", ")}") }.also { println("Allowed final states: ${final.joinToString(", ")}") } open fun recognizes(str: List<Σᐩ>) = if (isNominalizable) nominalForm.recognizes(str) else (str.fold(init) { acc, sym -> val nextStates = acc.flatMap { map[it to sym] ?: emptySet() }.toSet() // println("$acc --$sym--> $nextStates") nextStates.also { println("Next states: $it") } } intersect final).isNotEmpty() open fun recognizes(str: Σᐩ) = recognizes(str.tokenizeByWhitespace()) fun toDot(): String { fun String.htmlify() = replace("<", "&lt;").replace(">", "&gt;") return """ strict digraph { graph ["concentrate"="false","rankdir"="LR","bgcolor"="transparent","margin"="0.0","compound"="true","nslimit"="20"] ${ states.joinToString("\n") { """"${it.htmlify()}" ["color"="black","fontcolor"="black","fontname"="JetBrains Mono","fontsize"="15","penwidth"="2.0","shape"="Mrecord"${if(it in final)""","fillcolor"=lightgray,"style"=filled""" else ""}]""" } } ${edgeLabels.entries.joinToString("\n") { (v, e) -> val (src, tgt) = v.first to v.second """"$src" -> "$tgt" ["arrowhead"="normal","penwidth"="2.0"]""" } } } """.trimIndent() } } val TSA.states by cache { flatMap { listOf(it.π1, it.π3) }.toSet() } // FSAs looks like this: /* INIT -> 1 | 3 DONE -> 4 1 -<a>-> 1 1 -<+>-> 3 3 -<b>-> 4 4 -<+>-> 1 4 -<b>-> 4 */ fun Σᐩ.parseFSA(): FSA { val Q = lines().asSequence() .filter { it.isNotBlank() } .map { it.split("->") } .map { (lhs, rhs) -> val src = lhs.tokenizeByWhitespace().first() val dst = rhs.split('|').map { it.trim() }.toSet() val sym = if ("-<" in lhs && lhs.endsWith(">")) lhs.split("-<").last().dropLast(1) else "" setOf(src) * setOf(sym) * dst }.flatten().toList() .onEach { println(it) } val init = Q.filter { it.π1 == "INIT" }.map { it.π3 }.toSet() val final = Q.filter { it.π1 == "DONE" }.map { it.π3 }.toSet() return FSA(Q.filter { it.π1 !in setOf("INIT", "DONE") }.toSet(), init, final) }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
4,133
galoisenne
Apache License 2.0
usvm-util/src/test/kotlin/org/usvm/algorithms/WeightedAaTreeTests.kt
UnitTestBot
586,907,774
false
{"Kotlin": 2547205, "Java": 471958}
package org.usvm.algorithms import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlin.test.fail internal class WeightedAaTreeTests { private fun checkInvariants(node : AaTreeNode<*>) { // The level of every leaf node is one if (node.left == null && node.right == null) { assertEquals(1, node.level) } // The level of every left child is exactly one less than that of its parent if (node.left != null) { assertEquals(node.level - 1, node.left!!.level) } // The level of every right child is equal to or one less than that of its parent if (node.right != null) { assertTrue(node.right!!.level == node.level - 1 || node.right!!.level == node.level) // The level of every right grandchild is strictly less than that of its grandparent if (node.right!!.right != null) { assertTrue(node.right!!.right!!.level < node.level) } } // Every node of level greater than one has two children if (node.level > 1) { assertNotNull(node.left) assertNotNull(node.right) } // Additional weighted tree invariant assertEquals(node.weight, node.weightSum - (node.left?.weightSum ?: 0.0) - (node.right?.weightSum ?: 0.0), 1e-5) } @Test fun simpleCountTest() { val tree = WeightedAaTree<Int>(naturalOrder()) tree.add(5, 5.0) assertEquals(1, tree.count) } @Test fun sameElementsAreNotAddedTest() { val tree = WeightedAaTree<Int>(naturalOrder()) tree.add(5, 5.0) tree.add(5, 10.0) assertEquals(1, tree.count) } @Test fun preOrderTraversalTraversesAllNodesTest() { val tree = WeightedAaTree<Int>(naturalOrder()) val elementsCount = 1000 for (i in 1..elementsCount) { val value = pseudoRandom(i) val weight = i.toDouble() tree.add(value, weight) } val traversed = HashSet<Int>() fun traverse(node : AaTreeNode<Int>) { if (traversed.contains(node.value)) { fail() } traversed.add(node.value) } tree.preOrderTraversal().forEach(::traverse) assertEquals(elementsCount, traversed.size) } @Test fun treeInvariantsAreSatisfiedTest() { val tree = WeightedAaTree<Int>(naturalOrder()) val elementsCount = 1000 for (i in 1..elementsCount) { val value = pseudoRandom(i) val weight = i.toDouble() tree.add(value, weight) } assertEquals(elementsCount, tree.count) tree.preOrderTraversal().forEach(::checkInvariants) for (i in 1..elementsCount) { val value = pseudoRandom(i) tree.remove(value) tree.preOrderTraversal().forEach(::checkInvariants) assertEquals(elementsCount - i, tree.count) } } }
39
Kotlin
0
7
94c5a49a0812737024dee5be9d642f22baf991a2
3,100
usvm
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions28.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 fun test28() { val a = BinaryTreeNode(8) val b = BinaryTreeNode(6) val c = BinaryTreeNode(6) val d = BinaryTreeNode(5) val e = BinaryTreeNode(7) val f = BinaryTreeNode(7) val g = BinaryTreeNode(5) a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g println(a.isSymmetrical()) c.value = 9 println(a.isSymmetrical()) val h = BinaryTreeNode(7) val i = BinaryTreeNode(7) val j = BinaryTreeNode(7) val k = BinaryTreeNode(7) val l = BinaryTreeNode(7) val m = BinaryTreeNode(7) h.left = i h.right = j i.left = k i.right = l j.left = m println(h.isSymmetrical()) } fun <T> BinaryTreeNode<T>.isSymmetrical(): Boolean { if (preOrderJudgment()) { if (preOrderBack() == _preOrderBack()) { return true } } return false } fun <T> BinaryTreeNode<T>.preOrderJudgment(): Boolean { var boo = judgment() if (boo) { left?.let { boo = it.preOrderJudgment() } right?.let { boo = it.preOrderJudgment() } } return boo } private fun <T> BinaryTreeNode<T>.judgment() = (left == null && right == null) || (left != null && right != null) fun <T> BinaryTreeNode<T>.preOrderBack(): String { var str = value.toString() str += left?.preOrderBack() str += right?.preOrderBack() return str } fun <T> BinaryTreeNode<T>._preOrderBack(): String { var str = value.toString() str += right?._preOrderBack() str += left?._preOrderBack() return str }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,436
Algorithm
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day309/day309.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day309 // day309.kt // By <NAME> // M people sitting in a row of N seats. enum class SeatContent { PERSON, EMPTY } typealias SeatContents=List<SeatContent> /** * Clump the people in the seats so that there are no gaps * between them using the fewest moves. */ fun SeatContents.group(): Int { if (isEmpty()) return 0 // We want the median of the seat contents: we see that as the point of gravity and move everyone there. val seatsUsed = indices.filter { get(it) == SeatContent.PERSON } // Process everyone to the left of the median, and then to the right of the median. val median = seatsUsed.count() / 2 // Move seats points towards median: val leftSeats = seatsUsed.take(median) // We adjust by the index because each seat must be 1 further away from the median. val leftDistancesToMedian = leftSeats.withIndex().map { (idx, seat) -> seatsUsed[median] - seat - (idx + 1) }.sum() // Move right seats towards median: val rightSeats = seatsUsed.drop(median + 1) // We adjust by the index because each seat must be 1 further away from the median. val rightDistancesToMedian = rightSeats.withIndex().map { (idx, seat) -> seat - seatsUsed[median] - (idx + 1)}.sum() return leftDistancesToMedian + rightDistancesToMedian } val P = SeatContent.PERSON val E = SeatContent.EMPTY
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,382
daily-coding-problem
MIT License
src/Day01.kt
davedupplaw
573,042,501
false
{"Kotlin": 29190}
fun main() { fun getElvesWithCalories(input: List<String>): Map<Int, Int> { var elfNumber = 0 return input.mapNotNull { i -> if (i.isBlank()) { elfNumber++; null } else elfNumber to i.toInt() } .groupBy({ it.first }, { it.second }) .mapValues { it.value.sum() } } fun part1(input: List<String>): Int { return getElvesWithCalories(input) .values .max() } fun part2(input: List<String>): Int { return getElvesWithCalories(input) .values .sortedDescending() .take(3) .sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3b3efb1fb45bd7311565bcb284614e2604b75794
797
advent-of-code-2022
Apache License 2.0
src/2021/Day13.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2021` import common.Point import java.io.File import java.util.* fun main() { Day13().solve() } class Day13 { val input0 = """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() private data class Instruction(val axis: String, val location: Int) { fun apply(p: Point): Point { when (axis) { "x" -> return p.foldX(location) "y" -> return p.foldY(location) else -> throw RuntimeException() } } } fun solve() { val f = File("src/2021/inputs/day13.in") val s = Scanner(f) // val s = Scanner(input0) var points = mutableSetOf<Point>() val instructions = mutableListOf<Instruction>() while (s.hasNextLine()) { val line = s.nextLine().trim() if (line.contains("fold along ")) { line.removePrefix("fold along ").split("=").let { instructions.add(Instruction(it[0], it[1].toInt())) } } else if (line.contains(",")) { line.split(",").let { points.add(Point(it[0].toInt(), it[1].toInt())) } } } var points1 = points.map { instructions[0].apply(it) }.toMutableSet() println(points.render()) instructions.forEach{ instruction -> points = points.map { instruction.apply(it) }.toMutableSet() println(points.render()) } println("${points1.size} ${points.size}") println(points.render()) } } private fun Set<Point>.render(): String { var r = StringBuilder("") for (y in 0..this.maxOf { it.y }) { for (x in 0..this.maxOf { it.x }) { r.append( if (this.contains(Point(x, y))) { "#" } else { "." }) } r.append("\n") } return r.toString() } private fun Point.foldY(y1: Int): Point { if (y == y1 || y>2*y1) { throw RuntimeException() } if (y<y1) { return this } return Point(x, 2*y1-y) } private fun Point.foldX(x1: Int): Point { if (x == x1 || x>2*x1) { throw RuntimeException() } if (x<x1) { return this } return Point(2*x1-x, y) }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
2,427
advent-of-code
Apache License 2.0
src/Lesson7StacksAndQueues/Nesting.kt
slobodanantonijevic
557,942,075
false
{"Kotlin": 50634}
import java.util.Stack /** * 100/100 * @param S * @return */ fun solution(S: String): Int { if (S.length == 0) return 1 if (S.length % 2 != 0) return 0 val stack: Stack<Char> = Stack<Char>() for (i in 0 until S.length) { val character = S[i] if (character == ')') { if (!stack.isEmpty() && stack.peek() == '(') { stack.pop() } else { return 0 } } else { stack.push(character) } } return if (stack.size == 0) { 1 } else 0 } /** * A string S consisting of N characters is called properly nested if: * * S is empty; * S has the form "(U)" where U is a properly nested string; * S has the form "VW" where V and W are properly nested strings. * For example, string "(()(())())" is properly nested but string "())" isn't. * * Write a function: * * class Solution { public int solution(String S); } * * that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise. * * For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [0..1,000,000]; * string S consists only of the characters "(" and/or ")". */
0
Kotlin
0
0
155cf983b1f06550e99c8e13c5e6015a7e7ffb0f
1,400
Codility-Kotlin
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2015/Day7.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2015 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 7: Some Assembly Required --- * https://adventofcode.com/2015/day/7 */ class Day7 : Solver { private val wires = mutableMapOf<String, Long>() override fun solve(lines: List<String>): Result { val m1 = solveFor(lines, null) wires.clear() val m2 = solveFor(lines, m1) return resultFrom(m1, m2) } private fun solveFor(lines: List<String>, overrideB: Long?): Long { val input = lines.toMutableSet() while (input.isNotEmpty()) { for (line in lines) { if (line !in input) continue val split = line.split(" -> ") assert(split.size == 2) val lhs = split[0].split(" ") val output = split[1] if (output == "b" && overrideB != null) wires[output] = overrideB else if (lhs.size == 1) { // Set value val v0 = value(lhs[0]) ?: continue wires[output] = v0 } else if (lhs.size == 2) { // Always "NOT" val v1 = value(lhs[1]) ?: continue wires[output] = v1.inv() } else if (lhs.size == 3) { // Operation with two operands val l = value(lhs[0]) ?: continue val r = value(lhs[2]) ?: continue val op = lhs[1] wires[output] = when (op) { "OR" -> l or r "AND" -> l and r "RSHIFT" -> l.shr(r.toInt()) "LSHIFT" -> l.shl(r.toInt()) else -> throw java.lang.RuntimeException("Unknown instruction ${wires[output]}") } } if (wires[output]!! < 0) wires[output] = wires[output]!! + 65536 if (wires[output]!! > 65535) wires[output] = wires[output]!! - 65536 input.remove(line) } } return wires["a"]!! } fun value(id: String): Long? { val num = id.toLongOrNull() if (num != null) return num if (id in wires) return wires[id]!! return null } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,977
euler
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2021/day13/TransparentPaper.kt
michaelbull
433,565,311
false
{"Kotlin": 162839}
package com.github.michaelbull.advent2021.day13 import com.github.michaelbull.advent2021.math.Vector2 fun Sequence<String>.toTransparentPaper(): TransparentPaper { val dots = mutableSetOf<Vector2>() val instructions = mutableListOf<FoldInstruction>() var readingInstructions = false for (line in this) { if (readingInstructions) { instructions += line.toFoldInstruction() } else if (line.isEmpty()) { readingInstructions = true } else { dots += line.toDot() } } return TransparentPaper(dots, instructions) } data class TransparentPaper( val dots: Set<Vector2>, val instructions: List<FoldInstruction> ) { private val xMin: Int get() = dots.minOf(Vector2::x) private val yMin: Int get() = dots.minOf(Vector2::y) private val xMax: Int get() = dots.maxOf(Vector2::x) private val yMax: Int get() = dots.maxOf(Vector2::y) private val xRange: IntRange get() = xMin..xMax private val yRange: IntRange get() = yMin..yMax fun fold(): TransparentPaper? { val instruction = instructions.firstOrNull() ?: return null return copy( dots = dots.mapTo(mutableSetOf()) { instruction.fold(it) }, instructions = instructions.drop(1) ) } fun foldSequence(): Sequence<TransparentPaper> { return generateSequence(this, TransparentPaper::fold) } fun decode(): String { return yRange.joinToString(separator = "\n") { y -> xRange.joinToString(separator = "") { x -> Vector2(x, y).decode() } } } private fun FoldInstruction.fold(dot: Vector2): Vector2 { return when (axis) { Axis.X -> dot.copy(x = fold(dot.x, line)) Axis.Y -> dot.copy(y = fold(dot.y, line)) } } private fun fold(dot: Int, line: Int): Int { require(dot != line) { "dots must not appear on fold line $line" } return if (dot > line) { (2 * line) - dot } else { dot } } private fun Vector2.decode(): String { return if (this in dots) "#" else "." } }
0
Kotlin
0
4
7cec2ac03705da007f227306ceb0e87f302e2e54
2,244
advent-2021
ISC License
src/main/kotlin/g2401_2500/s2499_minimum_total_cost_to_make_arrays_unequal/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2499_minimum_total_cost_to_make_arrays_unequal // #Hard #Array #Hash_Table #Greedy #Counting // #2023_07_04_Time_628_ms_(100.00%)_Space_63.2_MB_(100.00%) class Solution { fun minimumTotalCost(nums1: IntArray, nums2: IntArray): Long { val n = nums1.size val bucket = IntArray(n + 1) var max = 0 var maxKey = -1 var totalBucket = 0 var cost: Long = 0 for (i in 0 until n) { if (nums1[i] == nums2[i]) { if (++bucket[nums1[i]] > max) { max = bucket[nums1[i]] maxKey = nums1[i] } totalBucket++ cost += i.toLong() } } val requiredBucket = 2 * max if (requiredBucket > n) { return -1 } var lackBucket = requiredBucket - totalBucket var i = 0 while (i < n && lackBucket > 0) { if (nums1[i] == maxKey || nums2[i] == maxKey || nums1[i] == nums2[i]) { i++ continue } lackBucket-- cost += i.toLong() i++ } return if (lackBucket > 0) { -1 } else cost } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,252
LeetCode-in-Kotlin
MIT License
sources/dependency-resolution/src/org/jetbrains/amper/dependency/resolution/conflicts.kt
JetBrains
709,379,874
false
{"Kotlin": 952413, "Java": 184565, "Shell": 18598, "Lex": 16216, "Swift": 10408, "Ruby": 4639, "Batchfile": 4628, "Dockerfile": 838}
/* * Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.amper.dependency.resolution import org.apache.maven.artifact.versioning.ComparableVersion /** * Defines a conflict on a group of nodes with the same key and provides a way to resolve it. * Several strategies can work alongside, but only the first one is used for the conflict resolution. */ interface ConflictResolutionStrategy { /** * @return `true` if the strategy is able to find and resolve conflicts for the provided [candidates]. * They are guaranteed to have the same [Key]. */ fun isApplicableFor(candidates: List<DependencyNode>): Boolean /** * @return `true` if [candidates] have conflicts among them. */ fun seesConflictsIn(candidates: List<DependencyNode>): Boolean /** * Resolves conflicts among [candidates] by changing their state and returns `true` on success. * Returning `false` immediately interrupts the resolution process. */ fun resolveConflictsIn(candidates: List<DependencyNode>): Boolean } /** * Upgrades all dependencies to the highest version among them. * Works only with [MavenDependencyNode]s. */ class HighestVersionStrategy : ConflictResolutionStrategy { /** * @return `true` if all candidates are [MavenDependencyNode]s. */ override fun isApplicableFor(candidates: List<DependencyNode>): Boolean = candidates.all { it is MavenDependencyNode } /** * @return `true` if dependencies have different versions according to [ComparableVersion]. */ override fun seesConflictsIn(candidates: List<DependencyNode>): Boolean = candidates.map { it as MavenDependencyNode } .map { it.dependency } .distinctBy { ComparableVersion(it.version) } .size > 1 /** * Sets [MavenDependency] with the highest version and state to all candidates. Never fails. * * @return always `true` */ override fun resolveConflictsIn(candidates: List<DependencyNode>): Boolean { val mavenDependencyNodes = candidates.map { it as MavenDependencyNode } val dependency = mavenDependencyNodes.map { it.dependency }.maxWith( compareBy<MavenDependency> { ComparableVersion(it.version) }.thenBy { it.state } ) mavenDependencyNodes.forEach { it.dependency = dependency } return true } }
1
Kotlin
18
526
0e86e9b925df5c20c836209be0a134bc21316ecd
2,476
amper
Apache License 2.0
src/Day01.kt
baghaii
573,918,961
false
{"Kotlin": 11922}
fun main() { fun part1(input: List<String>): Int { val calories = mutableListOf<Int>() var calorieCount = 0 var maxCalories = 0 input.forEach { if (it.isNotEmpty()) { calorieCount += it.toInt() } else { if (calorieCount > maxCalories) { maxCalories = calorieCount } calories.add(calorieCount) calorieCount = 0 } } return maxCalories } fun part2(input: List<String>): Int { val calories = mutableListOf<Int>() var calorieCount = 0 var maxCalories = 0 input.forEach { if (it.isNotEmpty()) { calorieCount += it.toInt() } else { if (calorieCount > maxCalories) { maxCalories = calorieCount } calories.add(calorieCount) calorieCount = 0 } } calories.sortDescending() return calories.take(3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c66dae6569f4b269d1cad9bf901e0a686437469
1,177
AdventOfCode2022
Apache License 2.0
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTBucketSorter.kt
chrisfang6
105,401,243
false
{"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403}
package net.chris.lib.algorithms.sort.kotlin import java.util.* /** * Bucket sort. * * @param <T> </T> */ abstract class KTBucketSorter : KTSorter() { private var buckets: MutableList<Bucket>? = null override fun subSort(array: IntArray) { if (array == null) { return } createBuckets() for (i in array.indices) { for (j in buckets!!.indices) { if (buckets!![j].inBucket(array[i])) { buckets!![j].add(array[i]) break } } } val result = array.copyOf() var index = 0 for (j in buckets!!.indices) { val bucketArray = buckets!![j].sort() for (i in bucketArray.indices) { result[index] = bucketArray[i] index++ } } for (i in result.indices) { array[i] = result[i] } } private fun createBuckets() { val size = demarcations.size + 1 buckets = ArrayList(size) var i = 0 while (i < demarcations.size) { val left = demarcations[i] val right = demarcations[i + 1] buckets!!.add(Bucket(left, right)) i += 2 } } protected abstract val sorter: KTSorter protected abstract val demarcations: IntArray /** * */ inner class Bucket constructor(private val left: Int, private val right: Int) { private val list = mutableListOf<Int>() fun inBucket(element: Int): Boolean { return compareTo(element, left) >= 0 && compareTo(element, right) <= 0 } fun add(element: Int) { list.add(element) } fun sort(): IntArray { return sorter.sort(list.toList()).toIntArray() } } }
0
Java
0
0
1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0
1,866
sort
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReverseVowels.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 /** * 345. Reverse Vowels of a String * https://leetcode.com/problems/reverse-vowels-of-a-string/ */ fun interface ReverseVowels { operator fun invoke(s: String): String } class ReverseVowelsTwoPointers : ReverseVowels { companion object { private const val VOWELS = "aeiouAEIOU" } override operator fun invoke(s: String): String { if (s.isEmpty()) return s val chars: CharArray = s.toCharArray() var start = 0 var end: Int = s.length - 1 while (start < end) { while (start < end && !VOWELS.contains(chars[start].toString() + "")) { start++ } while (start < end && !VOWELS.contains(chars[end].toString() + "")) { end-- } val temp = chars[start] chars[start] = chars[end] chars[end] = temp start++ end-- } return String(chars) } } class ReverseVowelsSet : ReverseVowels { override operator fun invoke(s: String): String { val set: Set<Char> = HashSet(listOf('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')) val arr: CharArray = s.toCharArray() var left = 0 var right = arr.size - 1 while (left < right) { if (!set.contains(arr[left])) { left++ } else if (!set.contains(arr[right])) { right-- } else { val tmp = arr[left] arr[left] = arr[right] arr[right] = tmp left++ right-- } } return String(arr) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,301
kotlab
Apache License 2.0
app/src/main/kotlin/me/mataha/misaki/solutions/adventofcode/aoc2020/d01/Day.kt
mataha
302,513,601
false
{"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90}
package me.mataha.misaki.solutions.adventofcode.aoc2020.d01 import me.mataha.misaki.domain.adventofcode.AdventOfCode import me.mataha.misaki.domain.adventofcode.AdventOfCodeDay /** See the puzzle's full description [here](https://adventofcode.com/2020/day/1). */ @AdventOfCode("Report Repair", 2020, 1) class ReportRepair : AdventOfCodeDay<List<Int>, Int>() { override fun parse(input: String): List<Int> = input.lines().map { string -> string.toInt() } override fun solvePartOne(input: List<Int>): Int { val numbers = mutableSetOf<Int>() for (number in input) { val diff = YEAR - number if (diff in numbers) { return number * diff } else { numbers += number } } return INVALID_EXPENSE_REPORT } override fun solvePartTwo(input: List<Int>): Int { val numbers = mutableSetOf<Int>() val results = mutableSetOf<Result<Int>>() for (number in input) { val diff = YEAR - number for (result in results) { if (result.sum == diff) { return number * result.product } } for (entry in numbers) { results += Result(number + entry, number * entry) } numbers += number } return INVALID_EXPENSE_REPORT } companion object { const val INVALID_EXPENSE_REPORT = -1 private const val YEAR = 2020 } } private data class Result<T : Number>(val sum: T, val product: T)
0
Kotlin
0
0
748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685
1,603
misaki
MIT License
src/leetcodeProblem/leetcode/editor/en/SingleNumberIii.kt
faniabdullah
382,893,751
false
null
//Given an integer array nums, in which exactly two elements appear only once //and all the other elements appear exactly twice. Find the two elements that //appear only once. You can return the answer in any order. // // You must write an algorithm that runs in linear runtime complexity and uses //only constant extra space. // // // Example 1: // // //Input: nums = [1,2,1,3,2,5] //Output: [3,5] //Explanation: [5, 3] is also a valid answer. // // // Example 2: // // //Input: nums = [-1,0] //Output: [-1,0] // // // Example 3: // // //Input: nums = [0,1] //Output: [1,0] // // // // Constraints: // // // 2 <= nums.length <= 3 * 10⁴ // -2³¹ <= nums[i] <= 2³¹ - 1 // Each integer in nums will appear twice, only two integers will appear once. // // Related Topics Array Bit Manipulation 👍 3157 👎 167 package leetcodeProblem.leetcode.editor.en class SingleNumberIii { fun solution() { } //below code will be used for submission to leetcode (using plugin of course) //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun singleNumber(nums: IntArray): IntArray { var aXORb = 0 for (n in nums) { aXORb = aXORb.xor(n) } val rightSetBit = aXORb and -aXORb var a = 0 for (n in nums) { if (n and rightSetBit != 0) { a = a.xor(n) } } return intArrayOf(a, aXORb xor a) } } //leetcode submit region end(Prohibit modification and deletion) } fun main() {}
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,631
dsa-kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumIdenticalPairs.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 fun interface AbstractNumIdenticalPairs { operator fun invoke(arr: IntArray): Int } class NumIdenticalPairsNaive : AbstractNumIdenticalPairs { override operator fun invoke(arr: IntArray): Int { var count = 0 for (i in 0 until arr.size - 1) { var j = i + 1 while (j < arr.size) { if (arr[i] == arr[j]) { count++ } j++ } } return count } } class NumIdenticalPairsMap : AbstractNumIdenticalPairs { override operator fun invoke(arr: IntArray): Int { val map: MutableMap<Int, Int> = HashMap() var count = 0 for (num in arr) { count += map.getOrDefault(num, 0) map[num] = map.getOrDefault(num, 0) + 1 } return count } } class NumIdenticalPairsSort : AbstractNumIdenticalPairs { override operator fun invoke(arr: IntArray): Int { arr.sort() var count = 0 var i = 0 for (j in 1 until arr.size) { if (arr[j] == arr[i]) { count += j - i } else { i = j } } return count } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,852
kotlab
Apache License 2.0
2020/src/main/kotlin/sh/weller/adventofcode/twentytwenty/Day12.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.adventofcode.twentytwenty import kotlin.math.absoluteValue fun List<String>.day12Part2(): Int { var shipCoordinates = Coordinates(0, 0) var waypointCoordinates = Coordinates(10, 1) this.map { it.toInstruction() } .forEach { instruction -> when (instruction.getOperation()) { 'E' -> waypointCoordinates = waypointCoordinates.addX(instruction.getValue()) 'S' -> waypointCoordinates = waypointCoordinates.subtractY(instruction.getValue()) 'W' -> waypointCoordinates = waypointCoordinates.subtractX(instruction.getValue()) 'N' -> waypointCoordinates = waypointCoordinates.addY(instruction.getValue()) 'L', 'R' -> waypointCoordinates = waypointCoordinates.part2Rotate(instruction) 'F' -> shipCoordinates = shipCoordinates.moveInDirection(waypointCoordinates, instruction.getValue()) } } return shipCoordinates.getX().absoluteValue + shipCoordinates.getY().absoluteValue } private fun Coordinates.part2Rotate(instruction: Instruction): Coordinates = when ("${instruction.first}${instruction.second}") { "L90", "R270" -> Coordinates(-second, first) "L180", "R180" -> Coordinates(-first, -second) "R90", "L270" -> Coordinates(second, -first) else -> { throw IllegalArgumentException() } } private fun Coordinates.moveInDirection(coordinates: Coordinates, multiplier: Int): Coordinates = this.copy(this.getX() + (coordinates.getX() * multiplier), this.getY() + (coordinates.getY() * multiplier)) fun List<String>.day12Part1(): Int { var shipCoordinates = Coordinates(0, 0) var direction = 'E' this.map { it.toInstruction() } .forEach { instruction -> when (instruction.getOperation()) { 'E' -> shipCoordinates = shipCoordinates.addX(instruction.getValue()) 'S' -> shipCoordinates = shipCoordinates.subtractY(instruction.getValue()) 'W' -> shipCoordinates = shipCoordinates.subtractX(instruction.getValue()) 'N' -> shipCoordinates = shipCoordinates.addY(instruction.getValue()) 'L', 'R' -> direction = direction.rotate(instruction) 'F' -> { when (direction) { 'E' -> shipCoordinates = shipCoordinates.addX(instruction.getValue()) 'S' -> shipCoordinates = shipCoordinates.subtractY(instruction.getValue()) 'W' -> shipCoordinates = shipCoordinates.subtractX(instruction.getValue()) 'N' -> shipCoordinates = shipCoordinates.addY(instruction.getValue()) } } } } return shipCoordinates.getX().absoluteValue + shipCoordinates.getY().absoluteValue } private fun Char.rotate(instruction: Instruction): Char = when ("${instruction.getOperation()}${instruction.getValue()}") { "L90", "R270" -> when (this) { 'E' -> 'N' 'S' -> 'E' 'W' -> 'S' 'N' -> 'W' else -> throw IllegalArgumentException() } "L180", "R180" -> when (this) { 'E' -> 'W' 'S' -> 'N' 'W' -> 'E' 'N' -> 'S' else -> throw IllegalArgumentException() } "R90", "L270" -> when (this) { 'E' -> 'S' 'S' -> 'W' 'W' -> 'N' 'N' -> 'E' else -> throw IllegalArgumentException() } else -> throw IllegalArgumentException() } private typealias Coordinates = Pair<Int, Int> private fun Coordinates.addX(value: Int): Coordinates = this.copy(first = this.first + value) private fun Coordinates.subtractX(value: Int): Coordinates = this.copy(first = this.first - value) private fun Coordinates.addY(value: Int): Coordinates = this.copy(second = this.second + value) private fun Coordinates.subtractY(value: Int): Coordinates = this.copy(second = this.second - value) private fun Coordinates.getX() = this.first private fun Coordinates.getY() = this.second private typealias Instruction = Pair<Char, Int> private fun String.toInstruction(): Instruction = Instruction(this[0], this.drop(1).toInt()) private fun Instruction.getOperation() = this.first private fun Instruction.getValue() = this.second
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
4,421
AdventOfCode
MIT License
jvm/src/main/kotlin/io/prfxn/aoc2021/day02.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Dive! (https://adventofcode.com/2021/day/2) package io.prfxn.aoc2021 fun main() { val lines = textResourceReader("input/02.txt").useLines { ls -> ls.map { ln -> ln.split(" ").let { it[0] to it[1].toInt() } }.toList() } val answer1 = lines .fold(0 to 0) { (depth, distance), (key, value) -> when (key) { "forward" -> depth to (distance + value) "down" -> (depth + value) to distance "up" -> (depth - value) to distance else -> throw IllegalArgumentException() } } .let { (depth, distance) -> depth * distance } val answer2 = lines .fold(Triple(0, 0 ,0)) { (aim, depth, distance), (key, value) -> when (key) { "forward" -> Triple(aim, depth + (aim * value), distance + value) "down" -> Triple(aim + value, depth, distance) "up" -> Triple(aim - value, depth, distance) else -> throw IllegalArgumentException() } } .let { (_, depth, distance) -> depth * distance } sequenceOf(answer1, answer2).forEach(::println) } /** output * 1815044 * 1739283308 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,262
aoc2021
MIT License
kotlin/src/com/daily/algothrim/leetcode/CheckPossibility.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 665. 非递减数列 * * 给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。 * 我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。 */ class CheckPossibility { companion object { @JvmStatic fun main(args: Array<String>) { println(CheckPossibility().solution(intArrayOf(4, 2, 3))) println(CheckPossibility().solution(intArrayOf(4, 2, 1))) println(CheckPossibility().solution(intArrayOf(4, 2))) println(CheckPossibility().solution(intArrayOf(2))) println(CheckPossibility().solution(intArrayOf(3, 4, 2, 3))) } } // 输入: nums = [4,2,3] // 输出: true // 解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 fun solution(nums: IntArray): Boolean { val size = nums.size var adjustTime = 0 for (i in 0 until size - 1) { val x = nums[i] val y = nums[i + 1] if (x > y) { adjustTime++ if (adjustTime > 1) return false if (i > 0 && y < nums[i - 1]) { nums[i + 1] = x } } } return true } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,427
daily_algorithm
Apache License 2.0
src/main/kotlin/org/olafneumann/regex/generator/regex/RecognizerCombiner.kt
wasi-master
406,654,940
true
{"Kotlin": 80063, "HTML": 17238, "CSS": 2167, "Dockerfile": 201, "JavaScript": 153}
package org.olafneumann.regex.generator.regex object RecognizerCombiner { fun combineMatches( inputText: String, selectedMatches: Collection<RecognizerMatch>, options: Options ): RegularExpression { val rangesToMatches = selectedMatches.flatMap { match -> match.ranges .mapIndexed { index, range -> RegularExpressionPart(range, match.patterns[index], match = match) } } .sortedBy { it.range.first } .toList() return if (rangesToMatches.isEmpty()) { if (options.onlyPatterns) { RegularExpression( listOf(RegularExpressionPart(IntRange(0, 2), ".*", title = "anything")) .addWholeLineMatchingStuff(options) ) } else { val regex = inputText.escapeForRegex() RegularExpression( listOf(RegularExpressionPart(IntRange(0, regex.length), regex, inputText)) .addWholeLineMatchingStuff(options) ) } } else { // at this point we know, that rangesToMatches is not empty! val hasContentBeforeFirstMatch = rangesToMatches.first().range.first > 0 val hasContentAfterLastMatch = rangesToMatches.last().range.last < inputText.length - 1 val firstPart = when { hasContentBeforeFirstMatch && options.onlyPatterns -> RegularExpressionPart( IntRange(0, rangesToMatches.first().range.first - 1), ".*", title = "anything" ) hasContentBeforeFirstMatch && !options.onlyPatterns -> { val length = rangesToMatches.first().range.first val text = inputText.substring(0, length) RegularExpressionPart(IntRange(0, length - 1), text.escapeForRegex(), text) } else -> null } val lastPart = when { hasContentAfterLastMatch && options.onlyPatterns -> RegularExpressionPart( IntRange(0, rangesToMatches.last().range.last), ".*", title = "anything" ) hasContentAfterLastMatch && !options.onlyPatterns -> { val text = inputText.substring(rangesToMatches.last().range.last + 1) RegularExpressionPart(IntRange(0, rangesToMatches.last().range.last), text.escapeForRegex(), text) } else -> null } combineParts(firstPart, rangesToMatches, lastPart, inputText, options) } } private fun combineParts( firstPart: RegularExpressionPart?, rangesToMatches: List<RegularExpressionPart>, lastPart: RegularExpressionPart?, inputText: String, options: Options ): RegularExpression { val parts = mutableListOf<RegularExpressionPart>() if (options.matchWholeLine || firstPart?.fromInputText == true) { firstPart?.let { parts.add(it) } } for (i in rangesToMatches.indices) { if (i > 0) { getPartBetween(inputText, rangesToMatches[i - 1], rangesToMatches[i], options) ?.let { parts.add(it) } } parts.add(rangesToMatches[i]) } if (options.matchWholeLine || lastPart?.fromInputText == true) { lastPart?.let { parts.add(it) } } return RegularExpression(parts.addWholeLineMatchingStuff(options)) } private fun getPartBetween( inputText: String, first: RegularExpressionPart, second: RegularExpressionPart, options: Options ): RegularExpressionPart? { val rangeBetween = IntRange(first.range.last + 1, second.range.first - 1) if (!rangeBetween.isEmpty()) { return if (options.onlyPatterns) { RegularExpressionPart(rangeBetween, "*.") } else { val text = inputText.substring(rangeBetween) RegularExpressionPart(rangeBetween, text.escapeForRegex(), text) } } return null } private fun List<RegularExpressionPart>.addWholeLineMatchingStuff(options: Options): List<RegularExpressionPart> { return if (options.matchWholeLine) { val list = mutableListOf<RegularExpressionPart>() list.add(RegularExpressionPart(IntRange.EMPTY, pattern = "^", title = "Start of input")) list.addAll(this) list.add(RegularExpressionPart(IntRange.EMPTY, pattern = "$", title = "End of input")) list } else { this } } data class Options( val onlyPatterns: Boolean = DEFAULT_ONLY_PATTERN, val matchWholeLine: Boolean = DEFAULT_MATCH_WHOLE_LINE, val caseInsensitive: Boolean = DEFAULT_CASE_INSENSITIVE, val dotMatchesLineBreaks: Boolean = DEFAULT_DOT_MATCHES_LINE_BREAKS, val multiline: Boolean = DEFAULT_MULTILINE ) { companion object { private const val DEFAULT_ONLY_PATTERN = false private const val DEFAULT_MATCH_WHOLE_LINE = false private const val DEFAULT_CASE_INSENSITIVE = true private const val DEFAULT_DOT_MATCHES_LINE_BREAKS = false private const val DEFAULT_MULTILINE = false fun parseSearchParams(onlyPatternFlag: String?, matchWholeLineFlag: String?, regexFlags: String?): Options { val onlyPatterns = onlyPatternFlag?.let { it.toBoolean() } ?: DEFAULT_ONLY_PATTERN val matchWholeLine = matchWholeLineFlag?.let { it.toBoolean() } ?: DEFAULT_MATCH_WHOLE_LINE val caseInsensitive = regexFlags?.contains(char = 'i', ignoreCase = true) ?: DEFAULT_CASE_INSENSITIVE val dotMatchesLineBreaks = regexFlags?.contains(char = 's', ignoreCase = true) ?: DEFAULT_DOT_MATCHES_LINE_BREAKS val multiline = regexFlags?.contains(char = 'm', ignoreCase = true) ?: DEFAULT_MULTILINE return Options( onlyPatterns = onlyPatterns, matchWholeLine = matchWholeLine, caseInsensitive = caseInsensitive, dotMatchesLineBreaks = dotMatchesLineBreaks, multiline = multiline ) } } } data class RegularExpressionPart( val range: IntRange, val pattern: String, val originalText: String? = null, val match: RecognizerMatch? = null, val title: String? = null ) { val fromInputText get() = originalText != null } data class RegularExpression( val parts: Collection<RegularExpressionPart> ) { val pattern get() = parts.joinToString(separator = "") { it.pattern } } }
0
Kotlin
0
1
1c1d8035ddc2afa3ccf4f0709ccdfe57a0200b63
6,985
regex-generator
MIT License
sykdomstidslinje/src/main/kotlin/no/nav/helse/tournament/DagTurnering.kt
navikt
211,019,921
false
null
package no.nav.helse.tournament import no.nav.helse.sykdomstidslinje.dag.Dag import no.nav.helse.sykdomstidslinje.dag.Ubestemtdag internal val dagTurnering = DagTurnering() internal class DagTurnering(val source: String = "/dagturnering.csv") { internal val strategies: Map<Dag.Nøkkel, Map<Dag.Nøkkel, Strategy>> = readStrategies() fun slåss(venstre: Dag, høyre: Dag): Dag { val leftKey = venstre.nøkkel() val rightKey = høyre.nøkkel() return strategies[leftKey]?.get(rightKey)?.decide(venstre, høyre) ?: strategies[rightKey]?.get(leftKey)?.decide(høyre, venstre) ?: throw RuntimeException("Fant ikke strategi for $leftKey + $rightKey") } private fun readStrategies(): Map<Dag.Nøkkel, Map<Dag.Nøkkel, Strategy>> { val csv = this::class.java.getResourceAsStream(source) .bufferedReader(Charsets.UTF_8) .readLines() .map { it.split(",") } .map { it.first() to it.drop(1) } val (_, columnHeaders) = csv.first() return csv .drop(1) .map { (key, row) -> enumValueOf<Dag.Nøkkel>(key) to row .mapIndexed { index, cell -> columnHeaders[index] to cell } .filter { (_, cell) -> cell.isNotBlank() } .map { (columnHeader, cell) -> enumValueOf<Dag.Nøkkel>(columnHeader) to strategyFor(cell) } .toMap() } .toMap() } private fun strategyFor(cellValue: String) = when (cellValue) { "U" -> Undecided "R" -> Row "C" -> Column "X" -> Impossible "L" -> Latest "LR" -> LatestOrRow "LC" -> LatestOrColumn else -> throw RuntimeException("$cellValue is not a known strategy for deciding between days") } } internal sealed class Strategy { abstract fun decide(row: Dag, column: Dag): Dag } internal object Undecided : Strategy() { override fun decide(row: Dag, column: Dag): Dag = Ubestemtdag(row, column) } internal object Row : Strategy() { override fun decide(row: Dag, column: Dag): Dag = row.erstatter(column) } internal object Column : Strategy() { override fun decide(row: Dag, column: Dag): Dag = column.erstatter(row) } internal object Latest : Strategy() { override fun decide(row: Dag, column: Dag): Dag = when { row.sisteHendelse() == column.sisteHendelse() -> throw IllegalStateException("Strategien latest støtter ikke sammenliging av eventer med samme tidspunkt. (row: $row, column: $column)") row.sisteHendelse() > (column.sisteHendelse()) -> row.erstatter(column) else -> column.erstatter(row) } } internal object LatestOrRow : Strategy() { override fun decide(row: Dag, column: Dag): Dag = if (row.sisteHendelse() >= (column.sisteHendelse())) row.erstatter(column) else column.erstatter(row) } internal object LatestOrColumn : Strategy() { override fun decide(row: Dag, column: Dag): Dag = if (row.sisteHendelse() > (column.sisteHendelse())) row.erstatter(column) else column.erstatter(row) } internal object Impossible : Strategy() { override fun decide(row: Dag, column: Dag): Dag = throw RuntimeException("Nøklene ${row.nøkkel()} + ${column.nøkkel()} er en ugyldig sammenligning") }
0
Kotlin
0
1
f9e93b54da76aa03c74e2b650f5cdcc2077d73f4
3,424
helse-sykdomstidslinje
MIT License
app/src/main/java/eu/kanade/tachiyomi/data/library/LibraryUpdateRanker.kt
Rattlehead15
330,245,026
true
null
package eu.kanade.tachiyomi.data.library import eu.kanade.tachiyomi.data.database.models.Manga import java.util.Collections import kotlin.Comparator import kotlin.math.abs /** * This class will provide various functions to rank manga to efficiently schedule manga to update. */ object LibraryUpdateRanker { val rankingScheme = listOf( (this::lexicographicRanking)(), (this::latestFirstRanking)(), (this::nextFirstRanking)() ) /** * Provides a total ordering over all the Mangas. * * Orders the manga based on the distance between the next expected update and now. * The comparator is reversed, placing the smallest (and thus closest to updating now) first. */ fun nextFirstRanking(): Comparator<Manga> { val time = System.currentTimeMillis() return Collections.reverseOrder( Comparator { mangaFirst: Manga, mangaSecond: Manga -> compareValues(abs(mangaSecond.next_update - time), abs(mangaFirst.next_update - time)) } ) } /** * Provides a total ordering over all the [Manga]s. * * Assumption: An active [Manga] mActive is expected to have been last updated after an * inactive [Manga] mInactive. * * Using this insight, function returns a Comparator for which mActive appears before mInactive. * @return a Comparator that ranks manga based on relevance. */ private fun latestFirstRanking(): Comparator<Manga> = Comparator { first: Manga, second: Manga -> compareValues(second.last_update, first.last_update) } /** * Provides a total ordering over all the [Manga]s. * * Order the manga lexicographically. * @return a Comparator that ranks manga lexicographically based on the title. */ private fun lexicographicRanking(): Comparator<Manga> = Comparator { first: Manga, second: Manga -> compareValues(first.title, second.title) } }
9
Kotlin
4
61
e64143ef4a3734ba60334677be0b5e70074782ec
2,024
tachiyomiOCR
Apache License 2.0
2021/kotlin/me/brandonbuck/adventofcode/binarydiagnostic/Solution2.kt
bbuck
437,605,794
false
{"Kotlin": 5823, "Starlark": 3013}
package me.brandonbuck.adventofcode.binarydiagnostic import me.brandonbuck.adventofcode.common.io.readAllFromStandardIn fun main() { val inputs = readAllFromStandardIn() println(solution2(inputs)) } fun solution2(inputs: List<String>): Int { val binLength = inputs[0].length var o2List = inputs; var co2List = inputs; var i = 0 while (o2List.size > 1 && i < binLength) { var pair = Pair(0, 0) o2List.forEach { if (it[i] == '0') { pair = Pair(pair.first + 1, pair.second) } else { pair = Pair(pair.first, pair.second + 1) } } val target = if (pair.first > pair.second) '0' else '1' o2List = o2List.filter { it[i] == target } ++i } i = 0 while (co2List.size > 1 && i < binLength) { var pair = Pair(0, 0) co2List.forEach { if (it[i] == '0') { pair = Pair(pair.first + 1, pair.second) } else { pair = Pair(pair.first, pair.second + 1) } } val target = if (pair.second >= pair.first) '0' else '1' co2List = co2List.filter { it[i] == target } ++i } val o2N = o2List[0].toInt(2) val co2N = co2List[0].toInt(2) return o2N * co2N }
0
Kotlin
0
0
c06cbc73b6fbb848f3f8a2327a60f40d69a5f4fa
1,115
advent-of-code
MIT License
src/main/kotlin/us/sodiumlabs/electorate/sim/RegretMetrics.kt
napentathol
130,545,021
false
null
package us.sodiumlabs.electorate.sim import com.google.common.base.Strings import us.sodiumlabs.electorate.BigDecimalAverageCollector import java.math.BigDecimal import java.util.function.Function open class RegretMetrics( val rawUtility: BigDecimalWrapper, val regret: BigDecimalWrapper, val normalizedRegret: BigDecimalWrapper, val indeterminate: Boolean = false ) { override fun toString(): String { return if (indeterminate) { "election was indeterminate" } else { "raw utility: ${padBigDecimal(rawUtility)} " + "regret: ${padBigDecimal(regret)} " + "normalized regret: $normalizedRegret" } } } fun indeterminate(): RegretMetrics { return RegretMetrics(nan(), nan(), nan(), true) } class RegretStatistics(private val name: ElectoralSystemName, regretMetrics: Collection<RegretMetrics>) { private val rawUtilityStatistics: Statistics private val regretStatistics: Statistics private val normalizedRegretStatistics: Statistics private val indeterminateFraction: BigDecimal init { rawUtilityStatistics = Statistics(regretMetrics, false) { r -> r.rawUtility } regretStatistics = Statistics(regretMetrics) { r -> r.regret } normalizedRegretStatistics = Statistics(regretMetrics) { r -> r.normalizedRegret } var indeterminate = 0 regretMetrics.filter { it.indeterminate }.forEach { indeterminate++ } indeterminateFraction = BigDecimal(indeterminate).divide(BigDecimal(regretMetrics.size)) } override fun toString(): String { return "= $name =\n" + "== raw utility ==\n" + "$rawUtilityStatistics\n" + "== regret ==\n" + "$regretStatistics\n" + "== normalized regret ==\n" + "$normalizedRegretStatistics\n" + "== indeterminate fraction ==\n" + indeterminateFraction } } class Statistics( regretMetrics: Collection<RegretMetrics>, nanHigh: Boolean = true, metricAccessor: Function<RegretMetrics, BigDecimalWrapper> ) { private val p0: BigDecimalWrapper private val p10: BigDecimalWrapper private val p50: BigDecimalWrapper private val p90: BigDecimalWrapper private val p100: BigDecimalWrapper private val mean: BigDecimalWrapper init { val sortedMetrics = regretMetrics.sortedWith { left, right -> metricAccessor.apply(left).compare(metricAccessor.apply(right), nanHigh) } p0 = metricAccessor.apply(sortedMetrics[0]) p10 = metricAccessor.apply(sortedMetrics[sortedMetrics.size / 10]) p50 = metricAccessor.apply(sortedMetrics[sortedMetrics.size / 2]) p90 = metricAccessor.apply(sortedMetrics[sortedMetrics.size - sortedMetrics.size / 10]) p100 = metricAccessor.apply(sortedMetrics[sortedMetrics.lastIndex]) mean = regretMetrics.stream() .map { r -> metricAccessor.apply(r) } .collect(BigDecimalAverageCollector()) } override fun toString(): String { return "mean: ${padBigDecimal(mean)} " + "p0: ${padBigDecimal(p0)} " + "p10: ${padBigDecimal(p10)} " + "p50: ${padBigDecimal(p50)} " + "p90: ${padBigDecimal(p90)} " + "p100: ${padBigDecimal(p100)}" } } fun padBigDecimal(b: BigDecimalWrapper): String { return Strings.padEnd("$b;", 13, ' ') }
0
Kotlin
0
1
ad82e05775861030c40e0c39384016de34e69275
3,463
electorate
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountNodes.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 /** * 222. Count Complete Tree Nodes * @see <a href="https://leetcode.com/problems/count-complete-tree-nodes/">Source</a> */ fun interface CountNodes { operator fun invoke(root: TreeNode?): Int } class CountNodesBitrise : CountNodes { override operator fun invoke(root: TreeNode?): Int { val h = root.height() return if (h < 0) { 0 } else if (root?.right.height() == h - 1) { (1 shl h) + invoke(root?.right) } else { 1 shl h - 1 + invoke(root?.left) } } } class CountNodesIterative : CountNodes { override operator fun invoke(root: TreeNode?): Int { var nodes = 0 var tree = root var h: Int = root.height() while (tree != null) { if (tree.right.height() == h - 1) { nodes += 1 shl h tree = tree.right } else { nodes += 1 shl h - 1 tree = tree.left } h-- } return nodes } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,676
kotlab
Apache License 2.0
src/main/kotlin/g1801_1900/s1801_number_of_orders_in_the_backlog/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1801_1900.s1801_number_of_orders_in_the_backlog // #Medium #Array #Heap_Priority_Queue #Simulation // #2023_06_19_Time_668_ms_(100.00%)_Space_101.6_MB_(100.00%) import java.util.PriorityQueue class Solution { private class Order(var price: Int, var qty: Int) fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int { val sell = PriorityQueue( compareBy { a: Order -> a.price } ) val buy = PriorityQueue { a: Order, b: Order -> b.price - a.price } for (order in orders) { val price = order[0] var amount = order[1] val type = order[2] if (type == 0) { while (sell.isNotEmpty() && sell.peek().price <= price && amount > 0) { val ord = sell.peek() val toRemove = amount.coerceAtMost(ord.qty) ord.qty -= toRemove amount -= toRemove if (ord.qty == 0) { sell.poll() } } if (amount > 0) { buy.add(Order(price, amount)) } } else { while (buy.isNotEmpty() && buy.peek().price >= price && amount > 0) { val ord = buy.peek() val toRemove = amount.coerceAtMost(ord.qty) ord.qty -= toRemove amount -= toRemove if (ord.qty == 0) { buy.poll() } } if (amount > 0) { sell.add(Order(price, amount)) } } } var sellCount: Long = 0 for (ord in sell) { sellCount += ord.qty.toLong() } var buyCount: Long = 0 for (ord in buy) { buyCount += ord.qty.toLong() } val total = sellCount + buyCount return (total % 1000000007L).toInt() } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,006
LeetCode-in-Kotlin
MIT License
src/com/kingsleyadio/adventofcode/y2022/day01/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day01 import com.kingsleyadio.adventofcode.util.readInput fun main() { part1() part2() } fun part1() { var max = 0 var sum = 0 readInput(2022, 1).forEachLine { line -> if (line.isEmpty()) { max = maxOf(max, sum) sum = 0 } else sum += line.toInt() } println(max) } fun part2() { val top = IntArray(3) fun place(number: Int) { if (number > top[0]) { top[2] = top[1] top[1] = top[0] top[0] = number } else if (number > top[1]) { top[2] = top[1] top[1] = number } else if (number > top[2]) { top[2] = number } } var sum = 0 readInput(2022, 1).forEachLine { line -> if (line.isEmpty()) { place(sum) sum = 0 } else sum += line.toInt() } println(top.sum()) // Could also be as simple as sorted().takeLast(3) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
995
adventofcode
Apache License 2.0
src/Day03.kt
RandomUserIK
572,624,698
false
{"Kotlin": 21278}
private const val GROUP_SIZE = 3 private val PRIORITIES = (('a'..'z') + ('A'..'Z')).mapIndexed { idx, c -> c to (idx + 1) }.toMap() fun main() { fun part1(input: List<String>): Int = input .map { val (first, second) = it.chunked(it.length / 2) Pair(first.toSet(), second.toSet()) } .fold(0) { acc, (left, right) -> acc + (PRIORITIES[(left intersect right).first()] ?: 0) } fun part2(input: List<String>): Int = input .chunked(GROUP_SIZE) .map { (first: String, second: String, third: String) -> (first.toSet() intersect second.toSet() intersect third.toSet()).first() } .fold(0) { acc, badge -> acc + (PRIORITIES[badge] ?: 0) } val input = readInput("inputs/day03_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f22f10da922832d78dd444b5c9cc08fadc566b4b
763
advent-of-code-2022
Apache License 2.0
src/main/aoc2021/Day19.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 import java.lang.Integer.max import kotlin.math.abs // typealias is global, so use a name that won't collide with coordinates in other puzzles /** * Each beacon position is just a list of three coordinates. Due to scanner alignment issues different * indexes in the list may refer to different axis between beacons in different scanners. */ typealias Coordinate21d19 = List<Int> class Day19(input: List<String>) { companion object { operator fun Coordinate21d19.minus(other: Coordinate21d19): Coordinate21d19 = zip(other) { a, b -> a - b } operator fun Coordinate21d19.plus(other: Coordinate21d19): Coordinate21d19 = zip(other) { a, b -> a + b } fun Coordinate21d19.abs(): Coordinate21d19 = map { abs(it) } // Distance to another coordinate as a set, as order must not be considered when comparing distances // between beacons in different scanners. fun Coordinate21d19.distanceTo(other: Coordinate21d19) = (this - other).abs().toSet() fun Coordinate21d19.manhattanDistanceTo(other: Coordinate21d19) = (this - other).abs().sum() } data class Scanner(val beacons: List<Coordinate21d19>) { // the offset of this scanner compared to the reference scanner lateinit var scannerOffset: Coordinate21d19 // The positions in the beacons using the reference scanners coordinate system lateinit var realPositions: List<Coordinate21d19> // The distance between all beacons in the scanner val allDistances = beacons.map { beacon -> buildSet { for (i in beacons.indices) { val distance = beacon.distanceTo(beacons[i]) add(distance) } } } /** * Align this scanner based on the difference between the same two beacons in two different scanners. * * It also uses the position of one beacon in the two scanners to find the offset between the scanners * to be able to calculate the true positions of all the beacons in this scanner in the reference scanner's * coordinate system. * * Uses the distances between the beacons to find the correct alignment. * @param expected the expected result when taking the difference of the coordinates in the coordinate system * of the reference scanner * @param actual the actual result when using this scanners coordinate system. The order and sign of the * entries in actual may be different compared to expected. * @param alignedPosition the position of one beacon using aligned coordinates * @param unalignedPosition the position of the same beacon in this scanners coordinate system. */ fun alignScanner( expected: Coordinate21d19, actual: Coordinate21d19, alignedPosition: Coordinate21d19, unalignedPosition: Coordinate21d19 ) { val expectedMagnitudes = expected.abs() val actualMagnitudes = actual.abs() // axisMapping[0] is the coordinate that corresponds to the first coordinate in the reference scanner val axisMapping = listOf( actualMagnitudes.indexOf(expectedMagnitudes[0]), actualMagnitudes.indexOf(expectedMagnitudes[1]), actualMagnitudes.indexOf(expectedMagnitudes[2]) ) // align the axis without regards to sign val axisAligned = realignPosition(actual, axisMapping, listOf(1, 1, 1)) val signMapping = axisAligned.zip(expected) { a, b -> if (a == b) 1 else -1 } // Find the scanner offset compared to the reference scanner scannerOffset = alignedPosition - realignPosition(unalignedPosition, axisMapping, signMapping) realPositions = beacons.map { realignPosition(it, axisMapping, signMapping) + scannerOffset } } // Realign the given position using the provided axes and sign mappings. private fun realignPosition( pos: Coordinate21d19, axisMapping: List<Int>, signMapping: List<Int> ): Coordinate21d19 { return listOf( pos[axisMapping[0]] * signMapping[0], pos[axisMapping[1]] * signMapping[1], pos[axisMapping[2]] * signMapping[2] ) } } private val scanners: List<Scanner> private val allBeacons = mutableSetOf<Coordinate21d19>() init { val lineIterator = input.iterator() val scanners = mutableListOf<Scanner>() while (lineIterator.hasNext()) { lineIterator.next() // skip scanner name, it's of no interest val beacons: List<Coordinate21d19> = buildList { for (line in lineIterator) { if (line.isEmpty()) { break } add(line.split(",").map { it.toInt() }) } } scanners.add(Scanner(beacons)) } // Initialize the reference scanner scanners[0].apply { scannerOffset = listOf(0, 0, 0) realPositions = beacons } this.scanners = scanners alignAllScanners() } // Aligns two scanners with each other. Identifying if two scanners can be aligned // is done by measuring the distance between all beacons seen by the first scanner // and then comparing with the distances seen by the second scanner. If there are at // least 12 beacons with the same distance between them the scanners overlap. private fun alignScanners(s1: Scanner, s2: Scanner): Boolean { // Note: assumes that the allDistances set is ordered in the same way that they were added s1.allDistances.forEachIndexed { s1Index, s1Distances -> // for each beacon in s2. check how many common distances they have s2.allDistances.forEachIndexed { s2Index, s2Distances -> val common = s1Distances intersect s2Distances if (common.size >= 12) { // At least 12 beacons overlap. Scanner s1 and s2 has an overlap // Beacon at s1Index is the same beacon as the one at s2Index // Find another common beacon for both s1 and s2. It needs to have different distances // on all three axis to be able to calculate which axis correspond to each other. val distanceToSecondBeacon = common.first { it.size == 3 } val s1Beacon2Index = s1Distances.indexOf(distanceToSecondBeacon) val s2Beacon2Index = s2Distances.indexOf(distanceToSecondBeacon) s2.alignScanner( s1.realPositions[s1Index] - s1.realPositions[s1Beacon2Index], s2.beacons[s2Index] - s2.beacons[s2Beacon2Index], s1.realPositions[s1Index], s2.beacons[s2Index] ) allBeacons.addAll(s2.realPositions) return true } } } return false } /** * Align all scanners by searching for all scanners overlapping the reference scanner. * Then continue searching for other scanners that overlaps any of the identified * scanners until there are no unaligned scanners left. */ private fun alignAllScanners() { // Record all beacons for the first scanner and use it as the reference scanner allBeacons.addAll(scanners[0].realPositions) val alignedScanners = mutableListOf(scanners[0]) val remainingScanners = scanners.drop(1).toMutableList() // set of scanners that has already been identified as unalignable val alignmentHistory = mutableSetOf<Pair<Scanner, Scanner>>() baseLoop@ while (remainingScanners.isNotEmpty()) { for (aligned in alignedScanners) { for (unaligned in remainingScanners.filterNot { aligned to it in alignmentHistory }) { val res = alignScanners(aligned, unaligned) if (res) { alignedScanners.add(unaligned) remainingScanners.remove(unaligned) continue@baseLoop } alignmentHistory.add(aligned to unaligned) } } } } fun solvePart1(): Int { return allBeacons.size } fun solvePart2(): Int { var max = 0 val offsets = scanners.map { it.scannerOffset } for (i in offsets.indices) { for (j in offsets.indices) { max = max(offsets[i].manhattanDistanceTo(offsets[j]), max) } } return max } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
8,888
aoc
MIT License
src/questions/MergeSortedLists.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import algorithmdesignmanualbook.print import questions.common.LeetNode import utils.assertIterableSame import utils.shouldBe /** * Merge two sorted linked lists and return it as a sorted list. * The list should be made by splicing together the nodes of the first two lists. * [Source](https://leetcode.com/problems/merge-two-sorted-lists/) */ @UseCommentAsDocumentation private fun mergeTwoLists(l1: LeetNode?, l2: LeetNode?): LeetNode? { return returnLowerNode(l1, l2) } private fun returnLowerNode(l1: LeetNode?, l2: LeetNode?): LeetNode? { if (l1 == null) return l2 if (l2 == null) return l1 return if (l1.`val` <= l2.`val`) { l1.next = returnLowerNode(l1.next, l2) l1 } else { l2.next = returnLowerNode(l1, l2.next) l2 } } fun main() { assertIterableSame( expected = LeetNode.from(1, 1, 1, 1, 2, 2).toList(), actual = mergeTwoLists( LeetNode.from(1, 1, 2), LeetNode.from(1, 1, 2) )!!.toList() ) mergeTwoLists( l1 = LeetNode.from(1, 2, 4), l2 = LeetNode.from(1, 3, 4) )!!.toList() shouldBe LeetNode.from(1, 1, 2, 3, 4, 4).toList() assertIterableSame( expected = LeetNode.from(1, 1, 2, 3, 4, 4).toList(), actual = mergeTwoLists(LeetNode.from(1, 2, 4), LeetNode.from(1, 3, 4))!!.toList() ) assertIterableSame( expected = LeetNode.from(1, 2, 2).toList(), actual = mergeTwoLists(LeetNode.from(1, 2), LeetNode.from(2))!!.toList() ) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,586
algorithms
MIT License
solutions/src/main/kotlin/fr/triozer/aoc/y2022/Day01.kt
triozer
573,964,813
false
{"Kotlin": 16632, "Shell": 3355, "JavaScript": 1716}
package fr.triozer.aoc.y2022 import fr.triozer.aoc.utils.readInput // #region part1 private fun part1(input: List<String>): Int { return input.joinToString(";") .split(";;") .maxOf { carriedCalories -> carriedCalories.split(";").sumOf { it.toInt() } } } // #endregion part1 // #region part2 private fun part2(input: List<String>): Int { return input.joinToString(";") .split(";;") .map { carriedCalories -> carriedCalories.split(";").sumOf { it.toInt() } } .sortedDescending().subList(0, 3) .sum() } // #endregion part2 private fun main() { val testInput = readInput(2022, 1, "test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) println("Checks passed ✅") val input = readInput(2022, 1, "input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a9f47fa0f749a40e9667295ea8a4023045793ac1
895
advent-of-code
Apache License 2.0
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day16.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2018.days import nl.jstege.adventofcode.aoc2018.days.instructionset.Instruction.OpCodeInstruction import nl.jstege.adventofcode.aoc2018.days.instructionset.Op import nl.jstege.adventofcode.aoc2018.days.instructionset.RegisterBank import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.substringBetween class Day16 : Day(title = "Chronal Classification") { override fun first(input: Sequence<String>): Any = input .parseSamples() .count { (instr, before, after) -> Op.values().count { op -> op(instr.op1, instr.op2, instr.op3, before) == after } >= 3 } override fun second(input: Sequence<String>): Any = input .parseSamples() .determineOpCodes() .let { opCodes -> input .parseProgram() .fold(RegisterBank(0, 0, 0, 0)) { rs, (opCode, ra, rb, rc) -> opCodes[opCode]!!(ra, rb, rc, rs) }[0] } private fun Sequence<String>.parseProgram(): List<OpCodeInstruction> = this .joinToString("\n") .split("\n\n\n")[1] .split("\n") .filter { it.isNotEmpty() } .map { it.split(" ") } .map { it.map(String::toInt) } .map { (opCode, op1, op2, op3) -> OpCodeInstruction(opCode, op1, op2, op3) } private fun Sequence<String>.parseSamples() = this .chunked(4) .filter { it.first().startsWith("Before") } .map { (beforeLine, opLine, afterLine, _) -> val before = RegisterBank(beforeLine .substringBetween('[', ']') .split(", ") .map { it.toInt() }) val opCode = opLine .split(" ") .map { it.toInt() } .let { (code, op1, op2, op3) -> OpCodeInstruction(code, op1, op2, op3) } val after = RegisterBank(afterLine .substringBetween('[', ']') .split(", ") .map { it.toInt() }) Sample(opCode, before, after) } private fun Sequence<Sample>.determineOpCodes(): Map<Int, Op> { tailrec fun Iterator<Sample>.determinePossibles( possibilities: Map<Int, Set<Op>> ): Map<Int, Set<Op>> = if (!hasNext()) possibilities else { val (instr, beforeRegs, afterRegs) = next() determinePossibles( //Update the possible opcode-to-op entry with the information of the given //sample. This means that the entry will contain only the entries for which //the entry, given the instruction and "before" registers, produces the "after" //registers. possibilities + (instr.opCode to possibilities[instr.opCode]!!.filter { op -> op(instr.op1, instr.op2, instr.op3, beforeRegs) == afterRegs }.toSet()) ) } tailrec fun Map<Int, Set<Op>>.reduceToSingleEntries( definites: Map<Int, Op> = mapOf() ): Map<Int, Op> = if (definites.size == Op.values().size) definites else { //newDefinites contains all possibles which have been reduced to a single //possibility. Therefore, those entries are considered to be final. "remaining" //contains all entries which do not have a single entry left and should be further //reduced. val (newDefinites, remaining) = entries .partition { (opCode, ops) -> opCode !in definites && ops.size == 1 } //Since there may be new definite determined opCodes, remove these ops from the //remaining undetermined opcodes and recursively restart the process with the //remaining ops. remaining .associate { (opCode, remainingOps) -> opCode to (remainingOps - newDefinites.map { (_, op) -> op.first() }) } .reduceToSingleEntries( definites + newDefinites.map { (opCode, op) -> opCode to op.first() } ) } return this.iterator() //Initialise the possibles as a map of an opCode to all ops that fit. At this point no //samples have been processed thus all ops are possible. .determinePossibles((0 until Op.values().size).associate { it to Op.values().toSet() }) .reduceToSingleEntries() } data class Sample( val instruction: OpCodeInstruction, val before: RegisterBank, val after: RegisterBank ) }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
4,806
AdventOfCode
MIT License
src/Day01.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
fun main() { fun part1(input: List<String>): Int = input.fold(0 to 0) { (maximum, current), str -> if (str.isEmpty()) Math.max(maximum, current) to 0 else maximum to current + str.toInt() }.first fun part2(input: List<String>): Int = input.fold(listOf<Int>() to 0) { (list, acc), str -> if (str.isEmpty()) list + acc to 0 else list to acc + str.toInt() }.first.sortedBy { -it }.take(3).sum() val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
547
AdventOfKo2022
Apache License 2.0
2020/src/year2020/day14/Day14.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day12 import util.readAllLines import java.util.regex.Pattern private fun printBits(value: ULong) { println(value.toString(radix = 2).padStart(Long.SIZE_BITS, '0')) } private fun processMask(mask: String): Pair<ULong, ULong> { var andWord = 0.toULong() var andBit = 1.toULong() var orWord = 0.toULong() var orBit = 1.toULong() mask.reversed().forEachIndexed { index, value -> when (value) { '0' -> andWord += andBit '1' -> orWord += orBit else -> { } } andBit = andBit shl 1 orBit = orBit shl 1 } andWord = andWord.inv() return Pair(andWord, orWord) } private fun processMask2(mask: String): List<Pair<ULong, ULong>> { var andWord = 0.toULong() var andBit = 1.toULong() var orWord = 0.toULong() var orBit = 1.toULong() val reversed = mask.reversed() val xIndexes = mutableListOf<Int>() reversed.forEachIndexed { index, value -> when (value) { '0' -> andWord += andBit '1' -> orWord += orBit 'X' -> xIndexes.add(index) else -> { } } andBit = andBit shl 1 orBit = orBit shl 1 } val list = mutableListOf<Pair<ULong, ULong>>() list.add(Pair(andWord, orWord)) xIndexes.forEach { index -> } andWord = andWord.inv() return listOf(Pair(andWord, orWord)) } private val pattern = Pattern.compile("^mem.([0-9]+). = (.*)$") private fun processInstruction(instruction: String): Pair<Long, ULong>? { pattern.matcher(instruction).let { matcher -> if (matcher.matches()) { val location = matcher.group(1).toLong() val value = matcher.group(2).toULong() return Pair(location, value) } } return null } private fun process(filename: String) { val input = readAllLines(filename) var andWord = 0.toULong().inv() var orWord = 0.toULong() val memory = mutableMapOf<Long, ULong>() input.forEach { line -> if (line.startsWith("mask = ")) { processMask(line.substring("mask = ".length)).let { maskValue -> andWord = maskValue.first orWord = maskValue.second } } else { processInstruction(line)?.let { (location, value) -> val newVal = (value and andWord) or orWord memory[location] = newVal } } } var sum = 0.toULong() memory.entries.forEach { (location, value) -> sum += value } println("Process $filename --> $sum") } private fun process2(filename: String) { val input = readAllLines(filename) var andWord = 0.toULong().inv() var orWord = 0.toULong() val memory = mutableMapOf<Long, ULong>() input.forEach { line -> if (line.startsWith("mask = ")) { processMask(line.substring("mask = ".length)).let { maskValue -> andWord = maskValue.first orWord = maskValue.second } } else { processInstruction(line)?.let { (location, value) -> val newVal = (value and andWord) or orWord memory[location] = newVal } } } var sum = 0.toULong() memory.entries.forEach { (location, value) -> sum += value } println("Process $filename --> $sum") } fun main() { // process("test.txt") // process("input.txt") process2("test.txt") }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
3,531
adventofcode
MIT License
src/main/kotlin/com/colinodell/advent2021/Day15.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 import java.util.PriorityQueue import kotlin.math.abs class Day15(input: List<String>) { private val cavern = input.toGrid(Character::getNumericValue) fun solvePart1() = a_star(cavern, cavern.topLeft(), cavern.bottomRight()) fun solvePart2() = cavern.tile(5).let { a_star(it, it.topLeft(), it.bottomRight()) } private fun a_star(grid: Grid<Int>, start: Vector2, goal: Vector2): Int { val h = fun (v: Vector2) = abs(v.x - goal.x) + abs(v.y - goal.y) // The cost of the cheapest path val gScore = mutableMapOf(start to 0) // Our current best guess as to how far we are from the goal val fScore = mutableMapOf(start to h(start)) val openSet = PriorityQueue<Vector2>(1) { a, b -> gScore[a]!! - gScore[b]!! } openSet.add(start) val cameFrom = mutableMapOf<Vector2, Vector2>() while (openSet.isNotEmpty()) { val current = openSet.poll() if (current == goal) { return gScore[current]!! } for (neighbor in current.neighbors()) { if (!grid.containsKey(neighbor) || grid[neighbor] == 0) { continue } val tentativeGScore = gScore[current]!! + grid[neighbor]!! if (tentativeGScore >= gScore.getOrDefault(neighbor, Int.MAX_VALUE)) { continue } cameFrom[neighbor] = current gScore[neighbor] = tentativeGScore fScore[neighbor] = tentativeGScore + h(neighbor) if (!openSet.contains(neighbor)) { openSet.add(neighbor) } } } throw IllegalStateException("No path found") } private fun Grid<Int>.tile(times: Int): Grid<Int> { val newGrid = mutableMapOf<Vector2, Int>() val width = width() val height = height() this.forEach { (pos, value) -> for (xDiff in 0 until times) { for (yDiff in 0 until times) { newGrid[Vector2(pos.x + xDiff * width, pos.y + yDiff * height)] = (value + xDiff + yDiff).let { if (it > 9) it - 9 else it } } } } return newGrid } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
2,351
advent-2021
Apache License 2.0
src/main/kotlin/ru/timakden/aoc/year2022/Day03.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 3: Rucksack Reorganization](https://adventofcode.com/2022/day/3). */ object Day03 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2022/Day03") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>) = input.sumOf { s -> val (firstCompartment, secondCompartment) = s.chunked(s.length / 2).map { it.toSet() } val sameItems = firstCompartment intersect secondCompartment sameItems.sumOf { priorities[it] ?: 0 } } fun part2(input: List<String>) = input.chunked(3).sumOf { s -> val (first, second, third) = s.map { it.toSet() } val sameItems = first intersect second intersect third sameItems.sumOf { c -> priorities[c] ?: 0 } } private val priorities = (('a'..'z').zip(1..27) + ('A'..'Z').zip(27..52)).toMap() }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
1,052
advent-of-code
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2023/day12/day12.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day12 import biz.koziolek.adventofcode.findInput import java.time.LocalDateTime fun main() { val inputFile = findInput(object {}) val springs = parseHotSpringsRecords(inputFile.bufferedReader().readLines()) println("There are ${countPossibleArrangements(springs)} possible arrangements") } const val OPERATIONAL = '.' const val DAMAGED = '#' const val UNKNOWN = '?' data class HotSpringsRow(val conditions: String, val damagedGroupSizes: List<Int>) { fun unfold(): HotSpringsRow = HotSpringsRow( conditions = (1..5).joinToString(UNKNOWN.toString()) { this.conditions }, damagedGroupSizes = (1..5).flatMap { this.damagedGroupSizes } ) val isUnknown = UNKNOWN in conditions } fun parseHotSpringsRecords(lines: Iterable<String>): List<HotSpringsRow> = lines .map { line -> val (conditions, sizesStr) = line.split(" ") val sizes = sizesStr.split(",").map { it.toInt() } HotSpringsRow(conditions, sizes) } fun springsMatch(conditions: String, damagedGroupSizes: List<Int>): Boolean = conditions .split(OPERATIONAL) .filter { it.isNotEmpty() } .map { it.length } .let { it == damagedGroupSizes } fun springsHaveChanceToMatch(conditions: String, damagedGroupSizes: List<Int>): Boolean { val pattern = damagedGroupSizes.joinToString(separator = "[.?]+", prefix = "[.?]*", postfix = "[.?]*") { "[#?]{$it}" } return Regex(pattern).matches(conditions) } fun generatePossibleArrangements(hotSpringsRow: HotSpringsRow, debug: Boolean = false): Sequence<HotSpringsRow> = sequence { if (debug) println(hotSpringsRow.conditions) if (!hotSpringsRow.isUnknown) { if (springsMatch(hotSpringsRow.conditions, hotSpringsRow.damagedGroupSizes)) { yield(hotSpringsRow) } } else if (springsHaveChanceToMatch(hotSpringsRow.conditions, hotSpringsRow.damagedGroupSizes)) { val (first, second) = hotSpringsRow.conditions.split(UNKNOWN, limit = 2) yieldAll(generatePossibleArrangements( HotSpringsRow(first + OPERATIONAL + second, hotSpringsRow.damagedGroupSizes), debug )) yieldAll(generatePossibleArrangements( HotSpringsRow(first + DAMAGED + second, hotSpringsRow.damagedGroupSizes), debug )) } } private val cache: MutableMap<HotSpringsRow, Long> = mutableMapOf() internal var cacheHits = 0L internal var cacheMisses = 0L @Suppress("unused") internal fun resetCache() { cache.clear() cacheHits = 0 cacheMisses = 0 } fun countPossibleArrangements(hotSpringsRow: HotSpringsRow, debug: Boolean = false, level: Int = 0): Long { val count = cache[hotSpringsRow] if (count != null) { cacheHits++ return count } cacheMisses++ val conditions = hotSpringsRow.conditions val damagedGroupSizes = hotSpringsRow.damagedGroupSizes if (debug) { val indent = " ".repeat(level) print("$indent$conditions $damagedGroupSizes") } val newCount = if (!hotSpringsRow.isUnknown) { if (springsMatch(conditions, damagedGroupSizes)) { if (debug) println(" matches!") 1 } else { if (debug) println(" does not match") 0 } } else if (damagedGroupSizes.isEmpty()) { if (conditions.contains(DAMAGED)) { if (debug) println(" is not possible (v2)") 0 } else { if (debug) println(" matches! (shortcut)") 1 } } else { var matchedSizes = 0 var firstUnmatchedPos = 0 var damagedCount = 0 for (c in conditions) { if (damagedCount > 0 && c != DAMAGED) { if (damagedCount == damagedGroupSizes[matchedSizes]) { firstUnmatchedPos += damagedCount damagedCount = 0 matchedSizes++ } else if (damagedCount > damagedGroupSizes[matchedSizes]) { if (debug) println(" too many #") cache[hotSpringsRow] = 0 return 0 } else if (c != UNKNOWN){ if (debug) println(" too few #") cache[hotSpringsRow] = 0 return 0 } } when (c) { UNKNOWN -> break DAMAGED -> { if (matchedSizes >= damagedGroupSizes.size) { cache[hotSpringsRow] = 0 return 0 } damagedCount++ } OPERATIONAL -> firstUnmatchedPos++ else -> throw IllegalStateException("Unexpected character: $c") } } if (debug) print(" firstUnmatchedPos=$firstUnmatchedPos sizes=$matchedSizes") val remainingSizes = damagedGroupSizes.drop(matchedSizes) if (firstUnmatchedPos > 0 && conditions[firstUnmatchedPos - 1] == DAMAGED) { if (debug) println(" add .") countPossibleArrangements( HotSpringsRow(OPERATIONAL + conditions.substring(firstUnmatchedPos + 1), remainingSizes), debug, level + firstUnmatchedPos ) } else { val before = conditions.substring(firstUnmatchedPos, firstUnmatchedPos + damagedCount) val after = conditions.substring(firstUnmatchedPos + damagedCount + 1) if (damagedCount > 0) { if (firstUnmatchedPos + damagedCount < conditions.length && conditions[firstUnmatchedPos + damagedCount] == UNKNOWN) { if (debug) println(" continue #") countPossibleArrangements( HotSpringsRow(before + DAMAGED + after, remainingSizes), debug, level + firstUnmatchedPos ) } else { if (debug) println(" would like to continue # but it's not possible") 0 } } else { if (debug) println(" try # and .") countPossibleArrangements( HotSpringsRow(before + DAMAGED + after, remainingSizes), debug, level + firstUnmatchedPos ) + countPossibleArrangements( HotSpringsRow(before + OPERATIONAL + after, remainingSizes), debug, level + firstUnmatchedPos ) } } } cache[hotSpringsRow] = newCount return newCount } fun countPossibleArrangements(hotSpringsRows: List<HotSpringsRow>, debug: Boolean = false): Long = hotSpringsRows.mapIndexed { index, hotSpringsRow -> val count = countPossibleArrangements(hotSpringsRow, debug) if (debug) println("${LocalDateTime.now()} $index: $hotSpringsRow done = $count") count }.sum()
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
7,153
advent-of-code
MIT License
2022/src/main/kotlin/de/skyrising/aoc2022/day22/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day22 import de.skyrising.aoc.* private fun parseInput(input: PuzzleInput): Pair<CharGrid, List<String>> { val grid = CharGrid.parse(input.lines.subList(0, input.lines.size - 2)) val path = Regex("\\d+|R|L").findAll(input.lines.last()).map { it.value }.toList() return grid to path } private fun nextTile(grid: CharGrid, state: VecState, transitions: Map<VecState, VecState>? = null): VecState { var (pos, dir) = state return if (transitions == null) { do { pos = (pos + dir + grid.size) % grid.size } while (grid[pos] == ' ') if (grid[pos] == '.') pos to dir else state } else { val next = transitions[state] ?: ((pos + dir + grid.size) % grid.size to dir) when (grid[next.first]) { '.' -> next '#' -> state else -> error("Invalid tile: $next='${grid[next.first]}' ($pos+$dir)") } } } private val FACINGS = arrayOf(Vec2i.E, Vec2i.S, Vec2i.W, Vec2i.N) private fun move(grid: CharGrid, state: VecState, step: String, transitions: Map<VecState, VecState>? = null) = when(step) { "R" -> state.first to FACINGS[(FACINGS.indexOf(state.second) + 1) % 4] "L" -> state.first to FACINGS[(FACINGS.indexOf(state.second) + 3) % 4] else -> { val steps = step.toInt() var state = state repeat(steps) { state = nextTile(grid, state, transitions) } state } } private typealias EdgeSide = Pair<Line2i, Vec2i> private typealias Edge = Pair<EdgeSide, EdgeSide> private typealias VecState = Pair<Vec2i, Vec2i> private fun EdgeSide.reverse() = first.reverse() to second private class CubeNetDSL(size: Int, val A: Vec2i, val B: Vec2i, val C: Vec2i, val D: Vec2i, val E: Vec2i, val F: Vec2i) { private val last = size - 1 val edges = mutableListOf<Edge>() fun bottom(side: Vec2i) = Line2i(Vec2i(side.x, side.y + last), Vec2i(side.x + last, side.y + last)) to Vec2i.S fun top(side: Vec2i) = Line2i(Vec2i(side.x, side.y), Vec2i(side.x + last, side.y)) to Vec2i.N fun left(side: Vec2i) = Line2i(Vec2i(side.x, side.y), Vec2i(side.x, side.y + last)) to Vec2i.W fun right(side: Vec2i) = Line2i(Vec2i(side.x + last, side.y), Vec2i(side.x + last, side.y + last)) to Vec2i.E fun edge(edge: Edge) { edges.add(edge) } } private fun cubeNet(size: Int, A: Vec2i, B: Vec2i, C: Vec2i, D: Vec2i, E: Vec2i, F: Vec2i, block: CubeNetDSL.() -> Unit) = CubeNetDSL(size, A * size, B * size, C * size, D * size, E * size, F * size).apply(block).edges private fun cubeNetTest(size: Int) = cubeNet(size, Vec2i(2, 0), Vec2i(0, 1), Vec2i(1, 1), Vec2i(2, 1), Vec2i(2, 2), Vec2i(3, 2)) { // ..A. // BCD. // ..EF edge(left(A) to top(C)) edge(top(A) to top(B).reverse()) edge(right(A) to right(F).reverse()) edge(left(B) to bottom(F).reverse()) edge(bottom(B) to bottom(E).reverse()) edge(bottom(C) to left(E).reverse()) edge(right(D) to top(F).reverse()) } private fun cubeNetReal(size: Int) = cubeNet(size, Vec2i(1, 0), Vec2i(2, 0), Vec2i(1, 1), Vec2i(0, 2), Vec2i(1, 2), Vec2i(0, 3)) { // .AB // .C. // DE. // F.. edge(left(A) to left(D).reverse()) edge(top(A) to left(F)) edge(top(B) to bottom(F)) edge(right(B) to right(E).reverse()) edge(bottom(B) to right(C)) edge(left(C) to top(D)) edge(bottom(E) to right(F)) } private fun buildTransitions(edges: List<Edge>): MutableMap<VecState, VecState> { val transitions = mutableMapOf<VecState, VecState>() for ((a, b) in edges) { val (aLine, aDir) = a val aPoints = aLine.toList() val (bLine, bDir) = b val bPoints = bLine.toList() for (i in aPoints.indices) { transitions[aPoints[i] to aDir] = bPoints[i] to -bDir transitions[bPoints[i] to bDir] = aPoints[i] to -aDir } } return transitions } private fun run(input: PuzzleInput, transitions: Map<VecState, VecState>? = null): Int { val (grid, path) = parseInput(input) var state = grid.where { it == '.' }.first() to Vec2i.E for (step in path) { state = move(grid, state, step, transitions) } val pos = state.first return pos.y * 1000 + pos.x * 4 + FACINGS.indexOf(state.second) + 1004 } val test = TestInput(""" ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 """) @PuzzleName("Monkey Map") fun PuzzleInput.part1() = run(this) fun PuzzleInput.part2() = run(this, buildTransitions(cubeNetReal(50)))
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
4,726
aoc
MIT License
src/main/kotlin/solutions/constantTime/iteration3/MemorizedBracketTaxCalculator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package solutions.constantTime.iteration3 import dataModel.base.Money import dataModel.base.Money.Companion.dollars import dataModel.base.TaxBracket import dataModel.base.TaxCalculator import solutions.constantTime.iteration2.BoundedMemorizedTaxCalculator import dataModel.v2.AccumulatedTaxBracket import dataModel.v2.toAccumulatedBrackets /** * An improved version of [BoundedMemorizedTaxCalculator] as it stores a reference to an existing bracket for each * income instead of storing a new Money instance each time. This reduces memory consumption by about 40%. * Additionally, the initial setup completes in O(B) time instead of O(B * log(N)) time, where N is the number of * brackets and B is the lower bound of the highest tax bracket in pennies. */ class MemorizedBracketTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator { private val highestBracket: AccumulatedTaxBracket private val memorizedIncomeToBracket: Map<Money, AccumulatedTaxBracket> init { val accumulatedBrackets = taxBrackets.toAccumulatedBrackets() highestBracket = accumulatedBrackets.last() var bracketIndex = 0 memorizedIncomeToBracket = generateSequence(0.dollars) { it + Money.ofCents(amount = 1) } .takeWhile { it < taxBrackets.last().from } // create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory .associateWithTo(HashMap()) { income -> if (income >= taxBrackets[bracketIndex].to!!) { bracketIndex++ } accumulatedBrackets[bracketIndex] } } override fun computeTax(income: Money): Money { val bracket = memorizedIncomeToBracket[income] ?: highestBracket return bracket.computeTotalTax(income) } }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
1,825
tax-calculator
MIT License
language/kotlin/Kotlin for Java Developers. Week 3/Taxi Park/Task/src/taxipark/TaxiParkTask.kt
posadskiy
125,151,585
false
{"Java": 315541, "Kotlin": 111425, "HTML": 37044, "JavaScript": 16971, "CSS": 7560, "Swift": 6246}
package taxipark import kotlin.math.roundToInt /* * Task #1. Find all the drivers who performed no trips. */ fun TaxiPark.findFakeDrivers(): Set<Driver> = this.allDrivers.filter { driver -> this.trips.all { trip -> !trip.driver.name.equals(driver.name) } }.toSet() /* * Task #2. Find all the clients who completed at least the given number of trips. */ fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> = this.allPassengers.filter { passenger -> this.trips.count { trip -> trip.passengers.any { tripPassenger -> passenger.name.equals(tripPassenger.name) } } >= minTrips }.toSet() /* * Task #3. Find all the passengers, who were taken by a given driver more than once. */ fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> = this.allPassengers.filter { passenger -> this.trips.count { trip -> trip.passengers.any { tripPassenger -> passenger.name.equals(tripPassenger.name) } && trip.driver.name.equals(driver.name) } > 1 }.toSet() /* * Task #4. Find the passengers who had a discount for majority of their trips. */ fun TaxiPark.findSmartPassengers(): Set<Passenger> = this.allPassengers.filter { passenger -> val trips = this.trips.filter { trip -> trip.passengers.any { tripPassenger -> passenger.name.equals(tripPassenger.name) } }.partition { if (it.discount == null) { false } else { it.discount > 0 } } trips.first.size > trips.second.size }.toSet() /* * Task #5. Find the most frequent trip duration among minute periods 0..9, 10..19, 20..29, and so on. * Return any period if many are the most frequent, return `null` if there're no trips. */ fun TaxiPark.findTheMostFrequentTripDurationPeriod(): IntRange? { if (this.trips.isEmpty()) return null val max = (0..50).maxBy { duration -> this.trips.count { it.duration in duration*10..duration*10+9 } } if (max == null) return null return IntRange(max * 10, max * 10 + 9) } /* * Task #6. * Check whether 20% of the drivers contribute 80% of the income. */ fun TaxiPark.checkParetoPrinciple(): Boolean { val map = this.allDrivers.map { driver -> driver.name to this.trips.filter { it.driver.name == driver.name }.map { it.cost }.sum() }.sortedByDescending { it.second } val sumSuccessful = map.take((map.size * 0.2).roundToInt()).map { it.second }.sum() val allSum = map.map { it.second }.sum() return sumSuccessful / allSum >= 0.8 - 0.00001 }
1
Java
0
3
a0fd842209e1644298c19680aeffa672069955ed
2,548
study-everyday
MIT License
src/Day01.kt
achugr
573,234,224
false
null
fun main() { fun groupAndSum(input: List<String>) = input.foldIndexed(mutableListOf<MutableList<Int>>(mutableListOf())) { index, list, value -> when { value.isBlank() -> list.add(mutableListOf()) list.isNotEmpty() -> list.last().add(value.toInt()) else -> list.add(mutableListOf()) } list } .filter { list -> list.isNotEmpty() } .map { list -> list.sum() } fun part1(input: List<String>): Int { return groupAndSum(input) .max() } fun part2(input: List<String>): Int { return groupAndSum(input) .sorted() .reversed() .take(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
d91bda244d7025488bff9fc51ca2653eb6a467ee
931
advent-of-code-kotlin-2022
Apache License 2.0
src/Day16.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
import java.lang.Math.* import java.util.* fun main() { class Valve( var name: String, var flowRate: Int, var isOpen: Boolean = false, var isOpening: Boolean = false, var totalPressureReleased: Int = Integer.MAX_VALUE, var mostFlowRate: LinkedList<Valve> = LinkedList(), var adjacentNodes: MutableMap<Valve, Int> = mutableMapOf(), var openedValves: MutableList<Valve> = mutableListOf() ) : Comparable<Valve> { fun addAdjacentNode(valve: Valve, weight: Int) { adjacentNodes[valve] = weight } override fun compareTo(other: Valve): Int { if(!other.isOpen) { return Integer.compare(totalPressureReleased, other.totalPressureReleased) } else { return (random()*2 - 3).toInt() } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Valve if (name != other.name) return false if (flowRate != other.flowRate) return false if (isOpen != other.isOpen) return false if (totalPressureReleased != other.totalPressureReleased) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + flowRate result = 31 * result + isOpen.hashCode() result = 31 * result + totalPressureReleased return result } fun printAdjacentNodeNames() { println("${this.name}: ${(adjacentNodes.keys).joinToString { it.name }}") } override fun toString(): String { return "Valve(name='$name', flowRate=$flowRate, isOpen=$isOpen, isOpening=$isOpening)" } } fun evaluateFlowRateAndPath(adjacentNode: Valve, edgeWeight: Int, sourceNode: Valve ) { val newDistance = sourceNode.totalPressureReleased + edgeWeight if(newDistance > adjacentNode.totalPressureReleased) { adjacentNode.totalPressureReleased = newDistance val mostFlowRatePath = LinkedList<Valve>() mostFlowRatePath.addAll(sourceNode.mostFlowRate) mostFlowRatePath.add(sourceNode) adjacentNode.mostFlowRate = mostFlowRatePath } } fun calculateLargestFlowrate(source: Valve) : Set<Valve> { source.totalPressureReleased = 0 var settled = hashSetOf<Valve>() var unsettled = PriorityQueue<Valve>() unsettled.add(source) while(unsettled.isNotEmpty()) { var currentNode = unsettled.poll() currentNode.adjacentNodes.entries.forEach { evaluateFlowRateAndPath(it.key, it.value, currentNode) unsettled.add(it.key) } settled.add(currentNode) println("unsettled: ${unsettled.size } settled ${settled.joinToString { it.name }}") } return settled } fun part1(input: List<String>): Int { var valves = input .map { it.replace("Valve ", "") } .map { it.replace("has flow rate=", "") } .map { it.replace(";", "") } .map { it.replace("tunnel", "tunnels") } .map { it.replace("leads", "lead") } .map { it.replace("tunnels lead to valves ", "") } .map { val split = it.split(" ") Valve(split[0],split[1].toInt()) } valves.forEachIndexed { i, valve -> val connectedValves = input.map { it.replace("valves", "valve") } .map { it.substring(it.indexOf("valve ") + "valve ".length) }[i] .split(", ") connectedValves.forEach { valve.addAdjacentNode(valves.find { v -> v.name == it }!!, 1) } } // println(valves) var bestLog = mutableListOf<String>() var logList = mutableListOf<String>() // val releasedPressures = mutableSetOf<Int>().toSortedSet(Collections.reverseOrder()) // releasedPressures.add(0) var maxPressure = 0 repeat(1_000_000_000) { var minute = 30 var location = valves[0] var oldLocation = location var movingToAnotherRoom = true var releasedPressure = 0 while(minute > 0) { if(movingToAnotherRoom) { oldLocation = location location = location.adjacentNodes.keys.random() // println("from: ${oldLocation.name} to possibly ${oldLocation.adjacentNodes.keys.joinToString{it.name}} but went to ${location.name}") // bestLog += "from: ${oldLocation.name} to possibly ${oldLocation.adjacentNodes.keys.joinToString{it.name}} but went to ${location.name}" if(!location.isOpen && location.flowRate>0 && random() < 0.5) { movingToAnotherRoom = false } } else { location.isOpen = true movingToAnotherRoom = true releasedPressure += location.flowRate * (minute - 1) } minute-- // releasedPressure += valves.filter { it.isOpen }.sumOf { it.flowRate } logList.add("\ntime: $minute pressure: $releasedPressure location: ${location.name} openValves: " + "${valves.filter { it.isOpen }.joinToString{ it.name }} " + // "opening: ${valves.filter { it.isOpening }.joinToString { it.name }} total " + "flow: ${valves.filter { it.isOpen }.sumOf { it.flowRate }}") // valves.filter { it.isOpening }.forEach { it.isOpening = false; it.isOpen = true } } valves.forEach { it.isOpening = false it.isOpen = false } if(releasedPressure > maxPressure) { bestLog.clear() bestLog.addAll(logList) maxPressure = releasedPressure } // releasedPressures.add(releasedPressure) // if(it % 100000 == 0) { // for(i in releasedPressures.size-1 downTo 5) { // releasedPressures.remove(releasedPressures.last()) // } //// println(releasedPressures) // } logList.clear() } valves.forEach { println("${it.name}: ${it.adjacentNodes.keys.joinToString { it.name }} flowRate: ${it.flowRate}") } println(bestLog) // val start = valves[0] // val settled = calculateLargestFlowrate(start) // println(settled) // // return 0 return maxPressure } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") // println(part1(testInput)) // println(part2(testInput)) val input = readInput("Day16") output(part1(input)) // output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
6,316
AdventOfCode2022
Apache License 2.0
src/main/kotlin/org/rust/toml/crates/local/CrateVersionRequirement.kt
intellij-rust
42,619,487
false
{"Kotlin": 11390660, "Rust": 176571, "Python": 109964, "HTML": 23157, "Lex": 12605, "ANTLR": 3304, "Java": 688, "Shell": 377, "RenderScript": 343}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.toml.crates.local import io.github.z4kn4fein.semver.Version import io.github.z4kn4fein.semver.constraints.Constraint import io.github.z4kn4fein.semver.constraints.satisfiedBy import io.github.z4kn4fein.semver.constraints.toConstraintOrNull class CrateVersionRequirement private constructor(private val requirements: List<Constraint>) { val isPinned: Boolean = requirements.any { it.toString().startsWith("=") } fun matches(version: Version): Boolean = requirements.all { it satisfiedBy version } companion object { fun build(text: String): CrateVersionRequirement? { val requirements = text.split(",").map { it.trim() } if (requirements.size > 1 && requirements.any { it.isEmpty() }) return null val parsed = requirements.mapNotNull { normalizeVersion(it).toConstraintOrNull() } if (parsed.size != requirements.size) return null return CrateVersionRequirement(parsed) } } } /** * Normalizes crate version requirements so that they are compatible with semver lib. * * 1) For exact (=x.y.z) and range-based (>x.y.z, <x.y.z) version requirements, the version requirement is padded by * zeros from the right side. * * Example: * - `=1` turns into `=1.0.0` * - `>2.3` turns into `>2.3.0` * * 2) For "compatible" version requirements (x.y.z) that do not contain a wildcard (*), a caret is added to the * beginning. This matches the behaviour of Cargo. * * Example: * - `1.2.3` turns into `^1.2.3` * * See [Cargo Reference](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-dependencies-from-cratesio). */ private fun normalizeVersion(version: String): String { if (version.isBlank()) return version // Exact and range-based version requirements need to be padded from right by zeros. // kotlin-semver treats non-specified parts as *, so =1.2 would be =1.2.*. We need to explicitly specify them. var normalized = version if (normalized[0] in listOf('<', '>', '=')) { while (normalized.count { it == '.' } < 2) { normalized += ".0" } } // Cargo treats version requirements like `1.2.3` as if they had a caret at the beginning. // If the version begins with a digit and it does not contain a wildcard, we thus prepend a caret to it. // Also, kotlin-semver lib treats versions without any range modifiers as exact ones like `=1.2.3`, so // we would like to avoid it. return if (normalized[0].isDigit() && !normalized.contains("*")) { "^$normalized" } else { normalized } }
1,843
Kotlin
392
4,524
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
2,787
intellij-rust
MIT License
src/main/kotlin/g0901_1000/s0959_regions_cut_by_slashes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0959_regions_cut_by_slashes // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Union_Find // #2023_05_03_Time_180_ms_(100.00%)_Space_37.2_MB_(50.00%) @Suppress("NAME_SHADOWING") class Solution { private var regions = 0 private lateinit var parent: IntArray fun regionsBySlashes(grid: Array<String>): Int { val n = grid.size regions = n * n * 4 unionFind(regions) for (row in grid.indices) { val str = grid[row] val ch = str.toCharArray() for ((col, c) in ch.withIndex()) { val index = row * n * 4 + col * 4 when (c) { '/' -> { union(index, index + 3) union(index + 1, index + 2) } ' ' -> { union(index, index + 1) union(index + 1, index + 2) union(index + 2, index + 3) } else -> { union(index, index + 1) union(index + 2, index + 3) } } if (row != n - 1) { union(index + 2, index + 4 * n) } if (col != n - 1) { union(index + 1, index + 7) } } } return regions } private fun unionFind(n: Int) { parent = IntArray(n) for (i in 0 until n) { parent[i] = i } } private fun union(p: Int, q: Int) { if (connected(p, q)) { return } --regions val i = root(p) val j = root(q) if (i > j) { parent[i] = j } else { parent[j] = i } } private fun connected(p: Int, q: Int): Boolean { return root(p) == root(q) } private fun root(index: Int): Int { var index = index while (index != parent[index]) { parent[index] = parent[parent[index]] index = parent[index] } return index } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,164
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/VerbalArithmeticPuzzle.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 fun interface VerbalArithmeticPuzzle { operator fun invoke(words: Array<String>, result: String): Boolean } class VerbalArithmeticPuzzleBacktracking : VerbalArithmeticPuzzle { companion object { private val POW_10 = intArrayOf(1, 10, 100, 1000, 10000, 100000, 1000000) private const val ARR_SIZE = 91 } override fun invoke(words: Array<String>, result: String): Boolean { val charSet: MutableSet<Char> = HashSet() val charCount = IntArray(ARR_SIZE) val nonLeadingZero = BooleanArray(ARR_SIZE) // ASCII of `A..Z` chars are in range `65..90` for (word in words) { val cs = word.toCharArray() for (i in cs.indices) { if (i == 0 && cs.size > 1) { nonLeadingZero[cs[i].code] = true } charSet.add(cs[i]) charCount[cs[i].code] += POW_10[cs.size - i - 1] // charCount is calculated by units } } val cs = result.toCharArray() for (i in cs.indices) { if (i == 0 && cs.size > 1) { nonLeadingZero[cs[i].code] = true } charSet.add(cs[i]) charCount[cs[i].code] -= POW_10[cs.size - i - 1] // charCount is calculated by units } val used = BooleanArray(10) val charList = CharArray(charSet.size) var i = 0 for (c in charSet) { charList[i++] = c } return backtracking(used, charList, nonLeadingZero, 0, 0, charCount) } private fun backtracking( used: BooleanArray, charList: CharArray, nonLeadingZero: BooleanArray, step: Int, diff: Int, charCount: IntArray, ): Boolean { if (step == charList.size) return diff == 0 // difference between sum of words and result equal to 0 for (d in 0..9) { // each character is decoded as one digit (0 - 9). val c = charList[step] // decoded as one number without leading zeros. if (!used[d] && (d > 0 || !nonLeadingZero[c.code])) { used[d] = true if (backtracking( used, charList, nonLeadingZero, step + 1, diff + charCount[c.code] * d, charCount, ) ) { return true } used[d] = false } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,217
kotlab
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/FindAllNumbersDisappearedInAnArrayKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] */ class FindAllNumbersDisappearedInAnArrayKt { class Solution { /** Move the value of the element to nums[value - 1]. On swapping, if new value does not match index, continue until value matches 0 marks that a node is missing index = 0 i [5,1,2,3,4] [1,2,3,4,5] */ companion object { val VALUE_REMOVED = 0 } private fun swapUntilMatchingOrMissing(nums: IntArray, index: Int): Int { var valueAtIndex = 0 var valueFromIndex = 0 var timesLoopsRuns = 0 val whatTheIndexShouldBe = index + 1 while (true) { valueAtIndex = nums[index] if (valueAtIndex == VALUE_REMOVED || valueAtIndex == whatTheIndexShouldBe) { break } valueFromIndex = nums[valueAtIndex - 1] if (valueFromIndex == valueAtIndex) { nums[index] = 0 break } nums[index] = valueFromIndex nums[valueAtIndex - 1] = valueAtIndex timesLoopsRuns++ } return timesLoopsRuns } fun findDisappearedNumbers(nums: IntArray): List<Int> { var index = 0 val timesLoopRuns = ArrayList<Int>() while (index < nums.size) { timesLoopRuns.add(swapUntilMatchingOrMissing(nums, index)) index++ } index = 0 var size = 0 while (index < nums.size) { if (nums[index] == 0) { size++ } index++ } index = 0 val result = ArrayList<Int>(size) while (index < nums.size) { if (nums[index] == 0) { result.add(index + 1) } index++ } var total = 0 timesLoopRuns.forEach { total += it} return result } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
2,694
cloud-dqn-leetcode
No Limit Public License
day02/kotlin/corneil/src/main/kotlin/solution.kt
timgrossmann
224,991,491
true
{"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46}
package com.github.corneil.aoc2019.day2 import java.io.File fun readProgram(input: String) = input.split(",").map { it.toInt() } fun readProgram(input: File) = readProgram(input.readText().trim()) fun deref(input: List<Int>, address: Int): Int = input[input[address]] fun assign(input: MutableList<Int>, address: Int, value: Int) { input[input[address]] = value } fun applyOperation(input: MutableList<Int>, pc: Int, operation: (Int, Int) -> Int): Int { val result = operation(deref(input, pc + 1), deref(input, pc + 2)) assign(input, pc + 3, result) return pc + 4 } fun readAndExecute(pc: Int, input: MutableList<Int>): Int { val opcode = input[pc] return when (opcode) { 1 -> { applyOperation(input, pc) { a, b -> a + b } } 2 -> { applyOperation(input, pc) { a, b -> a * b } } 99 -> { input.size } else -> { throw Exception("Invalid opcode $opcode") } } } fun executeProgram(input: MutableList<Int>): List<Int> { var pc = 0; while (pc < input.size) { pc = readAndExecute(pc, input) } return input.toList() } // We make a copy of the original for testing an iteration. fun executeIteration(program: List<Int>, noun: Int, verb: Int): List<Int> { val copyX = program.toMutableList() copyX[1] = noun copyX[2] = verb return executeProgram(copyX) } fun main(args: Array<String>) { val fileName = if (args.size > 1) args[0] else "input.txt" val program = readProgram(File(fileName)).toMutableList() val output = executeIteration(program, 12, 2) println("Result1=${output[0]}") assert(output[0] == 5866714) // This is a brute force but with no more than 1000 iteration it isn't a problem. Solvers can wait mainLoop@ for (i in 0..99) { for (j in 0..99) { try { val result = executeIteration(program, i, j) if (result[0] == 19690720) { val answer = 100 * i + j println("Result=$answer") break@mainLoop; } } catch (x: Throwable) { println("Iteration failed:$x") } } } }
0
HTML
0
1
bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b
2,268
aoc-2019
MIT License
src/main/kotlin/g2201_2300/s2280_minimum_lines_to_represent_a_line_chart/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2280_minimum_lines_to_represent_a_line_chart // #Medium #Array #Math #Sorting #Geometry #Number_Theory // #2023_06_28_Time_765_ms_(100.00%)_Space_98.8_MB_(100.00%) import java.util.Arrays class Solution { fun minimumLines(stockPrices: Array<IntArray>): Int { if (stockPrices.size == 1) { return 0 } Arrays.sort(stockPrices) { a: IntArray, b: IntArray -> a[0] - b[0] } // multiply with 1.0 to make it double and multiply with 100 for making it big so that // difference won't come out to be very less and after division it become 0. // failing for one of the case without multiply 100 var lastSlope = ( (stockPrices[1][1] - stockPrices[0][1]) * 100 / ((stockPrices[1][0] - stockPrices[0][0]) * 1.0) ) var ans = 1 for (i in 2 until stockPrices.size) { val curSlope = ( (stockPrices[i][1] - stockPrices[i - 1][1]) * 100 / ((stockPrices[i][0] - stockPrices[i - 1][0]) * 1.0) ) if (lastSlope != curSlope) { lastSlope = curSlope ans++ } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,275
LeetCode-in-Kotlin
MIT License
src/aoc2023/Day09.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day09" fun extrapolate(seq: List<Long>, backguard: Boolean): Long { var value = 0L var factor = 1 var current = seq while (current.any { it != 0L }) { if (backguard) { value += current.first() * factor factor *= -1 } else { value += current.last() } current = current.windowed(2).map { (a, b) -> b - a } } return value } fun extrapolateSum(input: List<String>, backguard: Boolean) = input.map { line -> line.split("\\s+".toRegex()).map { it.toLong() } }.sumOf { extrapolate(it, backguard) } fun part1(input: List<String>) = extrapolateSum(input, false) fun part2(input: List<String>) = extrapolateSum(input, true) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 114) println(part1(input)) checkValue(part2(testInput), 2) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
1,151
aoc-kotlin
Apache License 2.0
src/Day09.kt
vjgarciag96
572,719,091
false
{"Kotlin": 44399}
import kotlin.math.absoluteValue private data class Point( val x: Int, val y: Int, ) private fun part1(input: List<String>): Int { val pointsVisitedByTail = HashSet<Point>() var headPosition = Point(x = 0, y = 0) var tailPosition = Point(x = 0, y = 0) pointsVisitedByTail.add(tailPosition) input.forEach { movement -> val (direction, distance) = movement.split(" ") repeat(distance.toInt()) { headPosition = when (direction) { "L" -> headPosition.copy(x = headPosition.x - 1) "R" -> headPosition.copy(x = headPosition.x + 1) "U" -> headPosition.copy(y = headPosition.y + 1) "D" -> headPosition.copy(y = headPosition.y - 1) else -> error("invalid direction $direction") } val xDistance = headPosition.x - tailPosition.x val yDistance = headPosition.y - tailPosition.y tailPosition = when { xDistance.absoluteValue < 2 && yDistance.absoluteValue < 2 -> tailPosition xDistance == 2 && yDistance == 0 -> tailPosition.copy(x = tailPosition.x + 1) xDistance == -2 && yDistance == 0 -> tailPosition.copy(x = tailPosition.x - 1) yDistance == 2 && xDistance == 0 -> tailPosition.copy(y = tailPosition.y + 1) yDistance == -2 && xDistance == 0 -> tailPosition.copy(y = tailPosition.y - 1) xDistance == 2 && yDistance == 1 -> tailPosition.copy( x = tailPosition.x + 1, y = tailPosition.y + 1 ) xDistance == -2 && yDistance == 1 -> tailPosition.copy( x = tailPosition.x - 1, y = tailPosition.y + 1 ) xDistance == 2 && yDistance == -1 -> tailPosition.copy( x = tailPosition.x + 1, y = tailPosition.y - 1 ) xDistance == -2 && yDistance == -1 -> tailPosition.copy( x = tailPosition.x - 1, y = tailPosition.y - 1 ) yDistance == 2 && xDistance == 1 -> tailPosition.copy( x = tailPosition.x + 1, y = tailPosition.y + 1 ) yDistance == 2 && xDistance == -1 -> tailPosition.copy( x = tailPosition.x - 1, y = tailPosition.y + 1 ) yDistance == -2 && xDistance == 1 -> tailPosition.copy( x = tailPosition.x + 1, y = tailPosition.y - 1 ) yDistance == -2 && xDistance == -1 -> tailPosition.copy( x = tailPosition.x - 1, y = tailPosition.y - 1 ) else -> error("Invalid distances -> x = $xDistance, y = $yDistance") } pointsVisitedByTail.add(tailPosition) } } return pointsVisitedByTail.count() } private fun part2(input: List<String>): Int { val pointsVisitedByTail = HashSet<Point>() val positions = Array(10) { Point(x = 0, y = 0) }.toMutableList() pointsVisitedByTail.add(positions.last()) input.forEach { movement -> val (direction, distance) = movement.split(" ") repeat(distance.toInt()) { val headPosition = positions.first() positions[0] = when (direction) { "L" -> headPosition.copy(x = headPosition.x - 1) "R" -> headPosition.copy(x = headPosition.x + 1) "U" -> headPosition.copy(y = headPosition.y + 1) "D" -> headPosition.copy(y = headPosition.y - 1) else -> error("invalid direction $direction") } var pointerA = 0 var pointerB = 1 while (pointerB < positions.size) { val positionA = positions[pointerA] val positionB = positions[pointerB] val xDistance = positionA.x - positionB.x val yDistance = positionA.y - positionB.y val newPositionB = when { xDistance.absoluteValue < 2 && yDistance.absoluteValue < 2 -> positionB xDistance == 2 && yDistance == 0 -> positionB.copy(x = positionB.x + 1) xDistance == -2 && yDistance == 0 -> positionB.copy(x = positionB.x - 1) yDistance == 2 && xDistance == 0 -> positionB.copy(y = positionB.y + 1) yDistance == -2 && xDistance == 0 -> positionB.copy(y = positionB.y - 1) xDistance == 2 && yDistance == 1 -> positionB.copy( x = positionB.x + 1, y = positionB.y + 1 ) xDistance == -2 && yDistance == 1 -> positionB.copy( x = positionB.x - 1, y = positionB.y + 1 ) xDistance == 2 && yDistance == -1 -> positionB.copy( x = positionB.x + 1, y = positionB.y - 1 ) xDistance == -2 && yDistance == -1 -> positionB.copy( x = positionB.x - 1, y = positionB.y - 1 ) yDistance == 2 && xDistance == 1 -> positionB.copy( x = positionB.x + 1, y = positionB.y + 1 ) yDistance == 2 && xDistance == -1 -> positionB.copy( x = positionB.x - 1, y = positionB.y + 1 ) yDistance == -2 && xDistance == 1 -> positionB.copy( x = positionB.x + 1, y = positionB.y - 1 ) yDistance == -2 && xDistance == -1 -> positionB.copy( x = positionB.x - 1, y = positionB.y - 1 ) xDistance == 2 && yDistance == 2 -> positionB.copy( x = positionB.x + 1, y = positionB.y + 1, ) xDistance == -2 && yDistance == 2 -> positionB.copy( x = positionB.x - 1, y = positionB.y + 1, ) xDistance == 2 && yDistance == -2 -> positionB.copy( x = positionB.x + 1, y = positionB.y - 1, ) xDistance == -2 && yDistance == -2 -> positionB.copy( x = positionB.x - 1, y = positionB.y - 1, ) else -> error("Invalid distances -> x = $xDistance, y = $yDistance") } positions[pointerB] = newPositionB pointerA++ pointerB++ } pointsVisitedByTail.add(positions.last()) } } return pointsVisitedByTail.count() } fun main() { val testInput = readInput("Day09_test") check(part1(testInput) == 13) check(part2(testInput) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ee53877877b21166b8f7dc63c15cc929c8c20430
7,453
advent-of-code-2022
Apache License 2.0
src/Day06.kt
polbins
573,082,325
false
{"Kotlin": 9981}
fun main() { fun part1(input: List<String>, size: Int = 4): List<Int> { val result = mutableListOf<Int>() input.forEach { s -> val chars = mutableListOf<Char>() s.toCharArray().forEachIndexed { index, c -> chars.add(c) if (chars.size == size) { if (chars.toSet().size == size) { result.add(index + 1) return@forEach } else { chars.removeAt(0) } } } } return result } // test if implementation meets criteria from the description, like: val testInput1 = readInput("Day06_test") check( part1(testInput1) == listOf( 7, 5, 6, 10, 11 ) ) val input1 = readInput("Day06") println(part1(input1)) val testInput2 = readInput("Day06_test") check( part1(testInput2, 14) == listOf( 19, 23, 23, 29, 26 ) ) val input2 = readInput("Day06") println(part1(input2, 14)) }
0
Kotlin
0
0
fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14
945
AoC-2022
Apache License 2.0
src/main/kotlin/cloud/dqn/leetcode/DeleteNodeInABSTKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/delete-node-in-a-bst/description/ Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: Time complexity should be O(height of tree). Example: root = [5,3,6,2,4,null,7] key = 3 5 / \ 3 6 / \ \ 2 4 7 Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is [5,4,6,2,null,null,7], shown in the following BST. 5 / \ 4 6 / \ 2 7 Another valid answer is [5,2,6,null,4,null,7]. 5 / \ 2 6 \ \ 4 7 */ class DeleteNodeInABSTKt { class TreeNode(var `val`: Int = 0) { var left: TreeNode? = null var right: TreeNode? = null } class Solution { data class NodeAndParent ( val node: TreeNode?, val parent: TreeNode? ) private fun findNode(root: TreeNode?, key: Int): NodeAndParent { var parent: TreeNode? = null var node: TreeNode? = root var nodeValue = 0 while (node != null) { nodeValue = node.`val` if (key == nodeValue) { break } else if (key < nodeValue) { parent = node node = node.left } else { parent = node node = node.right } } return if (node == null) { NodeAndParent(node, null) } else { NodeAndParent(node, parent) } } fun deleteNode(root: TreeNode?, key: Int): TreeNode? { val (foundNode, parent) = findNode(root, key) if (foundNode != null) { var rightBranch = foundNode.right var leftBranch = foundNode.left val newSubHead = if (rightBranch == null) { leftBranch } else if (leftBranch == null) { rightBranch } else { var greatestOfLeftBranch = leftBranch while (greatestOfLeftBranch?.right != null) { greatestOfLeftBranch = greatestOfLeftBranch.right } greatestOfLeftBranch?.right = foundNode.right leftBranch } if (parent == null) { return newSubHead // remove the root } else if (parent.left?.`val` == key) { parent.left = newSubHead // replace the left node of parent } else { parent.right = newSubHead // replace the right node of parent } String } return root } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
3,159
cloud-dqn-leetcode
No Limit Public License
src/Day06.kt
vi-quang
573,647,667
false
{"Kotlin": 49703}
/** * Main ------------------------------------------------------------------- */ fun main() { class Bin(val name: String) { var content: Char = '-' } class CharacterWindow(var capacity: Int) { val binList = mutableListOf<Bin>() init { for (i in 1..capacity) { binList.add(Bin("" + i)) } } val map = mutableMapOf<Char, MutableList<Bin>>() private fun getListForChar(c : Char) : MutableList<Bin> { if (map[c] == null) { map[c] = mutableListOf() } return map[c]!! } var index = -1 var hasInitialized = false var count = 0 fun push(c : Char) { index++ if (index >= capacity) { hasInitialized = true index = 0 } if (!hasInitialized) { addChar(c) } else { emptyCurrentBin() addChar(c) } } private fun addChar(c: Char) { val bin = binList[index] bin.content = c val list = getListForChar(c) list.add(bin) val size = list.size - 1 count += (Math.pow(2.0, size.toDouble())).toInt() } private fun emptyCurrentBin() { val bin = binList[index] val list = getListForChar(bin.content) val size = list.size - 1 count -= (Math.pow(2.0, size.toDouble())).toInt() list.remove(bin) } fun isAllDistinct() : Boolean { return count == capacity } } fun part1(input: List<String>): Int { val line = input[0] val capacity = 4 val window = CharacterWindow(capacity) for ((index, c) in line.withIndex()) { window.push(c) if (window.isAllDistinct()) { return index + 1 } } return 0 } fun part2(input: List<String>): Int { val line = input[0] val capacity = 14 val window = CharacterWindow(capacity) for ((index, c) in line.withIndex()) { window.push(c) if (window.isAllDistinct()) { return index + 1 } } return 0 } val input = readInput(6) println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
ae153c99b58ba3749f16b3fe53f06a4b557105d3
2,465
aoc-2022
Apache License 2.0
src/chapter08/_8_1_2/_8_1_6_去除重复代码.kt
xu33liang33
252,216,839
false
null
package chapter08._8_1_2 data class SiteVisit( val path: String, val dutation: Double, val os: OS ) //函数类型和lambda 一起去除重复代码 enum class OS { WINDOWS, LINUX, MAC, IOS, ANDROID } fun main(args: Array<String>) { val log = listOf( SiteVisit("/", 34.0, OS.WINDOWS), SiteVisit("/", 22.0, OS.MAC), SiteVisit("/login", 12.0, OS.WINDOWS), SiteVisit("/signup", 8.0, OS.IOS), SiteVisit("/", 16.3, OS.ANDROID) ) println(log.filter { it.os == OS.WINDOWS } .map(SiteVisit::dutation)) //计算windows平均时间 val averageWindows = log.filter { it.os == OS.WINDOWS } .map(SiteVisit::dutation) .average() println(averageWindows) // println(log.filter { it.os == OS.WINDOWS } // .map(SiteVisit::dutation)) val averageMobile = log.filter { it.os in setOf(OS.IOS, OS.ANDROID) } .map(SiteVisit::dutation) .average() println(averageMobile) /** * 普通去重方法 */ println() println("log.averageDuration(OS.ANDROID)") println(log.averageDuration(OS.ANDROID)) println("------------------------") /** * 将需要的条件抽到函数类型参数中 */ println(log.averageDurationFor { it.os in setOf(OS.ANDROID, OS.IOS) }) println(log.averageDurationFor { it.os == OS.IOS && it.path == "/signup" }) } /** * 普通方法去重 */ fun List<SiteVisit>.averageDuration(os: OS) = filter { it.os == os } .map(SiteVisit::dutation) .average() /** * 将需要的条件抽到函数类型参数中 * 不仅抽取重复数据,也能抽取重复行为 */ fun List<SiteVisit>.averageDurationFor(predicate: (SiteVisit) -> Boolean) = filter(predicate) .map(SiteVisit::dutation) .average()
0
Kotlin
0
1
cdc74e445c8c487023fbc7917183d47e73ff4bc8
1,934
actioninkotlin
Apache License 2.0
src/main/kotlin/adventofcode2018/Day07TheSumOfItsParts.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 class Day07TheSumOfItsParts enum class Step { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z } data class Instruction(val step: Step, val preSteps: MutableSet<Step> = mutableSetOf()) data class ConcurrentWorker(var executionTime: Int = 0, var busy: Boolean = false) { fun isAvailable(processTime: Int) = executionTime <= processTime } class SleighProcessor(input: List<String>, private val numberOfSteps: Int) { val instructions: MutableList<Instruction> init { instructions = Step.values().take(numberOfSteps).map { Instruction(it) }.toMutableList() parseInput(input) } private fun parseInput(input: List<String>) { input.forEach { instruction -> val step = Step.valueOf(instruction.substringAfter("step ").substring(0, 1)) val preStep = Step.valueOf(instruction.substringAfter("Step ").substring(0, 1)) instructions.find { it.step == step }?.preSteps?.add(preStep) } } fun executeInstructions(): String { return buildString { while (instructions.isNotEmpty()) { val nextInstruction = instructions.first { it.preSteps.isEmpty() } append(nextInstruction.step) instructions.forEach { instruction -> instruction.preSteps.remove(nextInstruction.step) } instructions.remove(nextInstruction) } } } fun executeConcurrently(numberOfWorkers: Int): Int { var totalTime = 0 var maxTime = 0 val workers = List(numberOfWorkers) { ConcurrentWorker() } while (instructions.isNotEmpty()) { var subTime = 0 val pendingInstructions = instructions.filter { it.preSteps.isEmpty() } pendingInstructions.forEach { nextInstruction -> val availableWorker = workers.firstOrNull { !(it.busy) } ?: workers.minBy { it.executionTime } val currentExecutionTime = nextInstruction.step.ordinal + 1 availableWorker.executionTime = totalTime + subTime + currentExecutionTime subTime += currentExecutionTime instructions.forEach { instruction -> instruction.preSteps.remove(nextInstruction.step) } instructions.remove(nextInstruction) workers.forEach { worker -> worker.busy = worker.executionTime >= totalTime + subTime + 1 } } totalTime += subTime } println("total time: $totalTime") return workers.maxOf { it.executionTime } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,650
kotlin-coding-challenges
MIT License
year2020/src/main/kotlin/net/olegg/aoc/year2020/day12/Day12.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2020.day12 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.CCW import net.olegg.aoc.utils.Directions.Companion.CW import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2020.DayOf2020 /** * See [Year 2020, Day 12](https://adventofcode.com/2020/day/12) */ object Day12 : DayOf2020(12) { override fun first(): Any? { val route = lines.map { it.first() to it.drop(1).toInt() } val target = route.fold(Vector2D() to R) { acc, (op, size) -> when (op) { 'N' -> acc.first + U.step * size to acc.second 'W' -> acc.first + L.step * size to acc.second 'E' -> acc.first + R.step * size to acc.second 'S' -> acc.first + D.step * size to acc.second 'L' -> acc.first to (0..<size / 90).fold(acc.second) { dir, _ -> CCW[dir] ?: dir } 'R' -> acc.first to (0..<size / 90).fold(acc.second) { dir, _ -> CW[dir] ?: dir } 'F' -> acc.first + acc.second.step * size to acc.second else -> acc } } return target.first.manhattan() } override fun second(): Any? { val route = lines.map { it.first() to it.drop(1).toInt() } val target = route.fold(Vector2D() to Vector2D(10, -1)) { acc, (op, size) -> when (op) { 'N' -> acc.first to acc.second + U.step * size 'W' -> acc.first to acc.second + L.step * size 'E' -> acc.first to acc.second + R.step * size 'S' -> acc.first to acc.second + D.step * size 'L' -> acc.first to (0..<size / 90).fold(acc.second) { dir, _ -> Vector2D(dir.y, -dir.x) } 'R' -> acc.first to (0..<size / 90).fold(acc.second) { dir, _ -> Vector2D(-dir.y, dir.x) } 'F' -> acc.first + acc.second * size to acc.second else -> acc } } return target.first.manhattan() } } fun main() = SomeDay.mainify(Day12)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,025
adventofcode
MIT License
src/Day01.kt
zuevmaxim
572,255,617
false
{"Kotlin": 17901}
fun main() { fun part1(input: List<String>): Int { var current = 0 var result = 0 fun updateMax() { if (result < current) result = current current = 0 } for (s in input) { if (s.isEmpty()) { updateMax() } else { current += s.toInt() } } updateMax() return result } fun part2(input: List<String>): Int { var current = 0 val result = mutableListOf<Int>() for (s in input) { if (s.isEmpty()) { result.add(current) current = 0 } else { current += s.toInt() } } result.add(current) result.sortDescending() return result.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
34356dd1f6e27cc45c8b4f0d9849f89604af0dfd
1,053
AOC2022
Apache License 2.0
src/main/java/dev/haenara/mailprogramming/solution/y2019/m12/d15/Solution191215.kt
HaenaraShin
226,032,186
false
null
package dev.haenara.mailprogramming.solution.y2019.m12.d15 import dev.haenara.mailprogramming.solution.Solution /** * 매일프로그래밍 2019. 12. 15 * 정수 배열이 주어졌을 때, 왼쪽과 오른쪽의 합이 같은 값이 되는 위치를 찾으시오. * 즉, A라는 배열이 있다면 A[0] + … + A[i - 1]과 A[i + 1] + … + A[n]이 같은 값이 되는 i의 위치가 답이 됩니다. * 만약 A[1] + … + A[n]이 0이라면 0도 답이 됩니다. * * Input: [0, -3, 5, -4, -2, 3, 1, 0] * Output: [0, 3, 7] * * 풀이 : * 전체를 오른쪽 합계(rightSum)에 넣어놓은 다음 한개씩 빼서 왼쪽 합계(leftSum)에 넣어가면서 진행한다. * 왼쪽 합계(leftSum)와 오른쪽 합계(rightSum)가 같으면 정답에 추가한다. */ class Solution191215 : Solution<Array<Int>, Array<Int>>{ override fun solution(input: Array<Int>): Array<Int> { var leftSum = 0 var rightSum = input.sum() val answerList = arrayListOf<Int>() for ((index, value) in input.withIndex()){ rightSum -= value if (leftSum == rightSum) { answerList.add(index) } leftSum += value } return answerList.toTypedArray() } }
0
Kotlin
0
7
b5e50907b8a7af5db2055a99461bff9cc0268293
1,262
MailProgramming
MIT License
src/Day08.kt
ixtryl
575,312,836
false
null
import java.lang.IllegalArgumentException import java.util.* object DAY08 { fun run(fileName: String): Int { val lines = readInput(fileName) val forest: List<List<Int>> = createForest(lines) val matrix: List<List<Int>> = createVisibilityMatrix(forest) return calculateVisableTrees(matrix) } fun run2(fileName: String): Int { val lines = readInput(fileName) val forest: List<List<Int>> = createForest(lines) val matrix: List<List<Int>> = createScenicScoreMatrix(forest) return getHeighestScenicScore(matrix) } private fun getHeighestScenicScore(matrix: List<List<Int>>): Int { var maxScore = 0 matrix.forEach { row -> row.forEach { if (it > maxScore) maxScore = it } } return maxScore } private fun createScenicScoreMatrix(forest: List<List<Int>>): List<List<Int>> { val matrix: MutableList<MutableList<Int>> = mutableListOf() val columns = forest[0].size forest.forEach { _ -> matrix.add(ArrayList(Collections.nCopies(columns, 0))) } for (rowIndex in forest.indices) { val row = forest[rowIndex] for (colIndex in row.indices) { val treeHeight = forest[rowIndex][colIndex] var up = 0 var down = 0 var left = 0 var right = 0 // Up for (treeRow in rowIndex - 1 downTo 0) { val height = forest[treeRow][colIndex] up++ if (treeHeight <= height) break } // Down for (treeRow in rowIndex + 1 until forest.size) { val height = forest[treeRow][colIndex] down++ if (treeHeight <= height) break } // Left for (treeCol in colIndex - 1 downTo 0) { val height = forest[rowIndex][treeCol] left++ if (treeHeight <= height) break } // Right for (treeCol in colIndex + 1 until columns) { val height = forest[rowIndex][treeCol] right++ if (treeHeight <= height) break } matrix[rowIndex][colIndex] = up * down * left * right } } return matrix } private fun calculateVisableTrees(matrix: List<List<Int>>): Int { var result = 0 matrix.forEach { row -> row.forEach { result += it } } return result } private fun createVisibilityMatrix(forest: List<List<Int>>): List<List<Int>> { val matrix: MutableList<MutableList<Int>> = mutableListOf() val columns = forest[0].size forest.forEach { _ -> matrix.add(ArrayList(Collections.nCopies(columns, 0))) } for (rowIndex in forest.indices) { matrix[rowIndex][0] = 1 matrix[rowIndex][columns - 1] = 1 } for (colIndex in 0 until columns) { matrix[0][colIndex] = 1 matrix[forest.size - 1][colIndex] = 1 } for (rowIndex in forest.indices) { var height = 0 val row = forest[rowIndex] for (colIndex in row.indices) { val treeHeight = forest[rowIndex][colIndex] if (treeHeight > height) { matrix[rowIndex][colIndex] = 1 height = treeHeight } } } for (rowIndex in forest.indices) { var height = 0 val row = forest[rowIndex] for (colIndex in row.lastIndex downTo 0) { val treeHeight = forest[rowIndex][colIndex] if (treeHeight > height) { matrix[rowIndex][colIndex] = 1 height = treeHeight } } } for (colIndex in 0 until columns) { var height = 0 for (rowIndex in forest.indices) { val treeHeight = forest[rowIndex][colIndex] if (treeHeight > height) { matrix[rowIndex][colIndex] = 1 height = treeHeight } } } for (colIndex in 0 until columns) { var height = 0 for (rowIndex in forest.lastIndex downTo 0) { val treeHeight = forest[rowIndex][colIndex] if (treeHeight > height) { matrix[rowIndex][colIndex] = 1 height = treeHeight } } } return matrix } private fun createForest(lines: List<String>): List<List<Int>> { val forest: MutableList<MutableList<Int>> = mutableListOf() for ((row, line) in lines.withIndex()) { forest.add(mutableListOf()) for ((col, char) in line.withIndex()) { forest[row].add(Integer.parseInt(char.toString())) } } return forest } } fun main() { if (DAY08.run("Day08_test") != 21) { throw RuntimeException("Fail: Expected 21") } if (DAY08.run("Day08") != 1763) { throw RuntimeException("Fail: Expected 1763") } if (DAY08.run2("Day08_test") != 8) { throw RuntimeException("Fail: Expected 8") } if (DAY08.run2("Day08") != 671160) { throw RuntimeException("Fail: Expected 671160") } }
0
Kotlin
0
0
78fa5f6f85bebe085a26333e3f4d0888e510689c
5,562
advent-of-code-kotlin-2022
Apache License 2.0
2023/src/main/kotlin/net/daams/solutions/10a.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution import java.util.Stack class `10a`(input: String): Solution(input) { private val pipes = mutableListOf<MutableList<Pipe?>>() private lateinit var startingLocation: Pair<Int, Int> override fun run() { input.split("\n").forEachIndexed { y, pipeRow -> val p = mutableListOf<Pipe?>() pipeRow.forEachIndexed { x, c -> if (c != '.') { val pipeToAdd = Pipe(c, Pair(y, x)) if (c == 'S') startingLocation = Pair(y, x) p.add(pipeToAdd) } else p.add(null) } pipes.add(p) } var loopFound = false val types = Stack<Char>() types.push('7') types.push('J') types.push('F') types.push('L') types.push('-') types.push('|') var loopLength = 0 while (!loopFound) { pipes[startingLocation.first][startingLocation.second]!!.pipe = types.pop() pipes.forEach { pipez -> pipez.forEach { it?.makeConnections(pipes) } } loopLength = 0 var prev: Pipe? = null var current: Pipe = pipes[startingLocation.first][startingLocation.second]!! while (true) { loopLength++ val next = getNext(prev, current) ?: break if (next.location == startingLocation) { loopFound = true break } prev = current current = next } } println(loopLength) println(loopLength / 2) println(pipes[startingLocation.first][startingLocation.second]) } } fun getNext(prev: Pipe?, current: Pipe): Pipe? { if (prev == null) { if (current.connection2 != null && (current.connection2!!.connection1 == current || current.connection2!!.connection2 == current)) return current.connection2 if (current.connection1 != null && (current.connection1!!.connection1 == current || current.connection1!!.connection2 == current)) return current.connection1 return null } return if (current.connection1 == prev){ if (current.connection2 != null && (current.connection2!!.connection1 == current || current.connection2!!.connection2 == current)) { current.connection2 } else null } else { if (current.connection1 != null && (current.connection1!!.connection1 == current || current.connection1!!.connection2 == current)) { current.connection1 } else null } } class Pipe(var pipe: Char, val location: Pair<Int, Int>) { var connection1: Pipe? = null var connection2: Pipe? = null fun makeConnections(gridToCheck: List<List<Pipe?>>) { connection1 = null connection2 = null var connectionToMake: Pair<Pair<Int, Int>, Pair<Int, Int>> = Pair(Pair(-1, -1), Pair(-1, -1)) if (pipe == 'F') connectionToMake = Pair(Pair(location.first + 1, location.second), Pair(location.first, location.second + 1)) if (pipe == 'J') connectionToMake = Pair(Pair(location.first -1, location.second), Pair(location.first, location.second - 1)) if (pipe == '7') connectionToMake = Pair(Pair(location.first, location.second - 1), Pair(location.first + 1, location.second)) if (pipe == 'L') connectionToMake = Pair(Pair(location.first, location.second + 1), Pair(location.first - 1, location.second)) if (pipe == '|') connectionToMake = Pair(Pair(location.first - 1, location.second), Pair(location.first + 1, location.second)) if (pipe == '-') connectionToMake = Pair(Pair(location.first, location.second + 1), Pair(location.first, location.second - 1)) try { connection1 = gridToCheck[connectionToMake.first.first][connectionToMake.first.second] } catch (_: IndexOutOfBoundsException) {} try { connection2 = gridToCheck[connectionToMake.second.first][connectionToMake.second.second] } catch (_: IndexOutOfBoundsException) {} } override fun equals(other: Any?): Boolean { return other is Pipe && other.location == this.location } override fun toString(): String { return pipe.toString() } } fun MutableList<Pipe?>.toGrid(): String { var s = "" this.forEach { s += it?.pipe ?: '.' } return s }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
4,464
advent-of-code
MIT License
src/main/kotlin/day6/solver.kt
derekaspaulding
317,756,568
false
null
package day6 import java.io.File fun solveProblemOne(groups: List<List<String>>): Int = groups.fold(0, {sum, group -> val charSet = mutableSetOf<Char>() for (answer in group) { for (char in answer) { charSet.add(char) } } sum + charSet.size }) fun solveProblemTwo(groups: List<List<String>>): Int = groups.fold(0, {sum, group -> val charSet = mutableSetOf<Char>() for (answer in group) { for (char in answer) { if (group.all { a -> a.contains(char) }) { charSet.add(char) } } } sum + charSet.size }) fun main() { val inputText = File("src/main/resources/day6/input.txt").readText() val groups = inputText.split("\n\n").map { it.split("\n") } println("Sum where anyone answered yes: ${solveProblemOne(groups)}") println("Sum where everyone answered yes: ${solveProblemTwo(groups)}") }
0
Kotlin
0
0
0e26fdbb3415fac413ea833bc7579c09561b49e5
928
advent-of-code-2020
MIT License
src/main/kotlin/puzzle13/OrigamiSolver.kt
tpoujol
436,532,129
false
{"Kotlin": 47470}
package puzzle13 import kotlin.system.measureTimeMillis fun main() { val origamiSolver = OrigamiSolver() val time = measureTimeMillis { println("number of dots after one fold: ${origamiSolver.countDotsAfterFirstFold()}") println("Final Layout is:\n${origamiSolver.foldLayoutEntirely()}") } println("time: $time") } fun List<List<Boolean>>.printLayout( fold: FoldInstruction? = null ): String = buildString { for ((i, line) in this@printLayout.withIndex()) { for ((j, b) in line.withIndex()) { if (b) { append("#") } else if (fold is VerticalFoldInstruction && j == fold.x) { append("|") } else if (fold is HorizontalFoldInstruction && i == fold.y) { append("—") } else { append(" ") } } appendLine() } } data class Position(val x: Int, val y: Int) sealed interface FoldInstruction { fun performFold(layout: List<List<Boolean>>): List<List<Boolean>> } data class VerticalFoldInstruction(val x: Int): FoldInstruction { override fun performFold(layout: List<List<Boolean>>): List<List<Boolean>> { val newLayout = MutableList(layout.size) { MutableList(x) { false } } for (j in 0 until x) { val verticallySymmetricColumn = layout[0].size - j - 1 for (i in layout.indices) { newLayout[i][j] = layout[i][j] || layout[i][verticallySymmetricColumn] } } return newLayout .map { it.toList() } .toList() } } data class HorizontalFoldInstruction(val y: Int): FoldInstruction { override fun performFold(layout: List<List<Boolean>>): List<List<Boolean>> { val newLayout = MutableList(y) { MutableList(layout[0].size) { false } } for (i in y downTo 1){ val above = y - i val under = y + i for (j in layout[0].indices) { newLayout[y - i][j] = layout.getOrNull(under)?.getOrNull(j)?: false || layout.getOrNull(above)?.getOrNull(j) ?: false } } return newLayout .map { it.toList() } .toList() } } fun List<Position>.createLayout(): List<List<Boolean>> = MutableList(this.maxOf { it.y } + 1) { MutableList(this.maxOf { it.x } + 1) { false } } .apply { this@createLayout.forEach { this[it.y][it.x] = true } } .map { it.toList() } .toList() class OrigamiSolver { private val input = OrigamiSolver::class.java.getResource("/input/puzzle13.txt") ?.readText() ?: "" private val dotPosition = input .split("\n\n")[0] .split("\n") .map { val (x, y) = it.split(",") Position(x.toInt(), y.toInt()) } private val foldingInstructions = input .split("\n\n")[1] .split("\n") .map { s: String -> val (axis, value) = s.removePrefix("fold along ").split("=") when (axis) { "y" -> HorizontalFoldInstruction(value.toInt()) "x" -> VerticalFoldInstruction(value.toInt()) else -> error(axis) } } fun countDotsAfterFirstFold(): Int = foldingInstructions[0] .performFold(dotPosition.createLayout()) .flatten() .count { it } fun foldLayoutEntirely(): String = foldingInstructions .fold(dotPosition.createLayout()) { acc, foldInstruction -> foldInstruction.performFold(acc) }.printLayout() }
0
Kotlin
0
1
6d474b30e5204d3bd9c86b50ed657f756a638b2b
3,596
aoc-2021
Apache License 2.0
src/main/kotlin/com/github/javadev/select/QuickSelect.kt
javadev
156,964,261
false
null
package com.github.javadev.select /** * Quickselect is a selection algorithm to find the kth smallest element * in an unordered list. It is related to the quicksort sorting algorithm */ /* public class QuickSelect { public Integer quickSelect(int[] array, int k) { return quickSelect(array, 0, array.length - 1, k); } Integer quickSelect(int[] array, int low, int high, int k) { if (k < 1 || k > array.length) { return null; } if (low == high) { return array[low]; } int p = partition(array, low, high); int leftSize = p - low + 1; if (leftSize == k) { return array[p]; } else if (k < leftSize) { return quickSelect(array, low, p - 1, k); } else { return quickSelect(array, p + 1, high, k - leftSize); } } int partition(int[] array, int first, int last) { int pivot = array[first]; int low = first + 1; int high = last; while (low < high) { // Search forward from left while (low <= high && array[low] <= pivot) { low++; } // Search backward from right while (low <= high && array[high] > pivot) { high--; } // Swap two elements in the list if (high > low) { swap(array, low, high); } } while (high > first && array[high] >= pivot) { high--; } // Swap pivot with list[high] if (pivot > array[high]) { array[first] = array[high]; array[high] = pivot; return high; } else { return first; } } void swap(int[] a, int l, int r) { int v = a[l]; a[l] = a[r]; a[r] = v; } } */ class QuickSelect { fun quickSelect(array:IntArray, k:Int):Int? { return quickSelect(array, 0, array.size - 1, k) } internal fun quickSelect(array:IntArray, low:Int, high:Int, k:Int):Int? { if (k < 1 || k > array.size) { return null } if (low == high) { return array[low] } val p = partition(array, low, high) val leftSize = p - low + 1 if (leftSize == k) { return array[p] } else if (k < leftSize) { return quickSelect(array, low, p - 1, k) } else { return quickSelect(array, p + 1, high, k - leftSize) } } internal fun partition(array:IntArray, first:Int, last:Int):Int { val pivot = array[first] var low = first + 1 var high = last while (low < high) { // Search forward from left while (low <= high && array[low] <= pivot) { low++ } // Search backward from right while (low <= high && array[high] > pivot) { high-- } // Swap two elements in the list if (high > low) { swap(array, low, high) } } while (high > first && array[high] >= pivot) { high-- } // Swap pivot with list[high] if (pivot > array[high]) { array[first] = array[high] array[high] = pivot return high } else { return first } } internal fun swap(a:IntArray, l:Int, r:Int) { val v = a[l] a[l] = a[r] a[r] = v } }
0
Kotlin
0
5
3f71122f1d88ee1d83acc049f9f5d44179c34147
3,142
classic-cherries-kotlin
Apache License 2.0
src/main/kotlin/com/zachjones/languageclassifier/core/DecisionTree.kt
zachtjones
184,465,284
false
{"Kotlin": 73431}
package com.zachjones.languageclassifier.core import com.zachjones.languageclassifier.attribute.Attribute import com.zachjones.languageclassifier.core.AbsoluteDecider.Companion.fromLanguage import com.zachjones.languageclassifier.entities.InputRow import com.zachjones.languageclassifier.entities.LanguageDecision import com.zachjones.languageclassifier.entities.WeightedList import com.zachjones.languageclassifier.entities.spaces import com.zachjones.languageclassifier.model.types.Language import java.util.function.Predicate import kotlin.math.ln class DecisionTree /** Creates a decision tree given the left and right decisions, and the index of the attributes it splits on. */ private constructor(// could be a tree or a -- if false, this is evaluated private val left: Decider, // could be a tree of b -- if true, this is evaluated private val right: Decider, // attribute to split on private val splitOn: Attribute ) : Decider { /** Instance method to make the decision on input. */ override fun decide(row: InputRow): LanguageDecision { // recursive, test the inputs on the left and right side return if (splitOn.has(row)) right.decide(row) else left.decide(row) } /** How this should be represented as a string. */ override fun representation(numSpaces: Int): String { // I'm making it like a code block. return """if ${splitOn.name()} then: ${(numSpaces + 2).spaces()}${right.representation(numSpaces + 2)} ${numSpaces.spaces()}else: ${(numSpaces + 2).spaces()}${left.representation(numSpaces + 2)}""" } companion object { private fun languageIs(language: Language): Predicate<Pair<Double, InputRow>> { return Predicate { i: Pair<Double, InputRow> -> i.second.language == language } } /** * Picks the best decision tree to represent the decision at this level, with the options left. * This is a binary classifier of the two values provided. * Precondition: * all data is either languageOne or languageTwo * @param allData The weighted data this tree should decide on. (portion of the original data) * @param levelLeft The amount of tree depth left, if this is 0, then it will be decide always the one output. * @param optionsLeft The options that are left to choose from to split on. * @param totalSize The total size of the original data, not just what this has to choose from. * @param languageOne The first language * @param languageTwo The second language * @return A learned decision tree. */ fun learn( allData: WeightedList<InputRow>, levelLeft: Int, optionsLeft: Set<Attribute>, totalSize: Int, languageOne: Language, languageTwo: Language? ): Decider { require(allData.size() != 0) { "All data size should not be 0" } // count how many have output LanguageOne val countOne = allData.stream().filter(languageIs(languageOne)).count() // base case 1: there is no levels left to iterate - make a definite decision. if (levelLeft == 0) { // return the majority by total weight val weightOne = allData.stream().filter(languageIs(languageOne)) .mapToDouble { i: Pair<Double, InputRow> -> i.first } .sum() val totalWeight = allData.totalWeight() return ConfidenceDecider(languageOne, languageTwo!!, weightOne / totalWeight) } // base case 2: there is all of one type if (allData.size().toLong() == countOne) { // all are the first one return fromLanguage(languageOne) } else if (countOne == 0L) { // none are the first one, they are all the second return fromLanguage(languageTwo!!) } // split on the best attribute - based on information gain val result = optionsLeft.stream() .map { i: Attribute -> Pair( i, entropyForDecision(i, allData, totalSize, languageOne) ) } // pair<att, entropy> .min(Comparator.comparingDouble { pair: Pair<Attribute, Double> -> pair.second }) // result should be present -- if not we still have depth left but have exhausted options if (result.isEmpty) { // ran out of options, just return the majority return learn(allData, 0, emptySet(), totalSize, languageOne, languageTwo) } val best = result.get().first val trueOnes = allData.valuesWith { input: InputRow? -> best.has( input!! ) } val falseOnes = allData.valuesWith { input: InputRow? -> best.doesntHave( input!! ) } // need copies so they don't modify each other val optionsLeftFalse: MutableSet<Attribute> = HashSet(optionsLeft) optionsLeftFalse.remove(best) val optionsLeftTrue: MutableSet<Attribute> = HashSet(optionsLeft) optionsLeftTrue.remove(best) // single recursive where this attribute does not help if (trueOnes.size() == 0) { return learn(falseOnes, levelLeft, optionsLeftFalse, totalSize, languageOne, languageTwo) } if (falseOnes.size() == 0) { return learn(trueOnes, levelLeft, optionsLeftTrue, totalSize, languageOne, languageTwo) } // do the recursive calls val left = learn(falseOnes, levelLeft - 1, optionsLeftFalse, totalSize, languageOne, languageTwo) val right = learn(trueOnes, levelLeft - 1, optionsLeftTrue, totalSize, languageOne, languageTwo) // return the created tree return DecisionTree(left, right, best) } /** Returns the entropy associated with a decision to split on attribute index. */ private fun entropyForDecision( attribute: Attribute, allData: WeightedList<InputRow>, totalSize: Int, languageOne: Language ): Double { // split into the two sets - calculate entropy on each val falseOnes = allData.valuesWith { input: InputRow? -> attribute.doesntHave( input!! ) } val trueOnes = allData.valuesWith { input: InputRow? -> attribute.has( input!! ) } // entropy for each half * the proportion of the whole it is. return trueOnes.size().toDouble() / totalSize * entropyForList(trueOnes, languageOne) + falseOnes.size().toDouble() / totalSize * entropyForList(falseOnes, languageOne) } /** Returns the entropy for a list of data in bits. */ private fun entropyForList(allData: WeightedList<InputRow>, languageOne: Language): Double { // if there's no data, entropy is 0 if (allData.size() == 0) return 0.0 val total = allData.totalWeight() // arbitrary - defined first to be true (doesn't matter since symmetric distribution). val eAmount = allData.valuesWith { i: InputRow -> i.language == languageOne }.totalWeight() return entropyForBoolean(eAmount / total) } /** Returns the entropy for a weighted boolean random variable. */ @JvmStatic fun entropyForBoolean(trueChance: Double): Double { // 0 or 1 will result in NaN, but it should be 0. if (trueChance == 0.0 || trueChance == 1.0) { return 0.0 } // from the book −(q log2 q + (1 − q) log2(1 − q)) val falseChance = 1 - trueChance return -(trueChance * log2(trueChance) + falseChance * log2(falseChance)) } /** Returns the log base two of a number. */ fun log2(x: Double): Double { // log2 not defined in java in the Math class. return ln(x) / ln(2.0) } } }
0
Kotlin
0
1
dfe8710fcf8daa1bc57ad90f7fa3c07a228b819f
8,352
Multi-Language-Classifier
Apache License 2.0
src/main/Day08.kt
lifeofchrome
574,709,665
false
{"Kotlin": 19233}
package main import readInput fun main() { val input = readInput("Day08") val day08 = Day08(input) println("Part 1: " + day08.part1()) println("Part 2: " + day08.part2()) } class Day08(input: List<String>) { private var map: List<List<Int>> init { val tmp = mutableListOf<MutableList<Int>>() for(line in input) { val list = mutableListOf<Int>() for(tree in line) { list.add(tree.toString().toInt()) } tmp.add(list) } map = tmp } private fun List<List<Int>>.isVisible(row: Int, col: Int): Boolean { val results = MutableList(4) { false } for(i in 0 until row) { // up if(this[i][col] >= this[row][col]) { results[0] = false break } results[0] = true } for(i in row + 1 until this.size) { // down if(this[i][col] >= this[row][col]) { results[1] = false break } results[1] = true } for(i in 0 until col) { // left if(this[row][i] >= this[row][col]) { results[2] = false break } results[2] = true } for(i in col + 1 until this[row].size) { // right if(this[row][i] >= this[row][col]) { results[3] = false break } results[3] = true } return results.any { it } } private fun List<List<Int>>.viewDistances(row: Int, col: Int): List<Int> { val results = MutableList(4) { 0 } for(i in row - 1 downTo 0 ) { // up results[0]++ if(this[i][col] >= this[row][col]) { break } } for(i in row + 1 until this.size) { // down results[1]++ if(this[i][col] >= this[row][col]) { break } } for(i in col - 1 downTo 0) { // left results[2]++ if(this[row][i] >= this[row][col]) { break } } for(i in col + 1 until this[row].size) { // right results[3]++ if(this[row][i] >= this[row][col]) { break } } return results } fun part1(): Int { var numVisible = (map.size * 2) + ((map[0].size - 2) * 2) for(row in 1..map.size - 2) { for(col in 1..map[row].size - 2) { if(map.isVisible(row, col)) { numVisible++ } } } return numVisible } fun part2(): Int { var highest = 0 for(row in 1..map.size - 2) { for(col in 1..map[row].size - 2) { var current = 1 map.viewDistances(row, col).forEach { current *= it } if(current > highest) { highest = current } } } return highest } }
0
Kotlin
0
0
6c50ea2ed47ec6e4ff8f6f65690b261a37c00f1e
3,126
aoc2022
Apache License 2.0
src/main/kotlin/day4/Aoc.kt
widarlein
225,589,345
false
null
package day4 fun main(args: Array<String>) { if (args.isEmpty()) { println("Must provide input program") System.exit(0) } val (rangeStart, rangeStop) = args[0].split("-") val validPasswords = countValidPart1Passwords(rangeStart, rangeStop) println("Number of valid part1 passwords between $rangeStart-$rangeStop is $validPasswords") val validPart2Passwords = countValidPart2Passwords(rangeStart, rangeStop) println("Number of valid part2 passwords between $rangeStart-$rangeStop is $validPart2Passwords") } internal fun countValidPart1Passwords(start: String, stop: String): Int { var count = 0 var next = selfOrNextNonDecreasing(start) while (next.toInt() <= stop.toInt()) { if (hasTwoAdjacentMatchingDigits(next)) { count++ } next = selfOrNextNonDecreasing(next.inc()) } return count } internal fun countValidPart2Passwords(start: String, stop: String): Int { var count = 0 var next = selfOrNextNonDecreasing(start) while (next.toInt() <= stop.toInt()) { if (hasExactlyTwoAdjacentMatchingDigits(next)) { count++ } next = selfOrNextNonDecreasing(next.inc()) } return count } internal fun selfOrNextNonDecreasing(code: String): String { val index = indexOfDecreasingDigit(code) if (index == -1) return code return code.substring(0, index).padEnd(6, code[index - 1]) } internal fun String.inc() = (this.toInt() + 1).toString() private fun indexOfDecreasingDigit(code: String): Int { code.forEachIndexed { i, c -> if (i != 0) { if (c < code[i - 1]) { return i } } } return -1 } internal fun hasExactlyTwoAdjacentMatchingDigits(code: String): Boolean { code.forEachIndexed { index, c -> if (index != 0) { if (index == 1) { if (c == code[index - 1] && c != code[index + 1]) { return true } } else if (index == code.lastIndex) { if (c == code[index - 1] && c != code[index - 2]) { return true } } else { if (c == code[index - 1] && c != code[index - 2] && c != code[index + 1]) { return true } } } } return false } internal fun hasTwoAdjacentMatchingDigits(code: String): Boolean { code.forEachIndexed { index, c -> if (index != 0) { if (c == code[index - 1]) { return true } } } return false } internal fun countValidPart2PasswordsFail(start: String, stop: String): Int { var count = 0 var next = selfOrNextNonDecreasing(start) next = makeNonMultiAdjacent(next) while (next.toInt() <= stop.toInt()) { if (hasTwoAdjacentMatchingDigits(next)) { count++ } next = selfOrNextNonDecreasing(next.inc()) next = makeNonMultiAdjacent(next) } return count } internal tailrec fun makeNonMultiAdjacent(code: String): String { val index = indexOfThirdAdjacentDigit(code) if (index == -1) return code var prefix = code.substring(0, index) val overflow = prefix.last() == '9' // "112999" gives prefix 11299 if (overflow) { prefix = (prefix.toInt() + 1).toString() // New prefix 11300, this is decreasing and will always need to be fixed } // newPrefix.last() should never be '9' val paddedCode = prefix.padEnd(6, unsafeIncChar(prefix.last())) // get next non decreasing if overflow happened earlier return makeNonMultiAdjacent(if (overflow) selfOrNextNonDecreasing(paddedCode) else paddedCode) } // Only works if char is '0' - '8', hence unsafe. internal fun unsafeIncChar(char: Char): Char { return (Character.getNumericValue(char) + 1 + 48).toChar() } internal fun indexOfThirdAdjacentDigit(code: String): Int { code.forEachIndexed { i, c -> if (i != 0 && i != 1) { if (c == code[i - 1] && c == code[i - 2]) { return i } } } return -1 }
0
Kotlin
0
0
b4977e4a97ad61177977b8eeb1dcf298067e8ab4
4,166
AdventOfCode2019
MIT License
src/main/kotlin/io/github/lawseff/aoc2023/matrix/MatrixProblemSolver.kt
lawseff
573,226,851
false
{"Kotlin": 37196}
package io.github.lawseff.aoc2023.matrix import io.github.lawseff.aoclib.Day import io.github.lawseff.aoclib.PartOne import io.github.lawseff.aoclib.PartTwo import java.util.LinkedList import java.util.Queue data class Gear(val partNumbers: List<Int>) @Day(3) // TODO split into classes and refactor the spaghetti code class MatrixProblemSolver { @PartOne fun sumPartNumbers(input: List<String>): Int { TODO("Didn't push the commit, before reinstalling the OS. Back up your work!") } @PartTwo fun sumGearRatios(input: List<String>): Int { val matrix = input.map { it.toCharArray() }.toTypedArray() fun getDigit(x: Int, y: Int): Int? { val row = matrix.getOrNull(y) ?: return null val cell = row.getOrNull(x) ?: return null return if (cell.isDigit()) { cell.digitToInt() } else { null } } fun getFirstNumberChars(startX: Int, y: Int, goForward: Boolean): String? { val builder = StringBuilder() val step = if (goForward) { 1 } else { -1 } val xQueue: Queue<Int> = LinkedList() xQueue.add(startX) while (xQueue.isNotEmpty()) { val xToCheck = xQueue.poll() val digit = getDigit(xToCheck, y) if (digit != null) { if (goForward) { builder.append(digit) } else { builder.insert(0, digit) } xQueue.add(xToCheck + step) } } return if (builder.isNotEmpty()) { builder.toString() } else { null } } // the digit at (startX, y) is included, if present fun getAdjacentNumbers(startX: Int, y: Int): List<Int> { val numbers = mutableListOf<Int>() val middleDigit = getDigit(startX, y) if (middleDigit != null) { val digits = (getFirstNumberChars(startX - 1, y, false) ?: "") + middleDigit.toString() + (getFirstNumberChars(startX + 1, y, true) ?: "") numbers.add(digits.toInt()) } else { val numberToLeft = getFirstNumberChars(startX - 1, y, false) if (numberToLeft != null) { numbers.add(numberToLeft.toInt()) } val numberToRight = getFirstNumberChars(startX + 1, y, true) if (numberToRight != null) { numbers.add(numberToRight.toInt()) } } return numbers } val gears = mutableListOf<io.github.lawseff.aoc2023.matrix.Gear>() matrix.forEachIndexed { y, rowArray -> rowArray.forEachIndexed { x, cell -> if (cell == '*') { val partNumbers = mutableListOf<Int>() val numbersAbove = getAdjacentNumbers(x, y - 1) partNumbers.addAll(numbersAbove) val numbersSameRow = getAdjacentNumbers(x, y) partNumbers.addAll(numbersSameRow) val numbersBelow = getAdjacentNumbers(x, y + 1) partNumbers.addAll(numbersBelow) if (partNumbers.size == 2) { val gear = io.github.lawseff.aoc2023.matrix.Gear(partNumbers) gears.add(gear) } } } } return gears.sumOf { calculateGearRatio(it) } } private fun calculateGearRatio(gear: io.github.lawseff.aoc2023.matrix.Gear): Int { return gear.partNumbers.reduce { product, partNumber -> product * partNumber } } }
0
Kotlin
0
0
b60ab611aec7bb332b8aa918aa7c23a43a3e61c8
3,929
advent-of-code-2023
MIT License
src/year2015/day23/Day23.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day23 import readInput fun main() { // test if implementation meets criteria from the description, like: val input = readInput("2015", "Day23") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val computer = Computer(input.toInstructions()) computer.executeProgram() return computer.b } private fun part2(input: List<String>): Int { val computer = Computer(input.toInstructions()) computer.a = 1 computer.executeProgram() return computer.b } private fun List<String>.toInstructions() = map { val (instruction, p1, p2) = it.split(", ").flatMap { p -> p.split(' ') } + "" when (instruction) { "hlf" -> Hlf(p1.toRegister()) "tpl" -> Tpl(p1.toRegister()) "inc" -> Inc(p1.toRegister()) "jmp" -> Jmp(p1.toInt()) "jie" -> Jie(p1.toRegister(), p2.toInt()) "jio" -> Jio(p1.toRegister(), p2.toInt()) else -> error("invalid instruction: $it") } } private fun String.toRegister() = when (this) { "a" -> Register.A "b" -> Register.B else -> error("$this is not a register") } private class Computer(val program: List<Instruction>) { var a: Int = 0 var b: Int = 0 var instructionIndex = 0 fun executeProgram() { while (instructionIndex in program.indices) { val instruction = program[instructionIndex] instruction.execute(this) } } } private enum class Register { A, B } private sealed interface Instruction { fun execute(computer: Computer) } private data class Hlf(val register: Register) : Instruction { override fun execute(computer: Computer) { when (register) { Register.A -> computer.a /= 2 Register.B -> computer.b /= 2 } computer.instructionIndex++ } } private data class Tpl(val register: Register) : Instruction { override fun execute(computer: Computer) { when (register) { Register.A -> computer.a *= 3 Register.B -> computer.b *= 3 } computer.instructionIndex++ } } private data class Inc(val register: Register) : Instruction { override fun execute(computer: Computer) { when (register) { Register.A -> computer.a++ Register.B -> computer.b++ } computer.instructionIndex++ } } private data class Jmp(val offset: Int) : Instruction { override fun execute(computer: Computer) { computer.instructionIndex += offset } } private data class Jie(val register: Register, val offset: Int) : Instruction { override fun execute(computer: Computer) { val v = when (register) { Register.A -> computer.a Register.B -> computer.b } if (v % 2 == 0) { computer.instructionIndex += offset } else { computer.instructionIndex++ } } } private data class Jio(val register: Register, val offset: Int) : Instruction { override fun execute(computer: Computer) { val v = when (register) { Register.A -> computer.a Register.B -> computer.b } if (v == 1) { computer.instructionIndex += offset } else { computer.instructionIndex++ } } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,347
AdventOfCode
Apache License 2.0
src/day24/day24.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day24 import readInput private fun parse(input: List<String>): Array<Array<Item>> { val board = Array(input.size) { Array<Item>(input[0].length) { Item.Free } } // first line for ((index, item) in input[0].withIndex()) { board[0][index] = if (item == '#') { Item.Wall } else if (item == '.') { Item.Entrance } else Item.Free } // last line for ((index, item) in input.last().withIndex()) { board[input.size - 1][index] = if (item == Item.Wall.element) { Item.Wall } else if (item == Item.Free.element) { Item.Exit } else Item.Free } for (index in 1 until input.size - 1) { val row = input[index] for ((colIndex, item) in row.withIndex()) { board[index][colIndex] = when (item) { Item.Free.element -> Item.Free Item.Wall.element -> Item.Wall else -> Item.Blizzard(mutableListOf(item)) } } } return board } private fun findEntrance(board: Array<Array<Item>>): Pair<Int, Int> { for ((index, item) in board[0].withIndex()) { if (item is Item.Entrance) return Pair(0, index) } throw IllegalStateException("There is no entrance") } private fun play(startPosition: Position, input: Array<Array<Item>>, destination: Item): Result { fun generateNextBoard(board: Array<Array<Item>>): Array<Array<Item>> { val changes = mutableListOf<IncomingBlizzard>() for (rowIndex in 1 until board.size - 1) { val row = board[rowIndex] for ((colIndex, item) in row.withIndex()) { if (item is Item.Blizzard) { changes.addAll(nextBlizzardPosition(rowIndex, colIndex, board.size, board[0].size, item)) } } } val newBoard = Array(board.size) { Array<Item>(board[0].size) { Item.Free } } newBoard[0] = board[0] newBoard[board.size - 1] = board[board.size - 1] for (change in changes) { val item = newBoard[change.row][change.col] if (item !is Item.Blizzard) { newBoard[change.row][change.col] = Item.Blizzard(mutableListOf(change.direction)) } else { item.items.add(change.direction) } } for (row in newBoard) { row[0] = Item.Wall row[board[0].size - 1] = Item.Wall } return newBoard } fun findNewPositions(positions: Set<Position>, board: Array<Array<Item>>): Set<Position> { return positions.map { val newOptions = mutableListOf<Position>() if (it.row - 1 >= 0 && (board[it.row - 1][it.col] == Item.Free || board[it.row - 1][it.col] == destination)) { newOptions.add(Position(it.minutes + 1, it.row - 1, it.col)) } if (it.row + 1 < board.size && (board[it.row + 1][it.col] == Item.Free || board[it.row + 1][it.col] == destination)) { newOptions.add(Position(it.minutes + 1, it.row + 1, it.col)) } if (it.col - 1 >= 0 && board[it.row][it.col - 1] == Item.Free) { newOptions.add(Position(it.minutes + 1, it.row, it.col - 1)) } if (it.col < board[0].size && board[it.row][it.col + 1] == Item.Free) { newOptions.add(Position(it.minutes + 1, it.row, it.col + 1)) } if (board[it.row][it.col] !is Item.Blizzard) { newOptions.add(Position(it.minutes + 1, it.row, it.col)) } newOptions } .flatten() .toSet() } var board = input var positions = setOf(startPosition) while (positions.isNotEmpty()) { val isExit = positions.firstOrNull { board[it.row][it.col] == destination } if (isExit != null) return Result(isExit, board) board = generateNextBoard(board) positions = findNewPositions(positions, board) } throw IllegalStateException("") } private fun nextBlizzardPosition(row: Int, col: Int, maxRow: Int, maxCol: Int, item: Item.Blizzard): List<IncomingBlizzard> { fun fixCol(col: Int): Int = when (col) { 0 -> maxCol - 2 maxCol - 1 -> 1 else -> col } fun fixRow(row: Int): Int = when (row) { 0 -> maxRow - 2 maxRow - 1 -> 1 else -> row } return item.items.map { when (it) { '<' -> IncomingBlizzard(row = row, col = fixCol(col - 1), '<') '>' -> IncomingBlizzard(row = row, col = fixCol(col + 1), '>') '^' -> IncomingBlizzard(row = fixRow(row - 1), col = col, '^') 'v' -> IncomingBlizzard(row = fixRow(row + 1), col = col, 'v') else -> throw IllegalStateException("") } } } private fun part1(input: List<String>): Int { val board = parse(input) val entrance = findEntrance(board) val position = Position(0, entrance.first, entrance.second) return play(position, board, Item.Exit).position.minutes } private fun part2(input: List<String>): Int { val board = parse(input) val startPosition = findEntrance(board) val position = Position(0, startPosition.first, startPosition.second) val first = play(position, board, Item.Exit) val second = play(first.position, first.board, Item.Entrance) val third = play(second.position, second.board, Item.Exit) return third.position.minutes } data class Position( val minutes: Int, val row: Int, val col: Int, ) data class IncomingBlizzard( val row: Int, val col: Int, val direction: Char ) data class Result( val position: Position, val board: Array<Array<Item>>, ) sealed interface Item { val element: Char object Entrance : Item { override val element: Char = 'E' } object Exit : Item { override val element: Char = 'X' } object Wall : Item { override val element: Char = '#' } object Free : Item { override val element: Char = '.' } data class Blizzard( val items: MutableList<Char> ) : Item { override val element: Char = '*' } } fun main() { val input = readInput("day24/input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
6,440
aoc-2022
Apache License 2.0
src/main/kotlin/days/Day14.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import util.Line import util.MutableMatrix import util.Point class Day14Game2(input: List<String>) { val lines = input.flatMap { line -> line.split("->").map { it.trim() }.map { pointString -> val (x, y) = pointString.split(",").map { it.trim().toInt() } Point(x, y) }.windowed(2, 1, false).map { pointList -> check(pointList.size == 2) { "Expected 2 points" } Line(pointList[0], pointList[1]) } } val points = lines.flatMap { listOf(it.from, it.to) } val maxY = points.maxBy { it.y }.y val maxX = points.maxBy { it.x }.x val minX = points.minBy { it.x }.x val margin = 200 var start = Point(500, 0) var matrix = MutableMatrix.from(maxX + margin, maxY + margin) { _ -> '.' } companion object { val free = '.' val sandChar = 'O' } fun play(): Int { lines.forEach { Day14Util.draw(matrix, it) } val bottom = Line(Point(0, maxY + 2), Point(matrix.height() - 1, maxY + 2)) Day14Util.draw(matrix, bottom) val startChar = 'x' matrix.set(Point(500, 0), startChar) matrix.dropX(minX - margin) matrix = matrix.transpose() start = matrix.find(startChar) val amountDropped = dropSands() print() return amountDropped } private fun print() { matrix.printSep("") { false } } private fun dropSands(): Int { // create a new sand item val safety = matrix.width() * matrix.height() var dropped = 0 var isOverFlowing = false while (!isOverFlowing && dropped < safety) { dropped++ isOverFlowing = dropSand() // println("Iteration $dropped") // print() } return dropped } private fun dropSand(): Boolean { var sand = nextSandPosition(start) // avoid 'free' conflicts, should be enough room anyway while (sand != null && !isAtStartPosition(sand)) { val nextSand = nextSandPosition(sand) if (nextSand == null) { // cannot go further matrix.set(sand, sandChar) break } else { sand = nextSand } } return sand == null // ugly, but this will work } private fun nextSandPosition(sand: Point): Point? { val down = sand.down() return if (isFree(down)) { down } else if (isFree(down.left())) { down.left() } else if (isFree(down.right())) { down.right() } else { null } } private fun canDrop(sand: Point): Boolean { return isFree(sand.down()) || isFree(sand.down().left()) || isFree(sand.down().right()) } private fun isFree(p: Point): Boolean { return matrix.get(p) == free } private fun isAtStartPosition(sand: Point): Boolean { return sand == start } } class Day14Game(input: List<String>) { val lines = input.flatMap { line -> line.split("->").map { it.trim() }.map { pointString -> val (x, y) = pointString.split(",").map { it.trim().toInt() } Point(x, y) }.windowed(2, 1, false).map { pointList -> check(pointList.size == 2) { "Expected 2 points" } Line(pointList[0], pointList[1]) } } val points = lines.flatMap { listOf(it.from, it.to) } val maxY = points.maxBy { it.y }.y val maxX = points.maxBy { it.x }.x val minX = points.minBy { it.x }.x val margin = 2 var start = Point(500, 0) var matrix = MutableMatrix.from(maxX + margin, maxY + margin) { _ -> '.' } companion object { val free = '.' val sandChar = 'O' } fun play(): Int { lines.forEach { Day14Util.draw(matrix, it) } val startChar = 'x' matrix.set(Point(500, 0), startChar) matrix.dropX(minX - margin) matrix = matrix.transpose() start = matrix.find(startChar) val amountDropped = dropSands() print() return amountDropped } private fun print() { matrix.printSep("") { false } } private fun dropSands(): Int { // create a new sand item val safety = matrix.width() * matrix.height() var dropped = 0 var isOverFlowing = false while (!isOverFlowing && dropped < safety) { dropped++ isOverFlowing = dropSand() // print() } return dropped - 1 } private fun dropSand(): Boolean { var sand = start.down() // avoid 'free' conflicts, should be enough room anyway while (!isOverFlowing(sand)) { val nextSand = nextSandPosition(sand) if (nextSand == null) { // cannot go further matrix.set(sand, sandChar) break } else { sand = nextSand } } return isOverFlowing(sand) } private fun nextSandPosition(sand: Point): Point? { val down = sand.down() return if (isFree(down)) { down } else if (isFree(down.left())) { down.left() } else if (isFree(down.right())) { down.right() } else { null } } private fun canDrop(sand: Point): Boolean { return isFree(sand.down()) || isFree(sand.down().left()) || isFree(sand.down().right()) } private fun isFree(p: Point): Boolean { return matrix.get(p) == free } private fun isOverFlowing(sand: Point): Boolean { return matrix.isOnEdge(sand) } } class Day14 : Day(14) { override fun partOne(): Any { // return Day14Game(inputList).play() return 0 } override fun partTwo(): Any { return Day14Game2(inputList).play() } } object Day14Util { fun draw(matrix: MutableMatrix<Char>, l: Line) { l.points().forEach { p -> matrix.set(p, '#') } } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
6,102
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/engine/pathfinding/algorithms/AStarPathFinder.kt
CozmicGames
580,563,255
false
{"Kotlin": 612441}
package engine.pathfinding.algorithms import com.cozmicgames.utils.collections.Array2D import com.cozmicgames.utils.collections.PriorityList import com.cozmicgames.utils.concurrency.threadLocal import engine.pathfinding.* import engine.pathfinding.algorithms.heurisitcs.ClosestHeuristic import kotlin.math.max class AStarPathFinder(val map: TileBasedMap, val heuristic: Heuristic = ClosestHeuristic) : PathFinder { interface Heuristic { fun getCost(map: TileBasedMap, x: Int, y: Int, targetX: Int, targetY: Int, movableObject: MovableObject?): Float } private data class Node(val x: Int, val y: Int) : Comparable<Node> { enum class State { UNEVALUATED, OPEN, CLOSED } var cost = 0.0f var parent: Node? = null set(value) { field = value depth = (value?.depth ?: -1) + 1 } var heuristic = 0.0f var depth = 0 var state = State.UNEVALUATED fun reset() { state = State.UNEVALUATED cost = 0.0f depth = 0 } override fun compareTo(other: Node): Int { val f = heuristic + cost val of = other.heuristic + other.cost return when { f < of -> -1 f > 0f -> 1 else -> 0 } } } private inner class Nodes { private val array = Array2D<Node>(map.numTilesX, map.numTilesY) private val open = PriorityList<Node>() private val closed = arrayListOf<Node>() init { repeat(map.numTilesX) { x -> repeat(map.numTilesY) { y -> array[x, y] = Node(x, y) } } } fun reset() { open.clear() closed.clear() repeat(map.numTilesX) { x -> repeat(map.numTilesY) { y -> this[x, y]?.reset() } } } operator fun get(x: Int, y: Int) = array[x, y] fun setState(node: Node, state: Node.State) { node.state = state } fun setOpen(x: Int, y: Int) = this[x, y]?.let { setOpen(it) } fun setOpen(node: Node) { setState(node, Node.State.OPEN) if (node.state == Node.State.CLOSED) closed -= node open += node } fun setClosed(node: Node) { setState(node, Node.State.CLOSED) if (node.state == Node.State.OPEN) open -= node closed += node } fun setUnevaluated(node: Node) { when (node.state) { Node.State.OPEN -> open -= node Node.State.CLOSED -> closed -= node else -> {} } node.state = Node.State.UNEVALUATED } fun setParent(x: Int, y: Int, parent: Node?) { array[x, y]?.parent = parent } fun getFirstOpen() = open.first() fun hasOpen() = open.isNotEmpty() } private val nodes by threadLocal { Nodes() } override fun findPath(movableObject: MovableObject?, startX: Int, startY: Int, targetX: Int, targetY: Int, maxSearchDistance: Int, allowDiagonalMovement: Boolean): Path? { fun isValidLocation(context: PathFindingContext, sx: Int, sy: Int, x: Int, y: Int): Boolean { var invalid = (x < 0) || (y < 0) || (x >= map.numTilesX) || (y >= map.numTilesY) if (!invalid && (sx != x || sy != y)) invalid = map.isBlocked(x, y, sx, sy, context) return !invalid } val nodes = this.nodes val pathFindingContext = PathFindingContext(startX, startY, movableObject) if (map.isBlocked(targetX, targetY, targetX, targetY, pathFindingContext)) return null nodes.reset() nodes.setOpen(startX, startY) nodes.setParent(targetX, targetY, null) var maxDepth = 0 var current: Node? = null while ((maxDepth < maxSearchDistance) && nodes.hasOpen()) { var lx = startX var ly = startY if (current != null) { lx = current.x ly = current.y } current = nodes.getFirstOpen() pathFindingContext.searchDistance = current.depth if (current == nodes[targetX, targetY]) if (isValidLocation(pathFindingContext, lx, ly, targetX, targetY)) break nodes.setClosed(current) for (x in -1..1) for (y in -1..1) { if (y == 0 && x == 0) continue if (!allowDiagonalMovement && (x != 0 && y != 0)) continue val xp = x + current.x val yp = y + current.y if (isValidLocation(pathFindingContext, current.x, current.y, xp, yp)) { val nextStepCost = current.cost + map.getCost(xp, yp, current.x, current.y, pathFindingContext) val neighbor = nodes[xp, yp] ?: continue if (nextStepCost < neighbor.cost) nodes.setUnevaluated(neighbor) if (neighbor.state == Node.State.UNEVALUATED) { neighbor.cost = nextStepCost neighbor.heuristic = heuristic.getCost(map, xp, yp, targetX, targetY, movableObject) neighbor.parent = current maxDepth = max(maxDepth, neighbor.depth) nodes.setOpen(neighbor) } } } } if (nodes[targetX, targetY]?.parent == null) return null val path = Path() var target = requireNotNull(nodes[targetX, targetY]) while (target != nodes[startX, startY]) { path.prependStep(target.x, target.y) target = requireNotNull(target.parent) } path.prependStep(startX, startY) return path } }
0
Kotlin
0
0
d85d016431fb0490dcb6b125be5fd285e409bfc4
6,254
Sandbox2D
MIT License
Algorithm/src/main/kotlin/programmers/level1/personalInfoCollectionValidityPeriod.kt
getupminaaa
740,836,169
false
{"Kotlin": 28293}
import java.util.* fun main() { val solution = Solution() val terms: Array<String> = arrayOf("A 6", "B 12", "C 3") val privacies: Array<String> = arrayOf("2021.05.02 A", "2021.07.01 B", "2022.02.19 C", "2022.02.20 C") solution.solution(today = "2022.05.19", terms, privacies) } class Solution { fun solution(today: String, terms: Array<String>, privacies: Array<String>): IntArray { var answer: IntArray = intArrayOf() //오늘 날짜 변환 var tDates: Int = 0 val todayArray: List<String> = today.split(".", ".") tDates += todayArray[0].toInt() * 12 * 28 tDates += todayArray[1].toInt() * 28 tDates += todayArray[2].toInt() for (i in privacies.indices) { var pDates: Int = 0 val privaciesArray: List<String> = privacies[i].split(".", ".", " ") pDates += privaciesArray[0].toInt() * 12 * 28 pDates += privaciesArray[1].toInt() * 28 pDates += privaciesArray[2].toInt() for (j in terms.indices) { if (terms[j].split("\\s+".toRegex()).first() == privaciesArray[3]) { pDates += terms[j].split("\\s+".toRegex()).last().toInt() * 28 if (tDates >= pDates) { answer += i + 1 } } } } print(Arrays.toString(answer)) return answer } }
0
Kotlin
0
0
01187e280c375dca95ba26d80368f8a162610568
1,443
Algorithm
MIT License
year2020/day01/part1/src/main/kotlin/com/curtislb/adventofcode/year2020/day01/part1/Year2020Day01Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 1: Report Repair --- After saving Christmas five years in a row, you've decided to take a vacation at a nice resort on a tropical island. Surely, Christmas will go on without you. The tropical island has its own currency and is entirely cash-only. The gold coins used there have a little picture of a starfish; the locals just call them stars. None of the currency exchanges seem to have heard of them, but somehow, you'll need to find fifty of these coins by the time you arrive so you can pay the deposit on your room. To save your vacation, you need to get all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Before you leave, the Elves in accounting just need you to fix your expense report (your puzzle input); apparently, something isn't quite adding up. Specifically, they need you to find the two entries that sum to 2020 and then multiply those two numbers together. For example, suppose your expense report contained the following: 1721 979 366 299 675 1456 In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579. Of course, your expense report is much larger. Find the two entries that sum to 2020; what do you get if you multiply them together? */ package com.curtislb.adventofcode.year2020.day01.part1 import com.curtislb.adventofcode.common.search.findPairSum import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2020, day 1, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int? { val file = inputPath.toFile() val entries = file.readLines().map { it.toInt() } return entries.findPairSum(2020)?.let { it.first * it.second } } fun main() = when (val solution = solve()) { null -> println("No solution found.") else -> println(solution) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,125
AdventOfCode
MIT License
src/main/kotlin/com/lucaszeta/adventofcode2020/day03/day03.kt
LucasZeta
317,600,635
false
null
package com.lucaszeta.adventofcode2020.day03 import com.lucaszeta.adventofcode2020.ext.getResourceAsText fun findTreesForSlope( mountain: Mountain, slope: Slope ) = mountain.countTrees(slope) fun multiplyTreeForAllSlopes( mountain: Mountain, slopes: List<Slope> ) = slopes .map { mountain.countTrees(it).toLong() } .reduce(Long::times) fun main() { val input = getResourceAsText("/day03/map.txt") .split("\n") .filter { it.isNotEmpty() } val mountain = Mountain(input) val treeCount = findTreesForSlope(mountain, Slope(3, 1)) val result = multiplyTreeForAllSlopes( mountain, listOf( Slope(1, 1), Slope(3, 1), Slope(5, 1), Slope(7, 1), Slope(1, 2) ) ) println("Number of trees for slope (3, 1): %d".format(treeCount)) println("Multiplication of tree for all slopes: %d".format(result)) }
0
Kotlin
0
1
9c19513814da34e623f2bec63024af8324388025
946
advent-of-code-2020
MIT License
app/src/main/java/com/benjaminearley/droidbot/Omni.kt
BenjaminEarley
96,455,906
false
null
package com.benjaminearley.droidbot import java.lang.Math.PI import java.lang.Math.abs import java.lang.Math.cos import java.lang.Math.sin import java.lang.Math.sqrt val tau = PI.toFloat() * 2.0f val numWheels = 3 val xUnit = Vector3(1.0f, 0.0f, 0.0f) val yUnit = Vector3(0.0f, 1.0f, 0.0f) val zUnit = Vector3(0.0f, 0.0f, 1.0f) data class Vector2(val x: Float, val y: Float) { operator fun plus(v: Vector2): Vector2 = Vector2(x + v.x, y + v.y) fun scale(s: Float): Vector2 = Vector2(x * s, y * s) private fun divide(s: Float): Vector2 = Vector2(x / s, y / s) infix fun dot(v: Vector2): Float = (x * v.x) + (y * v.y) val clipToUnit: Vector2 get() = dot(this).let { lengthSquared -> if (lengthSquared <= 1.0) this else divide(sqrt(lengthSquared.toDouble()).toFloat()) } } data class Vector3(val x: Float, val y: Float, val z: Float) { fun scale(s: Float): Vector3 = Vector3(x * s, y * s, z * s) infix fun dot(v: Vector3): Float = x * v.x + y * v.y + z * v.z fun cross(v: Vector3): Vector3 = Vector3( y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x) operator fun unaryMinus(): Vector3 = Vector3(-x, -y, -z) } data class Quaternion(private val s: Float, private val v: Vector3) { private val conjugate: Quaternion get() = Quaternion(s, -v) private infix fun mul(q: Quaternion): Quaternion = Quaternion( s * q.s - (v dot q.v), Vector3( v.y * q.v.z - v.z * q.v.y + s * q.v.x + v.x * q.s, v.z * q.v.x - v.x * q.v.z + s * q.v.y + v.y * q.s, v.x * q.v.y - v.y * q.v.x + s * q.v.z + v.z * q.s)) fun rotate(v: Vector3): Vector3 = (this mul Quaternion(0.0f, v) mul conjugate).v } fun quaternionFromVector(axis: Vector3, r: Float): Quaternion = Quaternion( cos((r / 2.0f).toDouble()).toFloat(), axis.scale(sin((r / 2.0f).toDouble()).toFloat())) typealias Wheels = List<Vector3> val wheels: List<Vector3> = (0 until numWheels).map { quaternionFromVector(zUnit, (it.toFloat() / numWheels.toFloat()) * tau).rotate(xUnit) } typealias Speeds = List<Float> fun lateralSpeeds(wheels: Wheels, x: Float, y: Float): Speeds = Vector3(x, y, 0.0f).let { direction -> wheels.map { wheel -> direction.cross(wheel).z } } fun rotationalSpeeds(wheels: Wheels, turnRate: Float): Speeds = wheels.map { -turnRate } fun combineSpeeds(lateral: Speeds, rotational: Speeds): Speeds = lateral.zip(rotational).map { (lat, rot) -> lat + rot } fun scaleToWithinMaxSpeed(speeds: Speeds): Speeds = speeds.map(::abs).max()!!.let { max -> if (max > 1.0) speeds.map { it / max } else speeds } val maxSum = 1.25f fun scaleToWithinMaxSum(speeds: Speeds): Speeds = speeds.map(::abs).sum().let { sum -> if (sum > maxSum) speeds.map { it * (maxSum / sum) } else speeds } // Magnitude of direction should not exceed 1.0 // direction x axis is pointed in the direction of the first wheel. // direction y axis is pointed such that the z axis is pointed upward in a right handed coordinate system. // turnDirection: range from -1.0 to 1.0 // When turnDirection is positive it is CCW. // Speed is positive it is CCW when facing toward the center of robot. fun getSpeeds(direction: Vector2, turnDirection: Float): Speeds = direction.clipToUnit.let { (xDir, yDir) -> combineSpeeds( lateralSpeeds(wheels, xDir, yDir), rotationalSpeeds(wheels, turnDirection) ) pipe ::scaleToWithinMaxSpeed pipe // Scale down the sum of all wheel speeds to ensure max power draw is not exceeded. ::scaleToWithinMaxSum }
0
Kotlin
0
1
bb76a3e6f91c092a3915bd27aca90431df4463f2
3,651
DroidBot
MIT License
src/Day01.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
fun main() { fun part1(inputFilename: String): Int { var result = 0 var currentSum = 0 getInputFile(inputFilename).forEachLine { if (it.isNotBlank()) { currentSum += it.toInt() } else { if (currentSum > result) result = currentSum currentSum = 0 } } if (currentSum > result) result = currentSum return result } fun part2(inputFilename: String): Int { val sumList = mutableListOf<Int>() var currentSum = 0 getInputFile(inputFilename).forEachLine { if (it.isNotBlank()) { currentSum += it.toInt() } else { sumList.add(currentSum) currentSum = 0 } } sumList.add(currentSum) return sumList .sortedDescending() .take(3) .sum() } // test if implementation meets criteria from the description, like: check(part1("Day01_test") == 24000) check(part2("Day01_test") == 45000) println(part1("Day01")) println(part2("Day01")) }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
1,214
AdventOfCode2022
Apache License 2.0
src/main/kotlin/day22/Day22.kt
daniilsjb
572,664,294
false
{"Kotlin": 69004}
package day22 import java.io.File fun main() { val data = parse("src/main/kotlin/day22/Day22.txt") val answer1 = part1(data) val answer2 = part2(data) println("🎄 Day 22 🎄") println() println("[Part 1]") println("Answer: $answer1") println() println("[Part 2]") println("Answer: $answer2") } private data class Point( val x: Int, val y: Int, ) private sealed interface Step { data class Move(val count: Int) : Step object TurnRight : Step object TurnLeft : Step } private data class Board( val walls: Set<Point>, val steps: List<Step>, ) private fun String.toSteps(): List<Step> { val steps = mutableListOf<Step>() var count = 0 for (c in this) { if (c.isDigit()) { count = count * 10 + c.digitToInt() } else { steps += Step.Move(count) steps += when (c) { 'R' -> Step.TurnRight 'L' -> Step.TurnLeft else -> error("Unknown turn: $c") } count = 0 } } steps += Step.Move(count) return steps } private fun List<String>.toWalls(): Set<Point> { val walls = mutableSetOf<Point>() for ((y, row) in this.withIndex()) { for ((x, col) in row.withIndex()) { if (col == '#') { walls += Point(x, y) } } } return walls } @Suppress("SameParameterValue") private fun parse(path: String): Board = File(path).readLines().let { lines -> val walls = lines.dropLast(2).toWalls() val steps = lines.last().toSteps() Board(walls, steps) } private sealed interface Facing { fun turnLeft(): Facing fun turnRight(): Facing object E : Facing { override fun turnLeft(): Facing = N override fun turnRight(): Facing = S override fun toString() = "E" } object S : Facing { override fun turnLeft(): Facing = E override fun turnRight(): Facing = W override fun toString() = "S" } object W : Facing { override fun turnLeft(): Facing = S override fun turnRight(): Facing = N override fun toString() = "W" } object N : Facing { override fun turnLeft(): Facing = W override fun turnRight(): Facing = E override fun toString() = "N" } } private data class Transition( val sourceId: String, val targetId: String, val sourceFacing: Facing, val targetFacing: Facing, ) private const val PLANE_SIZE = 50 private data class Plane( val topLeft: Point, val transitionToE: Transition, val transitionToS: Transition, val transitionToW: Transition, val transitionToN: Transition, ) private fun Plane.selectTransition(facing: Facing): Transition = when (facing) { is Facing.E -> transitionToE is Facing.S -> transitionToS is Facing.W -> transitionToW is Facing.N -> transitionToN } private val planes = mapOf( // == Part 1 ============================================================== "A1" to Plane( topLeft = Point(50, 0), transitionToE = Transition(sourceId = "A1", targetId = "A2", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A1", targetId = "A3", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A1", targetId = "A2", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A1", targetId = "A5", Facing.N, Facing.N), ), "A2" to Plane( topLeft = Point(100, 0), transitionToE = Transition(sourceId = "A2", targetId = "A1", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A2", targetId = "A2", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A2", targetId = "A1", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A2", targetId = "A2", Facing.N, Facing.N), ), "A3" to Plane( topLeft = Point(50, 50), transitionToE = Transition(sourceId = "A3", targetId = "A3", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A3", targetId = "A5", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A3", targetId = "A3", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A3", targetId = "A1", Facing.N, Facing.N), ), "A4" to Plane( topLeft = Point(0, 100), transitionToE = Transition(sourceId = "A4", targetId = "A5", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A4", targetId = "A6", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A4", targetId = "A5", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A4", targetId = "A6", Facing.N, Facing.N), ), "A5" to Plane( topLeft = Point(50, 100), transitionToE = Transition(sourceId = "A5", targetId = "A4", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A5", targetId = "A1", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A5", targetId = "A4", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A5", targetId = "A3", Facing.N, Facing.N), ), "A6" to Plane( topLeft = Point(0, 150), transitionToE = Transition(sourceId = "A6", targetId = "A6", Facing.E, Facing.E), transitionToS = Transition(sourceId = "A6", targetId = "A4", Facing.S, Facing.S), transitionToW = Transition(sourceId = "A6", targetId = "A6", Facing.W, Facing.W), transitionToN = Transition(sourceId = "A6", targetId = "A4", Facing.N, Facing.N), ), // == Part 2 ============================================================== "B1" to Plane( topLeft = Point(50, 0), transitionToE = Transition(sourceId = "B1", targetId = "B2", Facing.E, Facing.E), transitionToS = Transition(sourceId = "B1", targetId = "B3", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B1", targetId = "B4", Facing.W, Facing.E), transitionToN = Transition(sourceId = "B1", targetId = "B6", Facing.N, Facing.E), ), "B2" to Plane( topLeft = Point(100, 0), transitionToE = Transition(sourceId = "B2", targetId = "B5", Facing.E, Facing.W), transitionToS = Transition(sourceId = "B2", targetId = "B3", Facing.S, Facing.W), transitionToW = Transition(sourceId = "B2", targetId = "B1", Facing.W, Facing.W), transitionToN = Transition(sourceId = "B2", targetId = "B6", Facing.N, Facing.N), ), "B3" to Plane( topLeft = Point(50, 50), transitionToE = Transition(sourceId = "B3", targetId = "B2", Facing.E, Facing.N), transitionToS = Transition(sourceId = "B3", targetId = "B5", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B3", targetId = "B4", Facing.W, Facing.S), transitionToN = Transition(sourceId = "B3", targetId = "B1", Facing.N, Facing.N), ), "B4" to Plane( topLeft = Point(0, 100), transitionToE = Transition(sourceId = "B4", targetId = "B5", Facing.E, Facing.E), transitionToS = Transition(sourceId = "B4", targetId = "B6", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B4", targetId = "B1", Facing.W, Facing.E), transitionToN = Transition(sourceId = "B4", targetId = "B3", Facing.N, Facing.E), ), "B5" to Plane( topLeft = Point(50, 100), transitionToE = Transition(sourceId = "B5", targetId = "B2", Facing.E, Facing.W), transitionToS = Transition(sourceId = "B5", targetId = "B6", Facing.S, Facing.W), transitionToW = Transition(sourceId = "B5", targetId = "B4", Facing.W, Facing.W), transitionToN = Transition(sourceId = "B5", targetId = "B3", Facing.N, Facing.N), ), "B6" to Plane( topLeft = Point(0, 150), transitionToE = Transition(sourceId = "B6", targetId = "B5", Facing.E, Facing.N), transitionToS = Transition(sourceId = "B6", targetId = "B2", Facing.S, Facing.S), transitionToW = Transition(sourceId = "B6", targetId = "B1", Facing.W, Facing.S), transitionToN = Transition(sourceId = "B6", targetId = "B4", Facing.N, Facing.N), ), ) private val Plane.minX: Int get() = topLeft.x private val Plane.maxX: Int get() = topLeft.x + PLANE_SIZE - 1 private val Plane.minY: Int get() = topLeft.y private val Plane.maxY: Int get() = topLeft.y + PLANE_SIZE - 1 private operator fun Plane.contains(point: Point): Boolean = (point.x in minX..maxX) && (point.y in minY..maxY) private fun Point.toLocal(plane: Plane): Point = Point(x - plane.topLeft.x, y - plane.topLeft.y) private fun Point.toGlobal(plane: Plane): Point = Point(x + plane.topLeft.x, y + plane.topLeft.y) private fun Point.flip(): Point = Point(y, x) private val Transition.source: Plane get() = planes[sourceId] ?: error("Plane '$sourceId' doesn't exist.") private val Transition.target: Plane get() = planes[targetId] ?: error("Plane '$targetId' doesn't exist.") private fun Transition.findPosition(start: Point): Point = when (sourceFacing to targetFacing) { Facing.E to Facing.E -> Point(target.minX, start.toLocal(source).toGlobal(target).y) Facing.W to Facing.W -> Point(target.maxX, start.toLocal(source).toGlobal(target).y) Facing.S to Facing.S -> Point(start.toLocal(source).toGlobal(target).x, target.minY) Facing.N to Facing.N -> Point(start.toLocal(source).toGlobal(target).x, target.maxY) Facing.N to Facing.E -> Point(target.minX, start.toLocal(source).flip().toGlobal(target).y) Facing.S to Facing.W -> Point(target.maxX, start.toLocal(source).flip().toGlobal(target).y) Facing.W to Facing.E -> Point(target.minX, target.maxY - start.toLocal(source).y) Facing.E to Facing.W -> Point(target.maxX, target.maxY - start.toLocal(source).y) Facing.W to Facing.S -> Point(start.toLocal(source).flip().toGlobal(target).x, target.minY) Facing.E to Facing.N -> Point(start.toLocal(source).flip().toGlobal(target).x, target.maxY) else -> error("Transition from $sourceFacing to $targetFacing isn't defined.") } private fun Facing.toOffset(): Point = when (this) { is Facing.E -> Point(+1, +0) is Facing.S -> Point(+0, +1) is Facing.W -> Point(-1, +0) is Facing.N -> Point(+0, -1) } private fun Facing.toValue(): Int = when (this) { is Facing.E -> 0 is Facing.S -> 1 is Facing.W -> 2 is Facing.N -> 3 } private fun solve(data: Board, start: String): Int { val (walls, steps) = data var plane = planes[start] ?: error("Plane '$start' doesn't exist.") var facing: Facing = Facing.E var position = plane.topLeft for (step in steps) { when (step) { is Step.TurnLeft -> facing = facing.turnLeft() is Step.TurnRight -> facing = facing.turnRight() is Step.Move -> { for (i in 1..step.count) { val (dx, dy) = facing.toOffset() var newFacing = facing var newPosition = Point(position.x + dx, position.y + dy) var newPlane = plane if (newPosition !in plane) { val transition = plane.selectTransition(facing) newFacing = transition.targetFacing newPosition = transition.findPosition(position) newPlane = transition.target } if (newPosition in walls) { break } facing = newFacing position = newPosition plane = newPlane } } } } return (1000 * (position.y + 1)) + (4 * (position.x + 1)) + facing.toValue() } private fun part1(data: Board): Int = solve(data, start = "A1") private fun part2(data: Board): Int = solve(data, start = "B1")
0
Kotlin
0
0
6f0d373bdbbcf6536608464a17a34363ea343036
12,075
advent-of-code-2022
MIT License
src/main/kotlin/adventofcode/y2021/Day06.kt
Tasaio
433,879,637
false
{"Kotlin": 117806}
import adventofcode.* import java.math.BigInteger fun main() { val testInput = "3,4,3,1,2" val test = Day06(testInput) println("TEST: " + test.part1()) val day = Day06() println(day.part1()) day.reset() println(day.part2()) } open class Day06(staticInput: String? = null) : Y2021Day(6, staticInput) { private val input = fetchInputAsSingleLineBigInteger(",").map { it.toInt() } override fun part1(): Number? { val fish = input.map { RotatingNumber(0, 6, it) }.toMutableList() val newFish = arrayListOf<RotatingNumber>() var fishesToAdd: Int for (i in 1..80) { fishesToAdd = 0 for (j in fish.indices) { if (fish[j].value == BigInteger.ZERO) { fishesToAdd++ } fish[j] = fish[j].dec() } for (j in 0 until fishesToAdd) { newFish.add(RotatingNumber(0, 6, 8)) } fish.addAll(newFish) newFish.clear() } return fish.size } override fun part2(): Number? { var fishCount = input.size.toBigInteger() val addOnDay = BigIntegerMap<Int>() input.forEach { addOnDay.inc(it + 1) } for (i in 1..256) { fishCount += addOnDay[i] addOnDay[i + 7] += addOnDay[i] addOnDay[i + 9] += addOnDay[i] } return fishCount } }
0
Kotlin
0
0
cc72684e862a782fad78b8ef0d1929b21300ced8
1,454
adventofcode2021
The Unlicense
src/day19/day19.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day19 import readInput import java.lang.Math.ceil import java.lang.Math.max private fun parse(input: List<String>): List<Blueprint> { return input.map { line -> val parts = line.split(": ", ". ") val ore = parts[1].split(" ")[4].toInt().let { Item.Ore(it) } val clay = parts[2].split(" ")[4].toInt().let { Item.Clay(it) } val obsidian = parts[3].split(" ").run { Item.Obsidian(oreCount = get(4).toInt(), clayCount = get(7).toInt()) } val geode = parts[4].split(" ").run { Item.Geode(oreCount = get(4).toInt(), obsidianCount = get(7).toInt()) } Blueprint(ore, clay, obsidian, geode) } } private fun helper(blueprint: Blueprint, state: State, cache: HashMap<Int, Int>): Int { if (state.time <= 0) return 0 if (cache.contains(state.hashCode())) return cache[state.hashCode()]!! var result = 0 fun createOre(item: Item.Ore): Int { var waitTime = ceil((item.count - state.oreCount) / state.oreMachine.toDouble()) .toInt().coerceAtLeast(0) val shouldCreate = state.oreMachine < max( max(blueprint.ore.count, blueprint.clay.count), max(blueprint.obsidian.oreCount, blueprint.geode.oreCount) ) return if (shouldCreate && state.time > waitTime) { waitTime++ val newState = state.copy( oreCount = state.oreCount - item.count + waitTime * state.oreMachine, clayCount = state.clayCount + waitTime * state.clayMachine, obsidianCount = state.obsidianCount + waitTime * state.obsidianMachine, oreMachine = state.oreMachine + 1, time = state.time - waitTime ) helper(blueprint, newState, cache) } else 0 } fun createClay(item: Item.Clay): Int { var waitTime = ceil((item.count - state.oreCount) / state.oreMachine.toDouble()) .toInt().coerceAtLeast(0) val shouldCreate = state.clayMachine < blueprint.obsidian.clayCount return if (shouldCreate && state.time > waitTime) { waitTime++ val newState = state.copy( oreCount = state.oreCount - item.count + waitTime * state.oreMachine, clayCount = state.clayCount + waitTime * state.clayMachine, obsidianCount = state.obsidianCount + waitTime * state.obsidianMachine, clayMachine = state.clayMachine + 1, time = state.time - waitTime ) helper(blueprint, newState, cache) } else 0 } fun createObsidian(item: Item.Obsidian): Int { var waitTime = if (state.oreMachine > 0 && state.clayMachine > 0) { val waitOreTime = ceil((item.oreCount - state.oreCount) / state.oreMachine.toDouble()).toInt() val waitClayTime = ceil((item.clayCount - state.clayCount) / state.clayMachine.toDouble()).toInt() max(waitOreTime, waitClayTime).coerceAtLeast(0) } else Int.MAX_VALUE val shouldCreate = state.obsidianMachine < blueprint.geode.obsidianCount return if (shouldCreate && state.time > waitTime) { waitTime++ val newState = state.copy( oreCount = state.oreCount - item.oreCount + waitTime * state.oreMachine, clayCount = state.clayCount - item.clayCount + waitTime * state.clayMachine, obsidianCount = state.obsidianCount + waitTime * state.obsidianMachine, obsidianMachine = state.obsidianMachine + 1, time = state.time - waitTime ) helper(blueprint, newState, cache) } else 0 } fun createGeode(item: Item.Geode): Int { var waitTime = if (state.oreMachine > 0 && state.obsidianMachine > 0) { val waitOreTime = ceil((item.oreCount - state.oreCount) / state.oreMachine.toDouble()).toInt() val waitObsidianTime = ceil((item.obsidianCount - state.obsidianCount) / state.obsidianMachine.toDouble()).toInt() max(waitOreTime, waitObsidianTime).coerceAtLeast(0) } else Int.MAX_VALUE return if (state.time > waitTime) { waitTime++ val newState = state.copy( oreCount = state.oreCount - item.oreCount + waitTime * state.oreMachine, clayCount = state.clayCount + waitTime * state.clayMachine, obsidianCount = state.obsidianCount - item.obsidianCount + waitTime * state.obsidianMachine, time = state.time - waitTime ) (state.time - waitTime) + helper(blueprint, newState, cache) } else 0 } result = createOre(blueprint.ore).coerceAtLeast(result) result = createClay(blueprint.clay).coerceAtLeast(result) result = createObsidian(blueprint.obsidian).coerceAtLeast(result) result = createGeode(blueprint.geode).coerceAtLeast(result) cache[state.hashCode()] = result return result } private fun part1(input: List<String>): Int { val blueprints = parse(input) val initialState = State(oreMachine = 1, time = 24) return blueprints.asSequence() .map { helper(it, initialState.copy(), hashMapOf()) } .foldIndexed(0) { index, acc, value -> acc + (index + 1) * value } } private fun part2(input: List<String>): Int { val blueprints = parse(input) val initialState = State(oreMachine = 1, time = 32) return blueprints.subList(0,3) .map { helper(it, initialState.copy(), hashMapOf()) } .fold(1) { acc: Int, result: Int -> acc * result } } data class State( val oreCount: Int = 0, val clayCount: Int = 0, val obsidianCount: Int = 0, val oreMachine: Int = 1, val clayMachine: Int = 0, val obsidianMachine: Int = 0, val time: Int = 0 ) data class Blueprint( val ore: Item.Ore, val clay: Item.Clay, val obsidian: Item.Obsidian, val geode: Item.Geode ) sealed interface Item { data class Ore(val count: Int) : Item data class Clay(val count: Int) : Item data class Obsidian(val oreCount: Int, val clayCount: Int) : Item data class Geode(val oreCount: Int, val obsidianCount: Int) : Item } fun main() { val input = readInput("day19/input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
6,385
aoc-2022
Apache License 2.0
puzzles/kotlin/src/surface/surface.kt
charlesfranciscodev
179,561,845
false
{"Python": 141140, "Java": 34848, "Kotlin": 33981, "C++": 27526, "TypeScript": 22844, "C#": 22075, "Go": 12617, "JavaScript": 11282, "Ruby": 6255, "Swift": 3911, "Shell": 3090, "Haskell": 1375, "PHP": 1126, "Perl": 667, "C": 493}
import java.util.Scanner import java.util.ArrayDeque const val LAND = '#' const val WATER = 'O' const val DEFAULT_INDEX = -1 fun main(args : Array<String>) { val grid = Grid() grid.readGameInput() grid.test() } data class Square(val x: Int, val y: Int, val terrain: Char, var lakeIndex: Int = DEFAULT_INDEX) class Grid { val input = Scanner(System.`in`) var width = 0 var height = 0 val nodes = ArrayList<List<Square>>() val lakes = HashMap<Int, Int>() // lake_index -> surface area fun readGameInput() { width = input.nextInt() height = input.nextInt() if (input.hasNextLine()) { input.nextLine() } for (y in 0 until height) { val row = input.nextLine().withIndex().map { Square(it.index, y, it.value) } nodes.add(row) } } fun test() { val n = input.nextInt() for (i in 0 until n) { val x = input.nextInt() val y = input.nextInt() println(area(x, y)) } } fun area(x: Int, y: Int): Int { val node = nodes[y][x] if (node.terrain == LAND) { return 0 } if (node.lakeIndex == DEFAULT_INDEX) { floodFill(node) } return lakes.getOrDefault(node.lakeIndex, 0) } // Source https://en.wikipedia.org/wiki/Flood_fill fun floodFill(start: Square) { val queue = ArrayDeque<Square>() var totalArea = 0 start.lakeIndex = start.y * width + start.x queue.add(start) while (!queue.isEmpty()) { totalArea++ val current = queue.poll() fillNeighbors(queue, current, start.lakeIndex) } lakes.put(start.lakeIndex, totalArea) } fun fillNeighbors(queue: ArrayDeque<Square>, square: Square, lakeIndex: Int) { if (square.x + 1 < width) { val rightNeighbor = nodes[square.y][square.x + 1] fill(queue, rightNeighbor, lakeIndex) } if (square.x > 0) { val leftNeighbor = nodes[square.y][square.x - 1] fill(queue, leftNeighbor, lakeIndex) } if (square.y + 1 < height) { val downNeighbor = nodes[square.y + 1][square.x] fill(queue, downNeighbor, lakeIndex) } if (square.y > 0) { val upNeighbor = nodes[square.y - 1][square.x] fill(queue, upNeighbor, lakeIndex) } } fun fill(queue: ArrayDeque<Square>, square: Square, lakeIndex: Int) { if (square.terrain == WATER && square.lakeIndex == DEFAULT_INDEX) { square.lakeIndex = lakeIndex queue.add(square) } } }
0
Python
19
45
3ec80602e58572a0b7baf3a2829a97e24ca3460c
2,433
codingame
MIT License
src/Day04.kt
zoidfirz
572,839,149
false
{"Kotlin": 15878}
fun main() { partOneSolution() partTwoSolution() } private fun partOneSolution() { val data = readInput("main/resources/Day04_input") var counter = 0 data.forEach { chunk -> // separate the input into separate arrays val (one, two) = chunk.split(",") val (groupOneStart, groupOneEnd) = one.split("-") val (groupTwoStart, groupTwoEnd) = two.split("-") if (groupOneStart.toInt() <= groupTwoStart.toInt() && groupOneEnd.toInt() >= groupTwoEnd.toInt()) { counter += 1 } else if (groupTwoStart.toInt() <= groupOneStart.toInt() && groupTwoEnd.toInt() >= groupOneEnd.toInt()) { counter += 1 } } println(counter) } private fun partTwoSolution() { val data = readInput("main/resources/Day04_input") var counter = 0 data.forEach { chunk -> // separate the input into separate arrays val (one, two) = chunk.split(",") val (groupOneStart, groupOneEnd) = one.split("-") val (groupTwoStart, groupTwoEnd) = two.split("-") if (groupOneStart.toInt() <= groupTwoStart.toInt() && groupOneEnd.toInt() >= groupTwoStart.toInt()) { counter += 1 } else if (groupTwoStart.toInt() <= groupOneStart.toInt() && groupTwoEnd.toInt() >= groupOneStart.toInt()) { counter += 1 } } println(counter) }
0
Kotlin
0
0
e955c1c08696f15929aaf53731f2ae926c585ff3
1,381
kotlin-advent-2022
Apache License 2.0
src/main/kotlin/adventOfCode2023/Day17.kt
TetraTsunami
726,140,343
false
{"Kotlin": 80024}
package adventOfCode2023 import util.* import util.templates.Grid2D import util.templates.Vector2D import java.util.* @Suppress("unused") class Day17(input: String, context: RunContext = RunContext.PROD) : Day(input, context) { override fun solve() { // we're going to come back to this later a(0, 0) val grid = Grid2D.fromLines(input).map { it.digitToIntOrNull() ?: 0 } val start = Vector2D(0, 0) val end = Vector2D(grid.width - 1, grid.height - 1) val costSoFar = mapDijkstrasAlgoSearch(grid, start) plt(Grid2D.intGridToString(Grid2D.fromVectors(costSoFar, 0).map { it ?: 0 })) // plt(Grid2D.fromVectors(fromDir.mapValues { it.value?.toChar() ?: ' ' }, ' ')) // val path = mutableListOf<Vector2D>() // var current = end // while (current != start) { // path.add(current) // current += fromDir[current]!! // } // path.add(start) // plt(Grid2D.fromVectors(path.associateWith { ((fromDir[it] ?: Vector2D(0, 0)) * -1).toChar()}, ' ')) a(costSoFar[end] ?: -1) // 1245 too low // 1301 too high } private fun mapDijkstrasAlgoSearch(grid: Grid2D<Int>, start: Vector2D): Map<Vector2D, Int> { data class Node( val coord: Vector2D, val direction: Vector2D, val steps: Int, val cost: Int ) { val triple = Triple(coord, direction, steps) } val first = Node(start, Vector2D(0, 0), 0, 0) val frontier = PriorityQueue<Node>(compareBy { it.cost }) frontier.add(first) // Memory: coord, direction, consecutive steps -> cost val memory = mutableMapOf(first.triple to 0) while (frontier.isNotEmpty()) { val node = frontier.remove() val neighbors = grid.getNeighbors(node.coord).toMutableList() for (next in neighbors) { val newCost = node.cost + grid[next] val diff = node.coord - next val isConsec = diff.isParallel(node.direction) if (isConsec && node.steps >= 2) { continue } val nextState = Node(next, diff, if (isConsec) node.steps + 1 else 0, newCost) if (newCost < memory.getOrDefault(nextState.triple, Int.MAX_VALUE)) { memory[nextState.triple] = newCost frontier.add(nextState) } } } // make map of coord -> lowest cost plt(Grid2D.fromVectors(memory.toList().sortedBy { -it.second }.associate { it.first.first to it.first.second.toChar() }, ' ')) return memory.toList().sortedBy { -it.second }.associate { it.first.first to it.second } } }
0
Kotlin
0
0
78d1b5d1c17122fed4f4e0a25fdacf1e62c17bfd
2,825
AdventOfCode2023
Apache License 2.0
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/Complexity/SpaceComplexity/SpaceComplexity.kt
betulnecanli
568,477,911
false
{"Kotlin": 167849}
package com.betulnecanli.kotlindatastructuresalgorithms.Complexity.SpaceComplexity fun main(){ //The time complexity of an algorithm isn't the only performance metric against which //algorithms are ranked. Another important metric is its space complexity, which is a //measure of the amount of memory it uses. val numbers = listOf(1, 3, 56, 66, 68, 80, 99, 105, 450) printSorted(numbers) printSortedOptimized(numbers) } //Since numbers.sorted() produces a new list with the same size of numbers, the //space complexity of printSorted is O(n). While this function is simple and elegant, //there may be some situations in which you want to allocate as little memory as //possible. fun printSorted(numbers: List<Int>) { val sorted = numbers.sorted() for (element in sorted) { println(element) } } //You could rewrite the above function like this: fun printSortedOptimized(numbers: List<Int>) { // 1 if (numbers.isEmpty()) return // 2 var currentCount = 0 var minValue = Int.MIN_VALUE // 3 for (value in numbers) { if (value == minValue) { println(value) currentCount += 1 } } while (currentCount < numbers.size) { // 4 var currentValue = numbers.max()!! for (value in numbers) { if (value < currentValue && value > minValue) { currentValue = value } } // 5 for (value in numbers) { if (value == currentValue) { println(value) currentCount += 1 } } // 6 minValue = currentValue } } //1. Check for the case if the list is empty. If it is, there’s nothing to print. //2. currentCount keeps track of the number of print statements made. minValue //stores the last printed value. //3. The algorithm begins by printing all values matching the minValue and updates //the currentCount according to the number of print statements made. //4. Using the while loop, the algorithm finds the lowest value bigger than minValue //and stores it in currentValue. //5. The algorithm then prints all values of currentValue inside the array while //updating currentCount. //6. minValue is set to currentValue, so the next iteration will try to find the next //minimum value. //The above algorithm only allocates memory for a few variables. Since the amount of //memory allocated is constant and does not depend on the size of the list, the space //complexity is O(1).
2
Kotlin
2
40
70a4a311f0c57928a32d7b4d795f98db3bdbeb02
2,543
Kotlin-Data-Structures-Algorithms
Apache License 2.0
src/main/kotlin/Lambdas+HigherOrderFunctions.kt
Muhammad-Shayan-Haider
611,615,684
false
null
import kotlin.math.pow fun main() { // Function stored in variable. Can be passed as argument as well. var fn: (a: Double, b: Double) -> Double = ::sum println(fn(2.0, 3.0)) fn = ::power println(fn(2.0, 3.0)) calculator(2.0, 4.0, fn) // Lambda functions are anonymous functions, which don't have names. val lambda1 = {x: Int, y: Int -> x + y} // last line in lambda is return line. val multilineLambda = { a: Int, b: String -> print("") print("") b } println(multilineLambda(2, "abc")) val singleParam: (Int) -> Int = { x -> x + x } val simplifiedLambdaWithSingleParam: (String) -> Int = { it.length } // it is default param for single param lambda. calculator(1.0, 2.0) {a, b -> a + b} // trailing lambda // map, filter and forEach val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9) val oddsList = nums.filter { a: Int -> a % 2 != 0 } // we can pass function in here as well with same signature. // map maps data to another form val squares = nums.map { (it * it).toDouble() } println(oddsList) // forEach nums.forEach { println(it) } } fun sum(a: Double, b: Double): Double { return a + b } fun power(a: Double, b: Double): Double { return a.pow(b) } // A higher order function is a function that accepts function as an argument or returns function or does both. fun calculator(a: Double, b: Double, fn: (a: Double, b: Double) -> Double) { var result = fn(a, b) println(result) }
0
Kotlin
0
0
676c8698e8a910534f0d43ed4ab5e7231b83ab60
1,544
kotlin-learning
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/BeautifulArray.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 // Beautiful Array @see <a href="https://leetcode.com/problems/beautiful-array/">Source</a> class BeautifulArray { private val memo: MutableMap<Int, IntArray> by lazy { HashMap() } operator fun invoke(n: Int): IntArray { var res = ArrayList<Int>() res.add(1) while (res.size < n) { val tmp = ArrayList<Int>() for (i in res) if (i * 2 - 1 <= n) tmp.add(i * 2 - 1) for (i in res) if (i * 2 <= n) tmp.add(i * 2) res = tmp } return res.stream().mapToInt { i: Int -> i }.toArray() } fun divideAndConquer(n: Int): IntArray { if (memo.containsKey(n)) return memo[n] ?: intArrayOf() val ans = IntArray(n) if (n == 1) { ans[0] = 1 } else { var t = 0 // odds val odds = n.plus(1).div(2) for (x in divideAndConquer(odds)) { ans[t++] = 2.times(x).minus(1) } // evens val evens = n.div(2) for (x in divideAndConquer(evens)) { ans[t++] = 2.times(x) } } memo[n] = ans return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,842
kotlab
Apache License 2.0
core/src/main/java/com/facebook/ktfmt/TypeNameClassifier.kt
cortinico
327,287,787
true
{"Kotlin": 284311, "Java": 30226, "Shell": 1655}
/* * Copyright 2015 Google Inc. * * 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. */ // This was copied from https://github.com/google/google-java-format and converted to Kotlin, // because the original is package-private. package com.facebook.ktfmt import com.google.common.base.Verify import java.util.Optional /** Heuristics for classifying qualified names as types. */ object TypeNameClassifier { /** A state machine for classifying qualified names. */ private enum class TyParseState(val isSingleUnit: Boolean) { /** The start state. */ START(false) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE -> // if we see an UpperCamel later, assume this was a class // e.g. com.google.FOO.Bar AMBIGUOUS JavaCaseFormat.LOWER_CAMEL -> REJECT JavaCaseFormat.LOWERCASE -> // could be a package START JavaCaseFormat.UPPER_CAMEL -> TYPE } } }, /** The current prefix is a type. */ TYPE(true) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE, JavaCaseFormat.LOWER_CAMEL, JavaCaseFormat.LOWERCASE -> FIRST_STATIC_MEMBER JavaCaseFormat.UPPER_CAMEL -> TYPE } } }, /** The current prefix is a type, followed by a single static member access. */ FIRST_STATIC_MEMBER(true) { override fun next(n: JavaCaseFormat): TyParseState { return REJECT } }, /** Anything not represented by one of the other states. */ REJECT(false) { override fun next(n: JavaCaseFormat): TyParseState { return REJECT } }, /** An ambiguous type prefix. */ AMBIGUOUS(false) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE -> AMBIGUOUS JavaCaseFormat.LOWER_CAMEL, JavaCaseFormat.LOWERCASE -> REJECT JavaCaseFormat.UPPER_CAMEL -> TYPE } } }; /** Transition function. */ abstract fun next(n: JavaCaseFormat): TyParseState } /** * Returns the end index (inclusive) of the longest prefix that matches the naming conventions of * a type or static field access, or -1 if no such prefix was found. * * Examples: * * * ClassName * * ClassName.staticMemberName * * com.google.ClassName.InnerClass.staticMemberName */ internal fun typePrefixLength(nameParts: List<String>): Optional<Int> { var state = TyParseState.START var typeLength = Optional.empty<Int>() for (i in nameParts.indices) { state = state.next(JavaCaseFormat.from(nameParts[i])) if (state === TyParseState.REJECT) { break } if (state.isSingleUnit) { typeLength = Optional.of(i) } } return typeLength } /** Case formats used in Java identifiers. */ enum class JavaCaseFormat { UPPERCASE, LOWERCASE, UPPER_CAMEL, LOWER_CAMEL; companion object { /** Classifies an identifier's case format. */ internal fun from(name: String): JavaCaseFormat { Verify.verify(name.isNotEmpty()) var firstUppercase = false var hasUppercase = false var hasLowercase = false var first = true for (element in name) { if (!Character.isAlphabetic(element.toInt())) { continue } if (first) { firstUppercase = Character.isUpperCase(element) first = false } hasUppercase = hasUppercase or Character.isUpperCase(element) hasLowercase = hasLowercase or Character.isLowerCase(element) } return if (firstUppercase) { if (hasLowercase) UPPER_CAMEL else UPPERCASE } else { if (hasUppercase) LOWER_CAMEL else LOWERCASE } } } } }
2
null
1
1
3b168867acbd34aeb55f83f51416969bc87ac3ed
4,485
ktfmt
Apache License 2.0
neuro/src/main/java/com/bukalapak/neuro/AxonBranch.kt
bukalapak
167,192,746
false
null
package com.bukalapak.neuro class AxonBranch private constructor( private val id: String?, private val priority: Int, val expression: String, val action: SignalAction ) : Comparable<AxonBranch> { constructor( expression: String, action: SignalAction ) : this(null, DEFAULT_PRIORITY, expression, action) constructor( id: String, expression: String, priority: Int = DEFAULT_PRIORITY, action: SignalAction ) : this(id, priority, expression, action) private val comparedPattern: String by lazy { // because space's ascii number is smaller than all supported character in URL val char = " " expression.replace(ANY_VARIABLE, char) } private val pattern: Regex by lazy { Regex(expression.toPattern()) } internal fun isMatch(path: String?): Boolean { val cleanPath = path ?: "" // if pattern is longer than path, it's an imposible match if (comparedPattern.length > cleanPath.length) return false return pattern.matches(cleanPath) } /** * Priorities: * #1 lowest priority number * #2 longest pattern length * #3 alphabetical by pattern * #4 alphabetical by id */ override fun compareTo(other: AxonBranch): Int { val priority1 = priority val priority2 = other.priority return if (priority1 == priority2) { val patternLength1 = comparedPattern.length val patternLength2 = other.comparedPattern.length if (patternLength1 == patternLength2) { val pattern1 = comparedPattern val pattern2 = other.comparedPattern if (pattern1 == pattern2) { val id1 = id val id2 = other.id if (id1 != null && id2 != null) { id1.compareTo(id2) } else { id2.orEmpty().compareTo(id1.orEmpty()) } } else pattern1.compareTo(pattern2) } else patternLength2 - patternLength1 } else priority1 - priority2 } override fun toString(): String { return if (id != null) { "$expression ($id)" } else expression } companion object { const val DEFAULT_PRIORITY = 100 } }
0
Kotlin
6
24
b6707ad6f682bbd929febdd39054f10c57b1b12d
2,392
neuro
Apache License 2.0
src/main/kotlin/com/polydus/aoc18/Day11.kt
Polydus
160,193,832
false
null
package com.polydus.aoc18 class Day11: Day(11){ //https://adventofcode.com/2018/day/11 val map = Array(300) {IntArray(300)} init { val input = input[0].toInt() for(y in 1 until map.size + 1){ for(x in 1 until map.size + 1){ //map[y][x] = -1 if(x == 3 && y == 5){ //println() } val rackId = x + 10 var powerLevel = rackId * y powerLevel += input powerLevel *= rackId val str = powerLevel.toString() //println("hunds digit of $powerLevel is ${str.substring(str.length - 3, str.length - 2).toInt()}") powerLevel = str.substring(str.length - 3, str.length - 2).toInt() powerLevel -= 5 map[y - 1][x - 1] = powerLevel } } //var x0 = 33 //var y0 = 45 //3628 /*for(y in y0 until y0 + 3){ for(x in x0 until x0 + 3){ val amount = map[y - 1][x - 1] if(amount < 0){ //print("${amount} ") } else { //(" ${amount} ") } } //print("\n") }*/ //partOne() partTwo() } fun partOne(){ var bestSum = 0 var bestX = 0 var bestY = 0 repeat(map.size - 2){y0 -> repeat(map.size - 2){x0-> var sum = 0 for(y in y0 until y0 + 3){ for(x in x0 until x0 + 3){ val amount = map[y][x] if(amount < 0){ //print("${amount} ") } else { //print(" ${amount} ") } sum += amount } //print("\n") } if(sum > bestSum){ bestSum = sum bestX = x0 + 1 bestY = y0 + 1 //println("best sum is $bestSum $bestX $bestY") } } } println("best sum is $bestSum | ${bestX},${bestY}") } fun partTwo(){ var bestSum = 0 var bestSize = 0 var bestX = 0 var bestY = 0 //var size = 3 for(size in 3 until 300){ repeat(map.size - (size - 1)){y0 -> repeat(map.size - (size - 1)){x0-> var sum = 0 for(y in y0 until y0 + size){ for(x in x0 until x0 + size){ sum += map[y][x] } } if(sum > bestSum){ bestSum = sum bestSize = size bestX = x0 + 1 bestY = y0 + 1 println("best sum is $bestSum | $bestX,$bestY | $bestSize") } } } } println("best sum is $bestSum | ${bestX},${bestY} | $bestSize") } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
3,217
advent-of-code-2018
MIT License
src/main/kotlin/Main.kt
BrightOS
618,267,574
false
null
import java.io.File fun parseInputFile(file: File): Pair<ArrayList<Process>, Int> { var resultNumberOfTicks = 0 val list = arrayListOf<Process>().apply { file.forEachLine { it.split(" ").let { add( Process( name = it[0], numberOfTicks = it[1].toInt(), appearanceTime = if (it.size > 2) it[2].toInt() else 0 ).let { resultNumberOfTicks += it.numberOfTicks it } ) } } } return Pair(list, resultNumberOfTicks) } fun main() { val numberOfActualTicks: Int var numberOfWaitTicks = 0 var numberOfAbstractTicks = 0 var currentTick = 0 val processList = parseInputFile( // File("test1") File("test2") ).let { numberOfActualTicks = it.second it.first } val ticks = arrayListOf<String>() println(numberOfActualTicks) repeat(numberOfActualTicks) { processList.filter { it.appearanceTime <= currentTick && it.ticksLeft > 0 }.let { sublist -> if (sublist.isNotEmpty()) sublist.minBy { it.ticksLeft }.let { ticks.add(it.name) it.ticksLeft-- } else { ticks.add("_") } } currentTick++ } processList.forEach { process -> print( "${process.name} ${process.numberOfTicks} ${process.appearanceTime} " ) currentTick = 0 ticks.subList(0, ticks.indexOfLast { it.contains(process.name) } + 1).forEach { processName -> print(processName.contains(process.name).let { if (currentTick < process.appearanceTime) " " else { if (!it) numberOfWaitTicks++ numberOfAbstractTicks++ if (it) "И" else "Г" } }) currentTick++ } println() } // println(ticks) println("Efficiency: ${"%.${2}f".format((numberOfWaitTicks.toFloat() / numberOfAbstractTicks * 100))}%") } data class Process( val name: String, val numberOfTicks: Int, val appearanceTime: Int, var ticksLeft: Int = numberOfTicks )
0
Kotlin
0
0
7f4a263277becf1a86392369d83a6a48f81cf7c4
2,382
os_3
Apache License 2.0
2022/Day05/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import java.util.ArrayDeque import kotlin.collections.indexOf fun main(args: Array<String>) { val lines = File(args[0]).readLines() val separatorIdx = lines.indexOf("") val stackLines = lines.subList(0, separatorIdx) val moveLines = lines.subList(separatorIdx + 1, lines.size) println(problem1(createStacks(stackLines), moveLines)) println(problem2(createStacks(stackLines), moveLines)) } fun createStacks(stackLines: List<String>): List<ArrayDeque<Char>> { val numStacks = stackLines.last().takeLast(2).first().toString().toInt() val stacks = List(numStacks, { ArrayDeque<Char>() }) for (i in stackLines.size - 2 downTo 0) { for (j in 0..numStacks - 1) { val crate = stackLines[i][1 + j * 4] if (crate != ' ') { stacks[j].push(crate) } } } return stacks } fun problem1(stacks: List<ArrayDeque<Char>>, moves: List<String>): String { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() for (move in moves) { val (count, from, to) = regex.find(move)!!.destructured for (i in 1..count.toInt()) { stacks[to.toInt() - 1].push(stacks[from.toInt() - 1].pop()) } } return stacks.map { it.peek() }.joinToString("") } fun problem2(stacks: List<ArrayDeque<Char>>, moves: List<String>): String { val regex = """move (\d+) from (\d+) to (\d+)""".toRegex() for (move in moves) { val (count, from, to) = regex.find(move)!!.destructured val buffer = mutableListOf<Char>() for (i in 1..count.toInt()) { buffer.add(stacks[from.toInt() - 1].pop()) } for (crate in buffer.asReversed()) { stacks[to.toInt() - 1].push(crate) } } return stacks.map { it.peek() }.joinToString("") }
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
1,842
AdventOfCode
MIT License