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
2022/src/day09/Day09.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day09 import java.io.File import kotlin.math.absoluteValue fun main() { val input = File("src/day09/day09input.txt").readLines() val rope = Rope(2) rope.processInput(input) println(rope.getVisitedCount()) val longRope = Rope(10) longRope.processInput(input) println(longRope.getVisitedCount()) } typealias Cell = Pair<Int, Int> class Rope { private val _segments: MutableList<Cell> private val _seenPositions = mutableSetOf(Cell(0, 0)) constructor(segmentCount: Int) { _segments = MutableList(segmentCount) { Cell(0, 0) } } fun processInput(input: List<String>) { for (s in input) { val (direction, count) = s.split(" ") move(direction, count.toInt()) } } fun move(direction: String, count: Int) { val deltaX = when (direction) { "L" -> -1 "R" -> 1 else -> 0 } val deltaY = when (direction) { "U" -> 1 "D" -> -1 else -> 0 } (0 until count).forEach { _ -> _segments[0] = Cell(_segments[0].first + deltaX, _segments[0].second + deltaY) for (index in 0.._segments.size - 2) { moveSegmentIfNecessary(_segments[index], _segments[index + 1], index + 1) } } } private fun moveSegmentIfNecessary(segment: Cell, nextSegment: Cell, index: Int) { val gapX = nextSegment.first - segment.first val gapY = nextSegment.second - segment.second if (gapX.absoluteValue > 1 || gapY.absoluteValue > 1) { // Move the next segment if (gapX == 0 || gapY.absoluteValue > gapX.absoluteValue) { // We are on the same X or should be on the same X _segments[index] = Cell(segment.first, segment.second + (if (gapY > 0) 1 else -1)) } else if (gapY == 0 || gapX.absoluteValue > gapY.absoluteValue) { // We are on the same Y or should be on the same Y _segments[index] = Cell(segment.first + (if (gapX > 0) 1 else -1), segment.second) } else { // We are diagonal and have to move diagonal towards _segments[index] = Cell(segment.first + (if (gapX > 0) 1 else -1), segment.second + (if (gapY > 0) 1 else -1)) } } if (index == _segments.size - 1) { _seenPositions.add(_segments[index]) } } fun getVisitedCount(): Int { // println(_seenPositions) return _seenPositions.size } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
2,611
adventofcode
Apache License 2.0
src/day9/fr/Day09_1.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day9.fr import java.io.File private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun readInput(name: String) = File("src", "$name.txt").readLines() data class Bool4(var vrai: Boolean) { var p1 = true var p2 = true var p3 = true var p4 = true fun toutVrai() : Boolean { vrai = (p1 && p2 && p3 && p4) return vrai } } fun main() { var rep = 0L val vIn = readInput("input9") //val vIn = readInput("test9") val nL = vIn[0].length val nH = vIn.size var tabPoints: Array<Array<Int>> = Array (nH + 1) { Array(nL + 1) { -1 } } vIn.forEachIndexed { idx, it -> it.forEachIndexed { index, ch -> tabPoints[idx + 1][index + 1] = ch.code - 48 } } for (i in 1..nH) { for (j in 1 .. nL) { var v = tabPoints[i][j] var isVrai = false var verite = Bool4(isVrai) if ((i - 1) > 0) { if (tabPoints[i - 1][j] <= v) { verite.p1 = false } } if ((j - 1) > 0) { if (tabPoints[i][j - 1] <= v) { verite.p2 = false } } if ((j + 1) <= nL) { if (tabPoints[i][j + 1] <= v) { verite.p3 = false } } if ((i + 1) <= nH) { if (tabPoints[i + 1][j] <= v) { verite.p2 = false } } if (verite.toutVrai()) { rep += (1 + v) } } } println(rep) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
2,433
Advent-of-Code-2021
Apache License 2.0
jeorg-kotlin-algorithms/jeorg-kotlin-alg-2-bfs/src/main/kotlin/org/jesperancinha/algorithms/bfs/Bfs.kt
jesperancinha
354,756,418
false
{"Kotlin": 35444, "Java": 14401, "JavaScript": 10140, "Python": 4018, "Makefile": 1258, "Shell": 89}
package org.jesperancinha.algorithms.bfs import org.jesperancinha.algorithms.bfs.model.Station import org.jesperancinha.algorithms.bfs.model.TravelNode import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer fun main(args: Array<String>) { val railwaySystemMap = createRailwaySystem() outRoutes("olhao", "oliveiraDeAzemeis", railwaySystemMap) outRoutes("olhao", "valenca", railwaySystemMap) outRoutes("olhao", "lx", railwaySystemMap) outRoutes("olhao", "portimao", railwaySystemMap) outRoutes("olhao", "lagos", railwaySystemMap) outRoutes("olhao", "vilaReal", railwaySystemMap) outRoutes("olhao", "guarda", railwaySystemMap) outRoutes("olhao", "covilha", railwaySystemMap) } private fun outRoutes( startName: String, endName: String, railwaySystemMap: HashMap<String, Station> ) { val start = railwaySystemMap[startName] val end = railwaySystemMap[endName] ConsolerizerComposer.out() .green("🚂 - We start travelling from %s", start) val routeList = calculateRoutes(start!!, end!!, railwaySystemMap) ConsolerizerComposer.outSpace().yellow(routeList) ConsolerizerComposer.out() .red("🚂 - We stop travelling at %s", end) } private fun convertToRoutes( routeList: MutableList<TravelNode>, railwaySystemMap: HashMap<String, Station> ): List<List<Station?>> { val routes = routeList.map { val fastestRouteList = ArrayDeque<Station?>() fastestRouteList.addFirst(railwaySystemMap[it.key]) var up = it; do { up = up.back!!; fastestRouteList.addFirst(railwaySystemMap[up.key]) } while (up.back != null) fastestRouteList.toList() } return routes } /** * procedure BFS(G, root) is * let Q be a queue * label root as discovered * Q.enqueue(root) * while Q is not empty do * v := Q.dequeue() * if v is the goal then * return v * for all edges from v to w in G.adjacentEdges(v) do * if w is not labeled as discovered then * label w as discovered * Q.enqueue(w) **/ fun calculateRoutes(start: Station, end: Station, railwaySystemMap: HashMap<String, Station>): List<List<Station?>> { val routes = mutableListOf<TravelNode>() val queue = ArrayDeque<TravelNode>() val currentNode = TravelNode(start.name, start.key) val visited = mutableMapOf<String, Boolean>() start.linkedStations.forEach { val element = TravelNode(it.name, it.key) queue.addFirst(element) visited[it.name] = true currentNode.linkedStations.add(element) element.back = currentNode if (it.key === end.key) { routes.add(element) } } resolve(queue, routes, end, visited, railwaySystemMap) return convertToRoutes(routes, railwaySystemMap) } fun resolve( queue: ArrayDeque<TravelNode>, routes: MutableList<TravelNode>, end: Station, visited: MutableMap<String, Boolean>, railwaySystemMap: HashMap<String, Station> ) { if (queue.isNotEmpty()) { val removeLast = queue.removeLast() val station = railwaySystemMap[removeLast.key] station!!.linkedStations.forEach { if (visited[it.key] === null || !visited[it.key]!!) { val element = TravelNode(it.name, it.key) queue.addFirst(element) visited[it.key] = true element.back = removeLast if (it.key === end.key) { routes.add(element) } } } resolve(queue, routes, end, visited, railwaySystemMap) } } private fun createRailwaySystem(): HashMap<String, Station> { val olhao = Station("Olhão", "olhao") val faro = Station("Faro", "faro") val tavira = Station("Tavira", "tavira") val vilaReal = Station("Vila Real de Santo António", "vilaReal") val tunes = Station("Tunes", "tunes") val portimao = Station("Portimão", "portimao") val lagos = Station("Lagos", "lagos") val funcheira = Station("Funcheira", "funcheira") val lx = Station("Lisboa", "lx") val sintra = Station("Sintra", "sintra") val cascais = Station("Cascais", "cascais") val azambuja = Station("Azambuja", "azambuja") val vendasNovas = Station("Vendas Novas", "vendasNovas") val setubal = Station("Setúbal", "setubal") val casaBranca = Station("Casa Branca", "casaBranca") val evora = Station("Évora", "evora") val beja = Station("Beja", "beja") val santarem = Station("Santarém", "santarem") val entroncamento = Station("Entroncamento", "entroncamento") val abrantes = Station("Abrantes", "abrantes") val tomar = Station("Tomar", "tomar") val portalegre = Station("Portalegre", "portalegre") val casteloBranco = Station("Castelo Branco", "casteloBranco") val covilha = Station("Covilhã", "covilha") val elvas = Station("Elvas", "elvas") val coimbra = Station("Coimbra", "coimbra") val figureiraFoz = Station("Figueira da Foz", "figureiraFoz") val leiria = Station("Leiria", "leiria") val caldasDaRainha = Station("Caldas da Rainha", "caldasDaRainha") val pampilhosa = Station("Pampilhosa", "pampilhosa") val guarda = Station("Guarda", "guarda") val vilarFormoso = Station("Vilar Formoso", "vilarFormoso") val aveiro = Station("Aveiro", "aveiro") val agueda = Station("Águeda", "agueda") val sernadaVouga = Station("Sernada do Vouga", "sernadaVouga") val oliveiraDeAzemeis = Station("Oliveira de Azeméis", "oliveiraDeAzemeis") val espinho = Station("Espinho", "espinho") val porto = Station("Porto", "porto") val caide = Station("Caíde", "caide") val regua = Station("Régua", "regua") val tua = Station("Tua", "tua") val pocinho = Station("Pocinho", "pocinho") val guimaraes = Station("Guimarães", "guimaraes") val braga = Station("Braga", "braga") val barcelos = Station("Barcelos", "barcelos") val vianaCastelo = Station("Viana do Castelo", "vianaCastelo") val valenca = Station("Valença", "valenca") val railMap = hashMapOf( "olhao" to olhao, "faro" to faro, "tavira" to tavira, "vilaReal" to vilaReal, "tunes" to tunes, "portimao" to portimao, "lagos" to lagos, "funcheira" to funcheira, "lx" to lx, "sintra" to sintra, "cascais" to cascais, "azambuja" to azambuja, "vendasNovas" to vendasNovas, "setubal" to setubal, "casaBranca" to casaBranca, "evora" to evora, "beja" to beja, "santarem" to santarem, "entroncamento" to entroncamento, "abrantes" to abrantes, "tomar" to tomar, "portalegre" to portalegre, "casteloBranco" to casteloBranco, "covilha" to covilha, "elvas" to elvas, "coimbra" to coimbra, "figureiraFoz" to figureiraFoz, "leiria" to leiria, "caldasDaRainha" to caldasDaRainha, "pampilhosa" to pampilhosa, "guarda" to guarda, "vilarFormoso" to vilarFormoso, "aveiro" to aveiro, "agueda" to agueda, "sernadaVouga" to sernadaVouga, "oliveiraDeAzemeis" to oliveiraDeAzemeis, "espinho" to espinho, "porto" to porto, "caide" to caide, "regua" to regua, "tua" to tua, "pocinho" to pocinho, "guimaraes" to guimaraes, "braga" to braga, "barcelos" to barcelos, "vianaCastelo" to vianaCastelo, "valenca" to valenca ) olhao.linkedStations.add(faro) olhao.linkedStations.add(tavira) tavira.linkedStations.add(vilaReal) tavira.linkedStations.add(olhao) vilaReal.linkedStations.add(tavira) faro.linkedStations.add(olhao) faro.linkedStations.add(tunes) tunes.linkedStations.add(faro) tunes.linkedStations.add(portimao) tunes.linkedStations.add(funcheira) portimao.linkedStations.add(tunes) portimao.linkedStations.add(lagos) lagos.linkedStations.add(portimao) funcheira.linkedStations.add(tunes) funcheira.linkedStations.add(lx) funcheira.linkedStations.add(vendasNovas) funcheira.linkedStations.add(setubal) vendasNovas.linkedStations.add(casaBranca) vendasNovas.linkedStations.add(funcheira) vendasNovas.linkedStations.add(setubal) vendasNovas.linkedStations.add(lx) casaBranca.linkedStations.add(vendasNovas) casaBranca.linkedStations.add(evora) casaBranca.linkedStations.add(beja) evora.linkedStations.add(casaBranca) beja.linkedStations.add(casaBranca) lx.linkedStations.add(funcheira) lx.linkedStations.add(setubal) lx.linkedStations.add(vendasNovas) lx.linkedStations.add(azambuja) lx.linkedStations.add(sintra) lx.linkedStations.add(cascais) cascais.linkedStations.add(lx) sintra.linkedStations.add(caldasDaRainha) sintra.linkedStations.add(lx) caldasDaRainha.linkedStations.add(leiria) caldasDaRainha.linkedStations.add(sintra) leiria.linkedStations.add(figureiraFoz) leiria.linkedStations.add(caldasDaRainha) leiria.linkedStations.add(coimbra) azambuja.linkedStations.add(lx) azambuja.linkedStations.add(santarem) santarem.linkedStations.add(entroncamento) santarem.linkedStations.add(azambuja) entroncamento.linkedStations.add(abrantes) entroncamento.linkedStations.add(santarem) entroncamento.linkedStations.add(tomar) entroncamento.linkedStations.add(coimbra) abrantes.linkedStations.add(entroncamento) abrantes.linkedStations.add(casteloBranco) abrantes.linkedStations.add(portalegre) casteloBranco.linkedStations.add(covilha) casteloBranco.linkedStations.add(abrantes) covilha.linkedStations.add(casteloBranco) portalegre.linkedStations.add(abrantes) portalegre.linkedStations.add(elvas) elvas.linkedStations.add(portalegre) tomar.linkedStations.add(coimbra) tomar.linkedStations.add(entroncamento) coimbra.linkedStations.add(figureiraFoz) coimbra.linkedStations.add(leiria) coimbra.linkedStations.add(tomar) coimbra.linkedStations.add(entroncamento) coimbra.linkedStations.add(pampilhosa) pampilhosa.linkedStations.add(guarda) pampilhosa.linkedStations.add(coimbra) pampilhosa.linkedStations.add(aveiro) guarda.linkedStations.add(pampilhosa) guarda.linkedStations.add(vilarFormoso) vilarFormoso.linkedStations.add(guarda) aveiro.linkedStations.add(pampilhosa) aveiro.linkedStations.add(agueda) aveiro.linkedStations.add(espinho) agueda.linkedStations.add(aveiro) agueda.linkedStations.add(sernadaVouga) sernadaVouga.linkedStations.add(oliveiraDeAzemeis) sernadaVouga.linkedStations.add(agueda) oliveiraDeAzemeis.linkedStations.add(espinho) oliveiraDeAzemeis.linkedStations.add(sernadaVouga) espinho.linkedStations.add(oliveiraDeAzemeis) espinho.linkedStations.add(aveiro) espinho.linkedStations.add(porto) porto.linkedStations.add(espinho) porto.linkedStations.add(caide) porto.linkedStations.add(guimaraes) porto.linkedStations.add(braga) porto.linkedStations.add(barcelos) caide.linkedStations.add(regua) caide.linkedStations.add(porto) regua.linkedStations.add(caide) regua.linkedStations.add(tua) tua.linkedStations.add(regua) tua.linkedStations.add(pocinho) pocinho.linkedStations.add(tua) braga.linkedStations.add(barcelos) braga.linkedStations.add(guimaraes) braga.linkedStations.add(porto) guimaraes.linkedStations.add(braga) guimaraes.linkedStations.add(barcelos) guimaraes.linkedStations.add(porto) barcelos.linkedStations.add(braga) barcelos.linkedStations.add(guimaraes) barcelos.linkedStations.add(porto) barcelos.linkedStations.add(vianaCastelo) vianaCastelo.linkedStations.add(barcelos) vianaCastelo.linkedStations.add(valenca) valenca.linkedStations.add(vianaCastelo) return railMap }
1
Kotlin
0
1
7a382ed529ebdc53cc025671a453c7bd5699539e
12,168
jeorg-algorithms-test-drives
Apache License 2.0
src/Day15.kt
Totwart123
573,119,178
false
null
import kotlin.math.abs import kotlin.math.absoluteValue import kotlin.math.min fun main() { data class Beacon(val x: Int, val y: Int){ override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Beacon if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } data class Sensor(val x: Int, val y: Int, val nearestBeacon: Beacon, val distanceToBeacon: Int) fun calcDistance(from: Pair<Int,Int>, to: Pair<Int, Int>): Int{ return (from.first - to.first).absoluteValue + (from.second - to.second).absoluteValue } fun calcPossibleBeaconPositionsInRow(sensors: List<Sensor>, beacons: List<Beacon>, row: Int) : Int{ val maxDistance = sensors.maxOf { it.distanceToBeacon } val minX = sensors.minOf { it.x } - maxDistance val maxX = sensors.maxOf { it.x } + maxDistance var countBeaconNotToBe = 0 for(i in minX..maxX){ if(sensors.any{calcDistance(Pair(it.x, it.y), Pair(i, row)) <= it.distanceToBeacon} && !beacons.any { it.x == i && it.y == row }){ countBeaconNotToBe ++ } } return countBeaconNotToBe } fun calcPossibleBeaconPositionInRowSlow(sensors: List<Sensor>, beacons: List<Beacon>, max: Int) : Pair<Int, Int>{ val maxDistance = sensors.maxOf { it.distanceToBeacon } var minX = sensors.minOf { it.x } - maxDistance var maxX = sensors.maxOf { it.x } + maxDistance var minY = sensors.minOf { it.y } - maxDistance var maxY = sensors.maxOf { it.y } + maxDistance minX = if(minX < 0) 0 else minX minY = if(minY < 0) 0 else minY maxX = if(maxX > max) max else maxX maxY = if(maxY > max) max else maxY for(i in minY until maxY){ for(j in minX until maxX){ if(!sensors.any{calcDistance(Pair(it.x, it.y), Pair(j, i)) <= it.distanceToBeacon} && !beacons.any { it.x == j && it.y == i }){ return Pair(j, i) } } } return Pair(-1, -1) } fun calcRange(sensor: Sensor, row: Int): Pair<Int, Int>? { val yDist = abs(sensor.y - row) if(yDist > sensor.distanceToBeacon){ return null } val xDist = sensor.distanceToBeacon - yDist return Pair(sensor.x - xDist, sensor.x + xDist) } fun part2Fast(sensors: List<Sensor>, max: Int, beacons: List<Beacon>) : Pair<Int, Int>{ for(row in 0 until max){ println(row) val ranges = sensors.mapNotNull { calcRange(it, row) }.toMutableList() val newRanges = ranges.toMutableList() var isOverlapping = true while(isOverlapping){ isOverlapping = false for(i in ranges.indices){ for(j in i+1 until ranges.size){ val a = ranges[i].first val b = ranges[i].second val c = ranges[j].first val d = ranges[j].second if(a <= d && b >= c){ val left = min(a, c) val right = Math.max(b, d) newRanges.remove(ranges[i]) newRanges.remove(ranges[j]) newRanges.add(Pair(left, right)) isOverlapping = true } } } ranges.clear() ranges.addAll(newRanges) } if(ranges.size > 1){ val x = if (ranges[0].first < ranges[1].first) ranges[0].second + 1 else ranges[1].second + 1 if(!beacons.any{it.x == x && it.y == row}){ return Pair(x, row) } } } return Pair(-1 , -1) } fun part1(input: List<String>, row: Int): Int { val beacons = mutableListOf<Beacon>() val sensors = mutableListOf<Sensor>() input.forEach { line -> val sensorData = line.split(":")[0].replace("Sensor at ", "") val beaconData = line.split(":")[1].replace(" closest beacon is at ", "") var coords = beaconData.split(",") val beacon = Beacon(coords[0].split("=")[1].toInt(), coords[1].split("=")[1].toInt()) if(!beacons.contains(beacon)){ beacons.add(beacon) } coords = sensorData.split(",") val sensorX = coords[0].split("=")[1].toInt() val sensorY = coords[1].split("=")[1].toInt() val distance = calcDistance(Pair(beacon.x, beacon.y), Pair(sensorX, sensorY)) val sensor = Sensor(sensorX, sensorY, beacon, distance) sensors.add(sensor) } return calcPossibleBeaconPositionsInRow(sensors, beacons, row) } fun part2(input: List<String>, max: Int): Int { val beacons = mutableListOf<Beacon>() val sensors = mutableListOf<Sensor>() input.forEach { line -> val sensorData = line.split(":")[0].replace("Sensor at ", "") val beaconData = line.split(":")[1].replace(" closest beacon is at ", "") var coords = beaconData.split(",") val beacon = Beacon(coords[0].split("=")[1].toInt(), coords[1].split("=")[1].toInt()) if(!beacons.contains(beacon)){ beacons.add(beacon) } coords = sensorData.split(",") val sensorX = coords[0].split("=")[1].toInt() val sensorY = coords[1].split("=")[1].toInt() val distance = calcDistance(Pair(beacon.x, beacon.y), Pair(sensorX, sensorY)) val sensor = Sensor(sensorX, sensorY, beacon, distance) sensors.add(sensor) } val result = part2Fast(sensors, max, beacons) return result.first * 4000000 + result.second } val testInput = readInput("Day15_test") //check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011) val input = readInput("Day15") //println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
6,558
AoC
Apache License 2.0
src/Day06.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
fun main() { fun solution(input: List<String>, n: Int): Int { return input.filter { return@filter it.isNotEmpty() }.sumOf { l -> val (i, _) = l .windowed(n) .withIndex() .find { (_, w) -> w.toSet().size == n }!! return@sumOf i + n } } val testInput = readInput("Day06_test") check(solution(testInput, 4) == 7 + 5 + 6 + 10 + 11) check(solution(testInput, 14) == 19 + 23 + 23 + 29 + 26) val input = readInput("Day06") println(solution(input, 4)) println(solution(input, 14)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
633
aoc-2022
Apache License 2.0
2020/kotlin/src/main/kotlin/io/franmosteiro/aoc2020/Day08.kt
franmosteiro
433,734,642
false
{"Kotlin": 27170, "Ruby": 16611, "Shell": 389}
package io.franmosteiro.aoc2020 /** * Advent of Code 2020 - Day 8: Handheld Halting - * Problem Description: http://adventofcode.com/2020/day/8 */ class Day08(input: List<String>) { private val orders: List<Order> = input.map { val (name, offset) = it.split("\\s".toRegex()) Order(name, offset.toInt()) } fun resolvePartOne(): Int { val (position, accumulator) = Program().run(orders) return accumulator } fun resolvePartTwo(): Int { orders.forEachIndexed { i, order -> when (order.name) { "jmp" -> orders.toMutableList().also { orders -> orders[i] = Order("nop", order.offset) } "nop" -> orders.toMutableList().also { orders -> orders[i] = Order("jmp", order.offset) } else -> null }?.let { val (position, accumulator) = Program().run(it) if (position == orders.size) { return accumulator } } } return -1 } data class Program( var position: Int = 0, var accumulator: Int = 0, var executedOrdersPositions: MutableSet<Int> = mutableSetOf()) { fun run(orders: List<Order>): Pair<Int, Int> { while (true) { if (position in executedOrdersPositions || position >= orders.size) { return position to accumulator } executedOrdersPositions.add(position) val currentOrder = orders[position] when (currentOrder.name) { "jmp" -> position += currentOrder.offset "nop" -> position++ "acc" -> { accumulator += currentOrder.offset position++ } } } } } data class Order( val name: String, val offset: Int, ) }
0
Kotlin
0
0
dad555d9cd0c3060c4b1353c7c6f170aa340c285
2,001
advent-of-code
MIT License
src/main/kotlin/com/github/nicomincuzzi/Day2Dive.kt
NicoMincuzzi
435,492,958
false
{"Kotlin": 11507}
package com.github.nicomincuzzi import kotlin.math.abs class Day2Dive { fun horizontalPositionAndDepth(commands: List<Pair<String, Int>>): Int { val result = hashMapOf<String, Int>() for (command in commands) { if (calculateHorizontalPosition(result, command)) continue if (calculateDepth(result, command)) continue when (command.first) { "forward" -> result[command.first] = command.second "down" -> result["depth"] = command.second * -1 else -> result["depth"] = command.second } } return calculatePlannedCourse(result, "depth") } private fun calculateHorizontalPosition(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean { if (result.containsKey(command.first) && command.first == "forward") { result[command.first] = result[command.first]?.plus(command.second)!! return true } return false } fun horizontalPositionAndDepthPartTwo(commands: List<Pair<String, Int>>): Int { val result = hashMapOf<String, Int>() for (command in commands) { if (calculateHorizontalPositionTwoPart(result, command)) continue if (calculateDepth(result, command)) continue when (command.first) { "forward" -> { result[command.first] = command.second calculateAim(result, command) } "down" -> result["depth"] = command.second * -1 else -> result["depth"] = command.second } } return calculatePlannedCourse(result, "aim") } private fun calculateHorizontalPositionTwoPart(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean { if (result.containsKey(command.first) && command.first == "forward") { result[command.first] = result[command.first]?.plus(command.second)!! calculateAim(result, command) return true } return false } private fun calculateAim(result: HashMap<String, Int>, command: Pair<String, Int>) { if (!result.containsKey("depth")) { return } if (result.containsKey("aim")) { result["aim"] = result["aim"]?.plus(result["depth"]!! * command.second)!! return } result["aim"] = result["depth"]!! * command.second } private fun calculateDepth(result: HashMap<String, Int>, command: Pair<String, Int>): Boolean { if (result.containsKey("depth")) { var updateValue = 1 if (command.first == "down") updateValue = -1 result["depth"] = result["depth"]?.plus(command.second * updateValue)!! return true } return false } private fun calculatePlannedCourse(result: HashMap<String, Int>, value: String) = result["forward"]!! * abs(result[value]!!) }
0
Kotlin
0
0
345b69cc4f995f369c1dc509ccfd3db8336d3dd8
3,012
adventofcode-2021
Apache License 2.0
src/main/kotlin/days/Day14.kt
sicruse
315,469,617
false
null
package days class Day14 : Day(14) { class BitMask(val bitMask: Long, val setBits: Long, val floatingBits: Set<Long>) { constructor(pattern: String):this(maskFromString(pattern), valueFromString(pattern), floatingFromString(pattern)) {} fun apply(data: Long): Long = data.and(bitMask).or(setBits) fun combinationUtil(input: LongArray, tempData: LongArray, result: MutableList<Set<Long>>, start: Int, end: Int, index: Int, r: Int) { if (index == r) { result += (0 until r).map{j -> tempData[j]}.toSet() return } var i = start while (i <= end && end - i + 1 >= r - index) { tempData[index] = input[i] combinationUtil(input, tempData, result, i + 1, end, index + 1, r) i++ } } fun combination(input: LongArray, n: Int, r: Int): List<Set<Long>> { // A temporary array to store all combination one by one val data = LongArray(r) val result = mutableListOf<Set<Long>>() // Generate all combinations using temprary array 'data[]' combinationUtil(input, data, result, 0, n - 1, 0, r) return result } fun allCombinations(data: Set<Long>): List<Set<Long>> { return (1 .. data.size).flatMap{combination(data.toLongArray(), data.size, it)} } fun decode(address: Long): Set<Long> { // first apply the bitmask val base = address.or(setBits) // then apply the floating val floatingMask = floatingBits.sum().inv() val baseMasked = base.and(floatingMask) val addresses = allCombinations(floatingBits).map{ it.sum() or baseMasked } return (addresses + baseMasked).toSet() } companion object { fun maskFromString(pattern: String): Long { val maskPattern = pattern.replace('X','1') val result = maskPattern.toLong(2) return result } fun valueFromString(pattern: String): Long { val maskPattern = pattern.replace('X','0') val result = maskPattern.toLong(2) return result } fun floatingFromString(pattern: String): Set<Long> { val bits = pattern.reversed().mapIndexedNotNull { i, c -> if (c == 'X') 1L.shl(i) else null }.toSet() return bits } } } class Procedure(val mask: BitMask, val instructions: Map<Long, Long>) { constructor(data: String): this(extractMask(data), extractInstructions(data)) fun execute(memory: MutableMap<Long, Long>) { for (instruction in instructions) memory[instruction.key] = mask.apply(instruction.value) } fun decode(memory: MutableMap<Long, Long>) { for (instruction in instructions) { val addresses = mask.decode(instruction.key) for (address in addresses) memory[address] = instruction.value } } companion object { val destructuredRegex = "mem\\[(\\d+)] = (\\d+)".toRegex() fun extractMask(data: String): BitMask { val mask = data.split("\n").first() return BitMask(mask) } fun extractInstructions(text: String): Map<Long, Long> { val values = text.split("\n").drop(1).filter{ it.length > 0 } return values.map { destructuredRegex.matchEntire(it) ?.destructured ?.let { (_address, _value) -> _address.toLong() to _value.toLong() } ?: throw IllegalArgumentException("Bad input '$text'") }.toMap() } } } private val procedures: List<Procedure> by lazy { val blocks = inputString.split("mask = ").drop(1) blocks.map{ Procedure( it )} } override fun partOne(): Any { val memory = mutableMapOf<Long, Long>() for (procedure in procedures) { procedure.execute(memory) } return memory.values.sum() } override fun partTwo(): Any { val memory = mutableMapOf<Long, Long>() for (procedure in procedures) { procedure.decode(memory) } return memory.values.sum() } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
4,599
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/day2.kt
danielfreer
297,196,924
false
null
import kotlin.time.ExperimentalTime @ExperimentalTime fun day2(input: List<String>): List<Solution> { val program = input.flatMap { it.split(",") }.map(String::toInt) return listOf( solve(2, 1) { executeWithReplacements(program) }, solve(2, 2) { calculateNounVerb(program) } ) } private const val ADD = 1 private const val MULTIPLY = 2 private const val RETURN = 99 private tailrec fun execute(state: MutableList<Int>, index: Int): List<Int> { return when (val opCode = state[index]) { ADD -> { state[state[index + 3]] = state[state[index + 1]] + state[state[index + 2]] execute(state, index + 4) } MULTIPLY -> { state[state[index + 3]] = state[state[index + 1]] * state[state[index + 2]] execute(state, index + 4) } RETURN -> state else -> throw IllegalStateException("Unknown opcode: $opCode") } } fun execute(program: List<Int>) = execute(program.toMutableList(), 0) private fun executeWithReplacements(program: List<Int>): Int { val mutableProgram = program.toMutableList().apply { this[1] = 12 this[2] = 2 } return execute(mutableProgram, 0)[0] } private fun calculateNounVerb(program: List<Int>): Int { (0..99).forEach { noun -> (0..99).forEach { verb -> val mutableProgram = program.toMutableList().apply { this[1] = noun this[2] = verb } if (execute(mutableProgram, 0)[0] == 19_690_720) { return 100 * noun + verb } } } throw java.lang.IllegalStateException("Could not find noun/verb pair") }
0
Kotlin
0
0
74371d15f95492dee1ac434f0bfab3f1160c5d3b
1,692
advent2019
The Unlicense
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions43.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.BinaryTreeNode import com.qiaoyuang.algorithm.round0.Queue fun test43() { printlnResult(testCase1(), 7) printlnResult(binaryTreeTestCase2(), 9) printlnResult(testCase3(), 8) } /** * Questions 43: Inset value to a complete binary tree */ private class CBTInserter<T :Comparable<T>>(val root: BinaryTreeNode<T>) { infix fun insert(v: T): BinaryTreeNode<T> { val line = Queue<BinaryTreeNode<T>>() line.enqueue(root) while (!line.isEmpty) { val node = line.dequeue() node.left?.let { line.enqueue(it) } ?: kotlin.run { node.left = BinaryTreeNode(v) return node } node.right?.let { line.enqueue(it) } ?: kotlin.run { if (node.left != null) { node.right = BinaryTreeNode(v) return node } } } throw IllegalArgumentException("The inputted binary tree seems like getting some problems") } } private fun printlnResult(root: BinaryTreeNode<Int>, v: Int) { println("Insert the value $v to binary tree: ${root.postOrderList()}") println("We can get the parent of $v is: ${CBTInserter(root).insert(v).value}") println("Now, the binary tree is: ${root.postOrderList()}") println("----------------------------------------------") } private fun testCase1(): BinaryTreeNode<Int> { val root = BinaryTreeNode(1) root.left = BinaryTreeNode( value = 2, left = BinaryTreeNode(4), right = BinaryTreeNode(5), ) root.right = BinaryTreeNode( value = 3, left = BinaryTreeNode(6), ) return root } fun binaryTreeTestCase2(): BinaryTreeNode<Int> { val root = BinaryTreeNode(1) root.left = BinaryTreeNode( value = 2, left = BinaryTreeNode( value = 4, left = BinaryTreeNode(8) ), right = BinaryTreeNode(5), ) root.right = BinaryTreeNode( value = 3, left = BinaryTreeNode(6), right = BinaryTreeNode(7), ) return root } private fun testCase3(): BinaryTreeNode<Int> { val root = BinaryTreeNode(1) root.left = BinaryTreeNode( value = 2, left = BinaryTreeNode(value = 4), right = BinaryTreeNode(5), ) root.right = BinaryTreeNode( value = 3, left = BinaryTreeNode(6), right = BinaryTreeNode(7), ) return root }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,595
Algorithm
Apache License 2.0
solutions/aockt/y2023/Y2023D09.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import io.github.jadarma.aockt.core.Solution object Y2023D09 : Solution { /** A history report from an OASIS Scanner, with the [values] of the sensor readings. */ private data class History(val values: List<Int>) : List<Int> by values { /** Predict the next value based on the existing list of [values]. */ private fun prediction(values: List<Int>) = generateSequence(values) { it.windowed(2) { (l, r) -> r - l } } .takeWhile { numbers -> numbers.any { it != 0 } } .sumOf { it.last() } /** Predict the next value of this report based on previously gathered [values]. */ val predictNext: Int by lazy { prediction(values) } /** Predict the last value before this report started gathering the [values]. */ val predictPrevious: Int by lazy { prediction(values.reversed()) } } /** Parse the [input] and return the Oasis Report histories. */ private fun parseInput(input: String): List<History> = parse { input .lineSequence() .map { it.split(' ').map(String::toInt) } .map(::History) .toList() } override fun partOne(input: String) = parseInput(input).sumOf(History::predictNext) override fun partTwo(input: String) = parseInput(input).sumOf(History::predictPrevious) }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
1,377
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/fluency.ws.kts
mikaelstaldal
531,628,632
false
{"Kotlin": 28924}
import kotlin.math.abs data class Complex(val real: Double, val imaginary: Double) { operator fun times(other: Complex) = Complex(real * other.real - imaginary * other.imaginary, real * other.imaginary + imaginary * other.real) private fun sign() = if (imaginary < 0) "-" else "+" override fun toString() = "$real ${sign()} ${abs(imaginary)}i" } println(Complex(4.0, 2.0) * Complex(-3.0, 4.0)) println(Complex(1.4, 2.2) * Complex(-3.8, 4.2)) data class Point(val x: Int, val y: Int) data class Circle(val cx: Int, val cy: Int, val radius: Int) infix operator fun Circle.contains(point: Point) = (point.x - cx) * (point.x - cx) + (point.y - cy) * (point.y - cy) < radius * radius val circle = Circle(cx = 100, cy = 100, radius = 25) val point1 = Point(110, 110) val point2 = Point(10, 100) println(circle.contains(point1)) println(circle contains point2) println(point1 in circle) println(point2 in circle) val Circle.area: Double get() = kotlin.math.PI * radius * radius println("Areas is ${circle.area}") fun String.isPalindrome(): Boolean = reversed() == this fun String.shout() = toUpperCase() val dad = "dad" println(dad.isPalindrome()) println(dad.shout()) fun <T, R, U> ((T) -> R).andThen(next: (R) -> U): (T) -> U = { input: T -> next(this(input)) } fun increment(number: Int): Double = number + 1.toDouble() fun double(number: Double) = number * 2 val incrementAndDouble = ::increment.andThen(::double) println(incrementAndDouble(5)) fun top(func: String.() -> Unit) = "hello".func() fun nested(func: Int.() -> Unit) = (-2).func() top { println("In outer lambda $this and $length") nested { println("in inner lambda $this and ${toDouble()}") println("from inner through receiver of outer: $length") println("from inner to outer receiver ${this@top}") } }
0
Kotlin
0
0
668df246d08e5b0fcf42cae02f4282f85c93f422
1,844
KotlinPlayground
Apache License 2.0
src/main/kotlin/leetcode/problem0120/Triangle.kt
ayukatawago
456,312,186
false
{"Kotlin": 266300, "Python": 1842}
package leetcode.problem0120 import kotlin.math.min class Triangle { fun minimumTotal(triangle: List<List<Int>>): Int = when (triangle.size) { 1 -> triangle[0][0] else -> { val array = Array(triangle.size) { intArrayOf() } array[0] = intArrayOf(triangle[0][0]) (1..triangle.lastIndex).forEach { array[it] = IntArray(it + 1) (0..array[it].lastIndex).forEach { index -> array[it][index] = triangle[it][index] + when (index) { 0 -> array[it - 1][index] array[it].lastIndex -> array[it - 1][index - 1] else -> min(array[it - 1][index], array[it - 1][index - 1]) } } } array[triangle.lastIndex].findMin() } } private fun IntArray.findMin(): Int { var minValue = this[0] for (i in 1..lastIndex) { val v = this[i] if (minValue > v) { minValue = v } } return minValue } }
0
Kotlin
0
0
f9602f2560a6c9102728ccbc5c1ff8fa421341b8
1,187
leetcode-kotlin
MIT License
src/questions/TopKFrequent.kt
realpacific
234,499,820
false
null
package questions import _utils.UseCommentAsDocumentation import utils.shouldBeOneOf import java.util.* /** * Given an integer array nums and an integer k, return the k most frequent elements. * You may return the answer in any order. * [Source](https://leetcode.com/problems/top-k-frequent-elements//) */ @UseCommentAsDocumentation fun topKFrequent(nums: IntArray, k: Int): IntArray { val charToCountMap = HashMap<Int, Int>(nums.size / 2) // Reverse sorted map of frequency to [nums] element val frequencyToCharMap = TreeMap<Int, MutableSet<Int>>(object : Comparator<Int> { override fun compare(o1: Int?, o2: Int?): Int { return o2!! - o1!! // This will be sorted in reverse order of frequency } }) for (i in 0..nums.lastIndex) { val value = nums[i] val prevCount = charToCountMap.getOrDefault(value, 0) val newCount = prevCount + 1 charToCountMap[value] = newCount if (prevCount > 0) { // it has been encountered before // so remove it from its old key val set = frequencyToCharMap.getOrDefault(prevCount, mutableSetOf()) set.remove(value) } // and add it to [newCount] key val set = frequencyToCharMap.getOrDefault(newCount, mutableSetOf()) set.add(value) frequencyToCharMap[newCount] = set } // Since [frequencyToCharMap] is reverse sorted, top k elements should be in first few position val result = IntArray(k) { 0 } var index = 0 for (numSet in frequencyToCharMap.values) { for (value in numSet) { result[index] = value if (index >= k) { break } index++ } if (index >= k) { break } } return result } fun main() { topKFrequent(intArrayOf(1, 1, 1, 2, 2, 3), 2) shouldBeOneOf listOf(intArrayOf(1, 2), intArrayOf(2, 1)) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
1,957
algorithms
MIT License
src/test/kotlin/ch/ranil/aoc/aoc2023/Day09.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2023 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day09 : AbstractDay() { @Test fun part1Test() { assertEquals(114, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(1731106378, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(2, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(1087, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { return input .sumOf { line -> line .readNumbers() .getHistory() .extrapolateRight() } } private fun compute2(input: List<String>): Int { return input .sumOf { line -> line .readNumbers() .getHistory() .extrapolateLeft() } } private fun String.readNumbers(): List<Int> { return this.split(" ").map { it.toInt() } } private fun List<List<Int>>.extrapolateRight(): Int { val numbers = this var i = numbers.size - 2 var extrapolatedNum = 0 while (i >= 0) { extrapolatedNum += numbers[i--].last() println("Extrapolated $extrapolatedNum") } return extrapolatedNum } private fun List<List<Int>>.extrapolateLeft(): Int { val numbers = this var i = numbers.size - 2 var extrapolatedNum = 0 while (i >= 0) { extrapolatedNum = numbers[i--].first() - extrapolatedNum println("Extrapolated $extrapolatedNum") } return extrapolatedNum } private fun List<Int>.getHistory(): List<List<Int>> { println("Building History for $this") val histories = mutableListOf(this) while (!histories.last().all { it == 0 }) { val nextLine = nextHistory(histories.last()) println(nextLine) histories.add(nextLine) } return histories } private fun nextHistory(numbers: List<Int>): List<Int> { return numbers.windowed(2) { (a, b) -> b - a } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
2,312
aoc
Apache License 2.0
src/Day10.kt
fercarcedo
573,142,185
false
{"Kotlin": 60181}
private const val NOOP_INSTRUCTION = "noop" private val ADDX_INSTRUCTION_REGEX = "addx\\s+(?<value>-?\\d+)".toRegex() private const val CRT_WIDTH = 40 private const val CRT_HEIGHT = 6 sealed class Instruction { object Noop: Instruction() { override val cycles: Int get() = 1 override fun toString() = "Noop" override fun execute(registerX: Int) = registerX } data class Addx(val value: Int): Instruction() { override val cycles: Int get() = 2 override fun execute(registerX: Int) = registerX + value } abstract val cycles: Int abstract fun execute(registerX: Int): Int } data class ExecutionResult( val signalStrengths: List<Int>, val crt: List<List<Char>> ) class Computer(private val crtEnabled: Boolean) { private var registerX = 1 private var cycle = 1 private var signalStrengths = mutableListOf<Int>() private var crt = mutableListOf(mutableListOf<Char>()) fun execute(instructions: List<Instruction>): ExecutionResult { checkCycle() for (instruction in instructions) { for (i in 0 until instruction.cycles) { cycle++ if (i < instruction.cycles - 1) { checkCycle() } } registerX = instruction.execute(registerX) checkCycle() } return ExecutionResult(signalStrengths, crt) } private fun checkCycle() { if (crtEnabled) { handleCrt() } if (cycle in listOf(20, 60, 100, 140, 180, 220)) { signalStrengths.add(cycle * registerX) } } private fun handleCrt() { if (cycle <= CRT_WIDTH * CRT_HEIGHT) { val crtPosition = (cycle - 1) % 40 crt.last().add(if (crtPosition >= (registerX - 1) && crtPosition <= (registerX + 1)) '#' else '.') if (cycle % 40 == 0 && cycle < CRT_WIDTH * CRT_HEIGHT) { crt.add(mutableListOf()) } } } } fun List<List<Char>>.crtToString() = joinToString("\n") { it.joinToString("") } fun main() { fun play(input: List<String>, crtEnabled: Boolean): ExecutionResult { val instructions = input.map { if (it.startsWith(NOOP_INSTRUCTION)) { Instruction.Noop } else { Instruction.Addx(ADDX_INSTRUCTION_REGEX.matchEntire(it)!!.groups["value"]!!.value.toInt()) } } return Computer(crtEnabled).execute(instructions) } fun part1(input: List<String>) = play(input, false).signalStrengths.sum() fun part2(input: List<String>) = play(input, true).crt val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput).crtToString() == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() ) val input = readInput("Day10") println(part1(input)) // 14360 println(part2(input).crtToString()) // ###...##..#..#..##..####.###..####.####. // #..#.#..#.#.#..#..#.#....#..#.#.......#. // ###..#....##...#..#.###..#..#.###....#.. // #..#.#.##.#.#..####.#....###..#.....#... // #..#.#..#.#.#..#..#.#....#.#..#....#.... //###...###.#..#.#..#.####.#..#.####.####. }
0
Kotlin
0
0
e34bc66389cd8f261ef4f1e2b7f7b664fa13f778
3,728
Advent-of-Code-2022-Kotlin
Apache License 2.0
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day09.kt
mpichler94
656,873,940
false
{"Kotlin": 196457}
package at.mpichler.aoc.solutions.year2021 import at.mpichler.aoc.lib.* import org.jetbrains.kotlinx.multik.api.mk import org.jetbrains.kotlinx.multik.api.ndarray import org.jetbrains.kotlinx.multik.ndarray.data.D2Array open class Part9A : PartSolution() { lateinit var heights: D2Array<Int> lateinit var lowPoints: List<Vector2i> override fun parseInput(text: String) { val lines = text.split("\n") val map = lines.map { it.map { char -> char.digitToInt() } } heights = mk.ndarray(map) } override fun config() { lowPoints = findLowPoints() } private fun findLowPoints(): List<Vector2i> { val lowPoints = mutableListOf<Vector2i>() for (x in 0..<heights.shape[1]) { for (y in 0..<heights.shape[0]) { val pos = Vector2i(x, y) val neighborHeights = heights.neighborPositions(pos).map { heights[it] } if (neighborHeights.all { heights[pos] < it }) { lowPoints.add(pos) } } } return lowPoints } override fun compute(): Int { return lowPoints.sumOf { heights[it] + 1 } } override fun getExampleAnswer(): Int { return 15 } } class Part9B : Part9A() { override fun compute(): Int { val basinSizes = lowPoints.map { getBasinSize(it) }.sorted() return basinSizes.takeLast(3).reduce { acc, int -> acc * int } } private fun getBasinSize(pos: Vector2i): Int { val traversal = BreadthFirst(this::nextEdges) return traversal.startFrom(pos).toSet().size } private fun nextEdges(pos: Vector2i, traversal: BreadthFirst<Vector2i>): Iterable<Vector2i> { return heights.neighborPositions(pos) .filter { heights[it] < 9 } .filter { heights[pos] < heights[it] } .toList() } override fun getExampleAnswer(): Int { return 1134 } } fun main() { Day(2021, 9, Part9A(), Part9B()) }
0
Kotlin
0
0
69a0748ed640cf80301d8d93f25fb23cc367819c
2,022
advent-of-code-kotlin
MIT License
src/main/kotlin/ru/glukhov/aoc/Day3.kt
cobaku
576,736,856
false
{"Kotlin": 25268}
package ru.glukhov.aoc import java.io.BufferedReader import java.util.* fun main() { Problem.forDay("day3").use { solveFirst(it) }.let { println("Result of the first problem is $it") } Problem.forDay("day3").use { solveSecond(it) }.let { println("Result of the second problem is $it") } } private fun solveFirst(input: BufferedReader): Int { var result = 0 val checker = BitSet(127) input.lines().forEach { checker.clear() val (first, second) = it.splitByHalf() first.chars().forEach { char -> checker.set(char) } for (char in second.chars()) { if (checker[char]) { result += char.weight() break } } } return result } private fun solveSecond(input: BufferedReader): Int { val checker = MutableList(127) { 0 } var groupSize = 0 var result = 0 for (line in input.lines()) { line.toSet().forEach { checker[it.code]++ } groupSize++ if (groupSize == 3) { result += checker.indexOf(3).weight() checker.fill(0) groupSize = 0 } } return result } private fun String.splitByHalf(): Pair<String, String> = Pair(substring(0, length / 2), substring(length / 2, length)) private fun Int.weight(): Int { if (this in 65..90) { return this - 38 } if (this in 97..122) { return this - 96 } throw IllegalArgumentException("Get back! We a fooled!") }
0
Kotlin
0
0
a40975c1852db83a193c173067aba36b6fe11e7b
1,489
aoc2022
MIT License
src/Day03.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
private val Char.priority: Int get() = if (isLowerCase()) { minus('a') + 1 } else { minus('A') + 27 } fun <T> Iterable<Set<T>>.intersection(): Set<T> = reduceOrNull { acc, ts -> acc.intersect(ts) } ?: emptySet() fun <T> Iterable<Set<T>>.union(): Set<T> = reduceOrNull { acc, ts -> acc.union(ts) } ?: emptySet() fun main() { val rucksacks = readInput("Day03") println( rucksacks.sumOf { val (first, second) = it.chunked(it.length / 2, CharSequence::toSet) first.intersect(second).single().priority } ) println( rucksacks .map(String::toSet) .chunked(3) { it.intersection() } .sumOf { it.single().priority } ) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
755
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/sherepenko/leetcode/solutions/LengthOfLongestUniqueSubstring.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution import kotlin.math.max class LengthOfLongestUniqueSubstring( private val str: String ) : Solution { companion object { fun lengthOfLongestSubstring(str: String): Int { val indices = mutableMapOf<Char, Int>() var start = 0 var length = 0 for ((end, value) in str.withIndex()) { start = max(start, indices.getOrDefault(value, 0)) length = max(length, end - start + 1) indices[value] = end + 1 } return length } fun lengthOfLongestSubstringBf(str: String): Int { var length = 0 for (i in str.indices) { for (j in (i + 1)..str.length) { if (str.unique(i, j)) { length = max(length, j - i) } } } return length } private fun String.unique(start: Int, end: Int): Boolean { val set = mutableSetOf<Char>() for (i in start until end) { if (set.contains(this[i])) { return false } set.add(this[i]) } return true } } override fun resolve() { val result = lengthOfLongestSubstring(str) println( "Length of Longest Substring: \n" + " Input: $str; \n" + " Result: $result \n" ) } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
1,583
leetcode
The Unlicense
src/main/kotlin/ru/byprogminer/compmath/lab5/math/AdamsMethod.kt
ProgMiner
242,443,008
false
null
package ru.byprogminer.compmath.lab5.math import ru.byprogminer.compmath.lab4.expression.Expression import kotlin.math.min object AdamsMethod: OrderedCauchyProblemMethod(4) { override fun solve( function: Expression, startX: Double, startY: Double, step: Double, stepsCount: Int, variableX: String, variableY: String ): Map<Double, Double> { val firstStepsCount = min(3, stepsCount) val firstValues = RungeKuttaMethod.solve( function, startX, startY, step, firstStepsCount, variableX, variableY ).toSortedMap( (if (step >= 0) { Comparator.naturalOrder<Double>() } else { Comparator.reverseOrder() }) as Comparator<Double> ).toList() val points = Array(stepsCount + 1) { i -> firstValues.getOrElse(i) { (startX + i * step) to .0 } } if (stepsCount > firstStepsCount) { val f = { x: Double, y: Double -> -function.evaluate(mapOf(variableX to x, variableY to y)) } val values = Array(stepsCount + 1) { i -> when (i < 4) { true -> f(points[i].first, points[i].second) else -> .0 } } for (i in 4..stepsCount) { val fi = values[i - 1] val fi1 = values[i - 2] val fi2 = values[i - 3] val fi3 = values[i - 4] val d1 = fi - fi1 val d2 = fi - 2 * fi1 + fi2 val d3 = fi - 3 * fi1 + 3 * fi2 - fi3 val point = points[i].copy(second = points[i - 1].second + step * (fi + step * (d1 / 2 + step * (5 * d2 / 12 + step * 3 * d3 / 8)))) points[i] = point values[i] = f(point.first, point.second) } } return points.toMap() } }
0
Kotlin
0
1
201b562e7e07961c695ed4d09ad0b381281f6d10
2,093
Lab_CompMath
MIT License
src/main/kotlin/SubarraySumEqualsK.kt
Codextor
453,514,033
false
{"Kotlin": 26975}
/** * Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. * * A subarray is a contiguous non-empty sequence of elements within an array. * * * * Example 1: * * Input: nums = [1,1,1], k = 2 * Output: 2 * Example 2: * * Input: nums = [1,2,3], k = 3 * Output: 2 * * * Constraints: * * 1 <= nums.length <= 2 * 10^4 * -1000 <= nums[i] <= 1000 * -10^7 <= k <= 10^7 */ fun subarraySum(nums: IntArray, k: Int): Int { val prefixSumCount = mutableMapOf<Int, Int>() prefixSumCount[0] = 1 var currentPrefixSum = 0 var subarraysWithSumK = 0 for (number in nums) { currentPrefixSum += number val complement = currentPrefixSum - k subarraysWithSumK += prefixSumCount.getOrDefault(complement, 0) prefixSumCount[currentPrefixSum] = prefixSumCount.getOrDefault(currentPrefixSum, 0) + 1 } return subarraysWithSumK }
0
Kotlin
1
0
68b75a7ef8338c805824dfc24d666ac204c5931f
937
kotlin-codes
Apache License 2.0
kotlin/src/katas/kotlin/longest_subsequence/LongestSubsequence0.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.longest_subsequence import nonstdlib.printed import datsok.shouldEqual import org.junit.Test import kotlin.random.Random class LongestSubsequence0 { @Test fun `longest subsequence of two strings`() { longestSubsequence("", "") shouldEqual "" longestSubsequence("a", "") shouldEqual "" longestSubsequence("", "a") shouldEqual "" longestSubsequence("a", "a") shouldEqual "a" longestSubsequence("abc", "abc") shouldEqual "abc" longestSubsequence("abc", "_abc") shouldEqual "abc" longestSubsequence("abc", "__abc") shouldEqual "abc" longestSubsequence("abc", "abc_") shouldEqual "abc" longestSubsequence("abc", "abc__") shouldEqual "abc" longestSubsequence("abc", "_abc_") shouldEqual "abc" longestSubsequence("abc", "a_bc") shouldEqual "abc" longestSubsequence("abc", "ab_c") shouldEqual "abc" longestSubsequence("abc", "a_b_c") shouldEqual "abc" longestSubsequence("abc", "_a_b_c") shouldEqual "abc" longestSubsequence("abc", "_a_b_c_") shouldEqual "abc" longestSubsequence("_a_b_c_", "abc") shouldEqual "abc" longestSubsequence("_a_b_c_", "-a-b-c-") shouldEqual "abc" longestSubsequence("_a_a_a_", "-a-a-a-") shouldEqual "aaa" longestSubsequence("abcde", "ab__cd__cde") shouldEqual "abcde" val s1 = Random.nextInt().toString().padStart(20, '_').printed() val s2 = Random.nextInt().toString().padStart(20, '_').printed() val mixed = s1.zip(s2).joinToString("") { it.first.toString() + it.second}.printed() longestSubsequence(s1, mixed) shouldEqual s1 longestSubsequence(s2, mixed) shouldEqual s2 } private fun longestSubsequence(s1: String, s2: String): String { if (s1.isEmpty() || s2.isEmpty()) return "" val c = s1.first() val i = s2.indexOf(c) return if (i == -1) longestSubsequence(s1.drop(1), s2) else c.toString() + longestSubsequence(s1.drop(1), s2.drop(i + 1)) } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,049
katas
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/WiggleSubsequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max fun interface WiggleSubsequence { operator fun invoke(nums: IntArray): Int } /** * Brute Force * Time complexity : O(n!). * Space complexity : O(n). */ class WSBruteForce : WiggleSubsequence { override operator fun invoke(nums: IntArray): Int { val n = nums.size return if (n < 2) n else 1 + max(calculate(nums, 0, true), calculate(nums, 0, false)) } private fun calculate(nums: IntArray, index: Int, isUp: Boolean): Int { var maxCount = 0 for (i in index + 1 until nums.size) { if (isUp.and(nums[i] > nums[index]).or(isUp.not().and(nums[i] < nums[index]))) { maxCount = max(maxCount, 1 + calculate(nums, i, isUp.not())) } } return maxCount } } /** * Dynamic Programming * Time complexity : O(n^2). * Space complexity : O(n). */ class WSDP : WiggleSubsequence { override operator fun invoke(nums: IntArray): Int { val n = nums.size if (n < 2) return n val up = IntArray(n) val down = IntArray(n) for (i in 1 until n) { for (j in 0 until i) { if (nums[i] > nums[j]) { up[i] = max(up[i], down[j] + 1) } else if (nums[i] < nums[j]) { down[i] = max(down[i], up[j] + 1) } } } return 1 + max(down[n - 1], up[n - 1]) } } /** * Linear Dynamic Programming * Time complexity : O(n). * Space complexity : O(n). */ class WSLinearDP : WiggleSubsequence { override operator fun invoke(nums: IntArray): Int { val n = nums.size if (n < 2) return n val up = IntArray(n) val down = IntArray(n) up[0] = 1.also { down[0] = it } for (i in 1 until n) { when { nums[i] > nums[i - 1] -> { up[i] = down[i - 1] + 1 down[i] = down[i - 1] } nums[i] < nums[i - 1] -> { down[i] = up[i - 1] + 1 up[i] = up[i - 1] } else -> { down[i] = down[i - 1] up[i] = up[i - 1] } } } return max(down[n - 1], up[n - 1]) } } /** * Space-Optimized Dynamic Programming * Time complexity : O(n). * Space complexity : O(1). */ class WSSpaceOptimizedDP : WiggleSubsequence { override operator fun invoke(nums: IntArray): Int { val n = nums.size if (n < 2) return n var up = 1 var down = 1 for (i in 1 until n) { if (nums[i] > nums[i - 1]) { up = down + 1 } else if (nums[i] < nums[i - 1]) { down = up + 1 } } return max(down, up) } } /** * Greedy Approach * Time complexity : O(n). * Space complexity : O(1). */ class WSGreedy : WiggleSubsequence { override operator fun invoke(nums: IntArray): Int { val n = nums.size if (n < 2) return n var diffPrev = nums[1] - nums[0] var count = if (diffPrev != 0) 2 else 1 for (i in 2 until n) { val diff = nums[i] - nums[i - 1] if ((diff > 0).and(diffPrev <= 0).or((diff < 0).and(diffPrev >= 0))) { count++ diffPrev = diff } } return count } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,088
kotlab
Apache License 2.0
src/main/kotlin/problems/Day7.kt
PedroDiogo
432,836,814
false
{"Kotlin": 128203}
package problems import kotlin.math.abs class Day7(override val input: String) : Problem { override val number: Int = 7 private val crabPositions = input.split(",").map { i -> i.toInt() } override fun runPartOne(): String { val median = crabPositions.median() return crabPositions.sumOf { position -> abs(position - median) } .toString() } private fun List<Int>.median(): Int { val sorted = this.sorted() return if (this.size % 2 == 1) { sorted[this.size / 2] } else { (sorted[this.size / 2 - 1] + sorted[this.size / 2]) / 2 } } override fun runPartTwo(): String { val average = crabPositions.average() return ((average-1).toInt()..(average+1).toInt()) .map { position -> calculateComplexFuel(crabPositions, position) }.minOf { it } .toString() } private fun calculateComplexFuel(positions: List<Int>, toPosition: Int): Int { return positions.sumOf { position -> val distance = abs(position - toPosition) // Partial sum - 1+2+3+...+distance distance * (distance + 1) / 2 } } }
0
Kotlin
0
0
93363faee195d5ef90344a4fb74646d2d26176de
1,198
AdventOfCode2021
MIT License
src/main/kotlin/juuxel/advent/Day2.kt
Juuxel
226,936,488
false
{"Kotlin": 2545}
package juuxel.advent import java.nio.file.Files import java.nio.file.Paths fun main() { val input = Files.readAllLines(Paths.get("day2.txt")).joinToString(separator = "") val mem = input.split(',').map { it.toInt() }.toIntArray() part1(mem.copyOf()) part2(mem) // Part 2 is mem-safe } private fun part1(mem: IntArray) { println( "Part 1: " + run(mem, noun = 12, verb = 2) ) } private fun part2(mem: IntArray) { for (noun in mem.indices) { for (verb in mem.indices) { val result = run(mem.copyOf(), noun, verb) if (result == 19690720) { println("Part 2: ${100 * noun + verb}") break } } } } private fun run(mem: IntArray, noun: Int, verb: Int): Int { val reader = MemReader(mem) mem[1] = noun mem[2] = verb while (true) { reader.nextOpcode().run(mem) ?: return mem[0] } } private class MemReader(private val mem: IntArray) { private var pos: Int = 0 fun nextOpcode(): Intcode { val result = when (val opcode = mem[pos]) { 1 -> Intcode.Add(mem[pos + 1], mem[pos + 2], mem[pos + 3]) 2 -> Intcode.Multiply(mem[pos + 1], mem[pos + 2], mem[pos + 3]) 99 -> Intcode.Halt else -> Intcode.Unknown(opcode) } pos += 4 return result } } private sealed class Intcode { data class Add(val a: Int, val b: Int, val out: Int) : Intcode() data class Multiply(val a: Int, val b: Int, val out: Int) : Intcode() object Halt : Intcode() data class Unknown(val opcode: Int) : Intcode() fun run(mem: IntArray): Unit? = when (this) { is Add -> mem[out] = mem[a] + mem[b] is Multiply -> mem[out] = mem[a] * mem[b] else -> null } }
0
Kotlin
0
0
3e9d21801346af2c79e3f28718101c4b6aeb3bfc
1,833
Advent2019
MIT License
src/day10/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day10 import day10.Op.AddX import day10.Op.Noop import readInput fun main() { fun part1(input: List<String>): Int { val summarizer = SignalStrengthSummarizer() Cpu.execute(input, summarizer::update) return summarizer.getSum() } fun part2(input: List<String>): Int { val crt = Crt() Cpu.execute(input, crt::update) crt.printScreen(::println) return -1 } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) } class SignalStrengthSummarizer { private val strengths = mutableMapOf<Int, Int>() fun update(cycle: Int, x: Int) { val level = getStrengthLevel(cycle) if (cycle == level) { strengths[level] = x } } fun getSum(): Int { return strengths.entries.sumOf { (l, x) -> l.times(x) } } private fun getStrengthLevel(cycle: Int): Int { return when (cycle) { in 0..20 -> 20 in 20..60 -> 60 in 60..100 -> 100 in 100..140 -> 140 in 140..180 -> 180 in 180..220 -> 220 else -> 0 } } } class Crt { private val crt = mutableListOf<MutableList<Char>>() fun update(cycle: Int, x: Int) { val line = getCrtLine(cycle) crt.init(line).apply { val idx = maxOf((cycle - 1) % 40, 0) if (idx in (x - 1..x + 1)) add('#') else add('.') } } fun printScreen(print: (String) -> Unit) { print(crt.joinToString(System.lineSeparator()) { it.joinToString("") }) } private fun MutableList<MutableList<Char>>.init(line: Int): MutableList<Char> { if (size <= line) { val lineChars = mutableListOf<Char>() add(lineChars) return lineChars } return get(line) } private fun getCrtLine(cycle: Int): Int { return when (cycle) { in 1..40 -> 0 in 41..80 -> 1 in 81..120 -> 2 in 121..160 -> 3 in 161..200 -> 4 in 201..240 -> 5 else -> -1 } } } data class Cpu( private var x: Int = 1, private var cycle: Int = 1, private var cycles: Int = cycle, private var strength: Int = 1, val onCycle: (Int, Int) -> Unit ) { private val executing: ArrayDeque<Op> = ArrayDeque() private val isRunning get() = cycle >= 0 fun run() { while (isRunning) execute() } fun schedule(op: Op): Cpu { executing.add(op) return this } private fun execute() { onCycle(cycles, x) when (val op = executing.firstOrNull() ?: return) { is AddX -> execute(op) { x += op.x } Noop -> execute(op) } when { executing.isEmpty() -> cycle = -1 else -> nextCycle() } } private fun nextCycle() { cycle++ cycles++ } private fun execute(op: Op, onRun: () -> Unit = {}) { if (cycle >= op.cycles) { cycle = 0 executing.removeFirst() onRun() } } companion object { fun execute(input: List<String>, onCycle: (Int, Int) -> Unit) { input .toOps() .fold(Cpu(onCycle = onCycle), Cpu::schedule) .run() } } } sealed class Op(val cycles: Int) { object Noop : Op(1) data class AddX(val x: Int) : Op(2) } fun String.toOp() = when { startsWith("noop") -> Noop else -> AddX(substringAfter(" ").toInt()) } fun List<String>.toOps(): List<Op> { return map(String::toOp) }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
3,715
AoC-2022
Apache License 2.0
jeorg-kotlin-algorithms/jeorg-kotlin-alg-1-hannoi-towers/src/main/kotlin/org/jesperancinha/algorithms/HanoiStarter.kt
jesperancinha
354,756,418
false
{"Kotlin": 35444, "Java": 14401, "JavaScript": 10140, "Python": 4018, "Makefile": 1258, "Shell": 89}
package org.jesperancinha.algorithms import org.jesperancinha.algorithms.data.PyramidElement fun main(args: Array<String>) { val startPositions = intArrayOf(1, 1, 1) val firstNode = PyramidElement(startPositions) calculateStartTriangle(firstNode) println("This is how you move the plates in an Hanoi Tower"); var startNode = firstNode println(startNode.positions.contentToString()) val destination = intArrayOf(3, 3, 3) while (startNode.connections.size != 0 && !startNode.positions.contentEquals(destination)) { var i = startNode.connections.size - 1 while (startNode.connections[i].connections.size == 0) { if (i > 0) { i-- } } startNode = startNode.connections[i] println(startNode.positions.contentToString()) } } fun calculateStartTriangle(firstNode: PyramidElement) { val nodeMap = mutableMapOf<String, PyramidElement>() calculateTriangle(firstNode, null, nodeMap) println(firstNode) } fun calculateTriangle( firstNode: PyramidElement, ignorePositions: IntArray?, nodeMap: MutableMap<String, PyramidElement> ) { for (i in 0..2) { val calculatePiramidMoves = calculatePiramidMoves(firstNode.positions, ignorePositions, i) firstNode.connections.addAll(calculatePiramidMoves) } nodeMap[firstNode.positions.contentToString()] = firstNode if (firstNode.connections.size > 0) { firstNode.connections.forEach { if (nodeMap[it.positions.contentToString()] == null) { calculateTriangle(it, firstNode.positions, HashMap(nodeMap)) } } } } fun calculatePiramidMoves(positions: IntArray, ignorePositions: IntArray?, i: Int): List<PyramidElement> { val calcList = mutableListOf<PyramidElement>() val canMove: Boolean = canMove(positions, i) if (canMove) { if (i == 0) { for (j in 0..positions.size - 1) { if (j + 1 != positions[0]) { val newPositions = positions.clone() newPositions[0] = j + 1 if (ignorePositions == null || !ignorePositions.contentEquals(newPositions)) { calcList.add(PyramidElement(newPositions)) } } } } if (i == 1) { for (j in 0..positions.size - 1) { if (j + 1 != positions[0] && j + 1 != positions[1]) { val newPositions = positions.clone() newPositions[1] = j + 1 if (ignorePositions == null || !ignorePositions.contentEquals(newPositions)) { calcList.add(PyramidElement(newPositions)) } } } } if (i == 2) { for (j in 0..positions.size - 1) { if (positions.indexOf(j + 1) == -1) { val newPositions = positions.clone() newPositions[2] = j + 1 if (ignorePositions == null || !ignorePositions.contentEquals(newPositions)) { calcList.add(PyramidElement(newPositions)) } } } } } return calcList } fun canMove(positions: IntArray, i: Int): Boolean { if (i == 0) { return true; } for (j in 0 until i) { if (positions[j] == positions[i]) { return false } } return true }
1
Kotlin
0
1
7a382ed529ebdc53cc025671a453c7bd5699539e
3,531
jeorg-algorithms-test-drives
Apache License 2.0
src/Day03.kt
raneric
573,109,642
false
{"Kotlin": 13043}
fun main() { fun part1(input: List<String>): Int { return input.map { it.splitAndCheckRec() }.flatten().sum() } fun part2(input: List<String>): Int { return input.findBadgeSum() } val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun String.splitAndCheckRec(): List<Int> { return this.toCharArray().take(this.length / 2).filter { this.toCharArray().takeLast(this.length / 2).contains(it) }.toSet().map { it.convertAsciiCOde() } } fun List<String>.findBadgeSum(): Int { return this.asSequence().chunked(3).map { groupArray -> groupArray[0].filter { groupArray[1].contains(it) && groupArray[2].contains(it) }.toSet() }.flatten().map { it.convertAsciiCOde() }.sum() } fun Char.convertAsciiCOde(): Int { return this.code - if (this.isLowerCase()) 96 else 38 }
0
Kotlin
0
0
9558d561b67b5df77c725bba7e0b33652c802d41
911
aoc-kotlin-challenge
Apache License 2.0
src/main/kotlin/org/jetbrains/bio/util/BinaryLut.kt
JetBrains-Research
173,494,429
false
{"Kotlin": 1220056}
package org.jetbrains.bio.util import java.util.* /** * A lookup table reducing the search space for binary search * over a sorted array of non-negative integers. * * See https://geidav.wordpress.com/2013/12/29/optimizing-binary-search. * * @author <NAME> */ open class BinaryLut( private val index: IntArray, /** The number of bits to use for LUT indexing. */ private val bits: Int, /** * The last LUT boundary. Keys larger than this should * have the `toIndex` equal to the total number of * elements indexed. */ private val end: Int ) { open fun binarySearch(data: IntArray, key: Int): Int { if (key < 0) return -1 // a negative key is strictly less than any data element val idx = key ushr Integer.SIZE - bits val from = index[idx] val to = if (idx + 1 > end) data.size else index[idx + 1] return Arrays.binarySearch(data, from, to, key) } /** * Returns an element having minimal distance to "key", or -1 when "data" is empty. * If there are several such elements, an arbitrary one is returned. */ fun nearestElemIdx(data: IntArray, key: Int): Int { val i = binarySearch(data, key) if (i >= 0) { return i } val idx = i.inv() return when (idx) { data.size -> idx - 1 0 -> idx else -> if (key - data[idx - 1] <= data[idx] - key) idx - 1 else idx } } /** * Returns an inclusive range of indices of elements having minimal distance to "key", * or (-1,-1) when "data" is empty. There are two reasons for this range being non-singular: * 1. equidistant elements, e.g. searching for an element nearest to 2 in an array {0, 1, 3, 4} will return (1,2) * 2. multiple elements, e.g. searching for an element nearest to 2 in an array {0, 2, 2, 4} will return (1,2) * We expect to have a few of these cases, so after we find a match the linear search is implemented. */ fun nearestElemDist(data: IntArray, key: Int): Pair<Int, Int> { val idx = nearestElemIdx(data, key) if (idx == -1) return Pair(-1, -1) val dist = Math.abs(data[idx] - key) val lowVal = key - dist val highVal = key + dist val low = run { var i = idx while (i > 0 && (data[i - 1] == lowVal || data[i - 1] == highVal)) { i-- } i } val high = run { var i = idx while (i < data.size - 1 && (data[i + 1] == lowVal || data[i + 1] == highVal)) { i++ } i } return Pair(low, high) } /** * Returns an inclusive range of indices of elements framing "key" both on the left and on the right side, * or (-1,-1) when "data" is empty. There can be multiple framing elements on each side, since they can be equal. * Also, the exact matches are included in the answer, but aren't counted as framing * (so even when "key" is present in "data", we look to the sides all the same). */ fun nearestElemLR(data: IntArray, key: Int): Pair<Int, Int> { if (data.isEmpty()) return -1 to -1 val idx = binarySearch(data, key) var low: Int var high: Int if (idx >= 0) { low = run { var i = idx - 1 while (i >= 0 && data[i] == key) { i-- } i } high = run { var i = idx + 1 while (i < data.size && data[i] == key) { i++ } i } } else { low = idx.inv() - 1 high = idx.inv() } if (low < 0) { low = 0 } else { while (low > 0 && data[low] == data[low - 1]) { low-- } } if (high == data.size) { high = data.size - 1 } else { while (high < data.size - 1 && data[high] == data[high + 1]) { high++ } } return low to high } /** * Returns an inclusive range of indices of elements framing "key" both on the left and on the right side * and matching the predicate, or (-1,-1) when no elements match the predicate. * There can be multiple framing elements on each side, since they can be equal. * If an exact match (also matching the predicate) is present, the resulting range will contain only exact matches. * The resulting range can contain some elements not matching the predicate. */ fun framingElem(data: IntArray, key: Int, predicate: (Int) -> Boolean): List<Int> { val idx = binarySearch(data, key) val left = run { var i = if (idx >= 0) idx else idx.inv() - 1 while (i >= 0 && !predicate(i)) { i-- } i } val right = run { var i = if (idx >= 0) idx else idx.inv() while (i < data.size && !predicate(i)) { i++ } i } if (left == -1 && right == data.size) return emptyList() var low: Int var high: Int if (left >= 0) { low = left val leftVal = data[left] var i = left - 1 while (i >= 0 && data[i] == leftVal) { if (predicate(i)) low = i i-- } } else { low = right } if (right != data.size) { high = right val rightVal = data[right] var i = right + 1 while (i < data.size && data[i] == rightVal) { if (predicate(i)) high = i i++ } } else { high = left } return (low..high).filter(predicate) } /** * Returns an inclusive range of indices of elements that are at a given distance or less from "key" * both on the left and on the right side, or (-1,-1) when there are no such elements. */ fun elemWithinDist(data: IntArray, key: Int, left: Int, right: Int = left): Pair<Int, Int> { if (data.isEmpty()) return -1 to -1 val idxLeft = binarySearch(data, key - left) val idxRight = binarySearch(data, key + right) val low = run { var i = if (idxLeft >= 0) idxLeft else idxLeft.inv() while (i > 0 && data[i - 1] == key - left) { i-- } i } val high = run { var i = if (idxRight >= 0) idxRight else idxRight.inv() - 1 while (i < data.size - 1 && data[i + 1] == key + right) { i++ } i } return if (low <= high) { low to high } else { -1 to -1 } } companion object { fun of(data: IntArray, bits: Int): BinaryLut { require(bits < Integer.SIZE) { "bits must be <${Integer.SIZE}" } if (data.isEmpty()) { return EmptyBinaryLut(bits) } // Invariant: index[key(x)] = i, s.t. data[i] <= x val index = IntArray((1 shl bits) + 1) var bound = 0 var ptr = 0 for (i in data.indices) { val nextBound = data[i] ushr Integer.SIZE - bits index[bound] = ptr if (nextBound > bound) { ptr = i index.fill(ptr, bound + 1, nextBound) } bound = nextBound } index.fill(ptr, bound, index.size) return BinaryLut(index, bits, bound) } } } private class EmptyBinaryLut(bits: Int) : BinaryLut(IntArray(0), bits, 0) { override fun binarySearch(data: IntArray, key: Int) = -1 }
2
Kotlin
3
30
3f806c069e127430b91712a003e552490bff0820
7,990
bioinf-commons
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/Nqueens.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 /** * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens * attack each other. * Given an integer n, return all distinct solutions to the n-queens puzzle. * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a * queen and an empty space respectively. */ fun Int.solveNQueens(): List<List<String>> { val chess = Array(this) { CharArray(this) } for (i in 0 until this) { for (j in 0 until this) { chess[i][j] = '.' } } val res: MutableList<List<String>> = ArrayList() solve(res, chess, 0) return res } @Throws(IllegalStateException::class) fun Array<out Pair<Int, Char>>.assertLocations(size: Int, abc: CharArray) { if (this.isEmpty()) return if (!this.map { it.first }.none { it > size }) { throw IllegalStateException("Column cannot be more that $size x $size board") } if (this.map { it.second }.none { abc.contains(it) }) { throw IllegalStateException( "Wrong row - should be one of this: ${abc.toList().joinToString()}", ) } } private const val BOARD_MAX_SIZE = 8 /** * Max 8x8. */ fun Int.genBoard(vararg locations: Pair<Int, Char>): String { if (this > BOARD_MAX_SIZE) throw IllegalStateException("Board size cannot be more than 8x8") val abc = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') val empty = "|_|" val filled = "|#|" val unique = locations.toSet().toTypedArray() unique.assertLocations(this, abc) val trueLocations = unique.map { it.first - 1 to abc.indexOf(it.second.lowercaseChar()) } val board = Array(this) { IntArray(this) { 0 } } for (loc in trueLocations) { board.reversedArray()[loc.first][loc.second] = 1 } val sb = StringBuilder() for (i in board.reversedArray().indices) { sb.append("${this - i} ") for (b in board[i]) { if (b == 0) sb.append(empty) else sb.append(filled) } sb.append("\n") } for (j in 0 until this) { sb.append(" ${abc[j]}") } sb.append("\n") return sb.toString() } private fun solve( res: MutableList<List<String>>, chess: Array<CharArray>, row: Int, ) { if (row == chess.size) { res.add(construct(chess)) return } for (col in chess.indices) { if (valid(chess, row, col)) { chess[row][col] = 'Q' solve(res, chess, row + 1) chess[row][col] = '.' } } } private fun valid(chess: Array<CharArray>, row: Int, col: Int): Boolean { for (i in 0 until row) { if (chess[i][col] == 'Q') { return false } } run { var i = row - 1 var j = col + 1 while (i >= 0 && j < chess.size) { if (chess[i][j] == 'Q') { return false } i-- j++ } } var i = row - 1 var j = col - 1 while (i >= 0 && j >= 0) { if (chess[i][j] == 'Q') { return false } i-- j-- } return true } private fun construct(chess: Array<CharArray>): List<String> { val path: MutableList<String> = ArrayList() for (chars in chess) { path.add(String(chars)) } return path }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,012
kotlab
Apache License 2.0
src/day11/Day11.kt
crmitchelmore
576,065,911
false
{"Kotlin": 115199}
package day11 import helpers.ReadFile class Day11 { val lines = ReadFile.named("src/day11/input.txt", blocks = "\n\n").map { it.split("\n") } val lines1 = listOf( listOf("Monkey 0:", "Starting items: 79, 98", "Operation: new = old * 19", "Test: divisible by 23", "If true: throw to monkey 2", "If false: throw to monkey 3", ),listOf( "Monkey 1:", "Starting items: 54, 65, 75, 74", "Operation: new = old + 6", "Test: divisible by 19", "If true: throw to monkey 2", "If false: throw to monkey 0", ),listOf( "Monkey 2:", "Starting items: 79, 60, 97", "Operation: new = old * old", "Test: divisible by 13", "If true: throw to monkey 1", "If false: throw to monkey 3", ),listOf( "Monkey 3:", "Starting items: 74", "Operation: new = old + 3", "Test: divisible by 17", "If true: throw to monkey 0", "If false: throw to monkey 1" )) class Monkey { var times = 0 val name: Int var items: MutableList<Long> var operation: (Long) -> Long val divideBy: Long var test: (Long) -> Int constructor(input: List<String>) { name = input[0].split(" ")[1].dropLast(1).toInt() items = input[1].drop(16).split(", ").map { it.toLong() }.toMutableList() val op = input[2].drop(21).split(" ") divideBy = input[3].drop(19).toLong() val worryLevelFactory: Long = 1 val tr = input[4].split(" ").last().toInt() val fal = input[5].split(" ").last().toInt() operation = when (op[0]) { "+" -> { x -> (x + (op[1].toLongOrNull()?:x))/worryLevelFactory } else -> { x -> (x * (op[1].toLongOrNull()?:x))/worryLevelFactory } // Times } val zero: Long = 0 test = { x -> if (x % divideBy == zero) tr else fal } } } fun result1() : String { val monkeys = lines.map { Monkey(it) } val factor = monkeys.fold(1L) { acc, monkey -> acc * (monkey.divideBy) } val rounds = 10000 for (i in 1..rounds) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newItem = monkey.operation(item) val target = monkey.test(newItem) monkeys[target].items.add(newItem % factor) monkey.times++ } monkey.items = mutableListOf() } if (i == 1 || i == 20 || i == 1000 || i == 10000) { println(monkeys.map { it.times }) } } val m = monkeys.sortedBy { it.times }.takeLast(2).map { it.times } return (m[0] * m[1]).toString() } }
0
Kotlin
0
0
fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470
2,800
adventofcode2022
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountOrders.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.MOD /** * 1359. Count All Valid Pickup and Delivery Options * @see <a href="https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options">Source</a> */ fun interface CountOrders { operator fun invoke(n: Int): Int } class CountOrdersBottomUp : CountOrders { override fun invoke(n: Int): Int { var res: Long = 1 for (i in 1..n) { res = res * (i * 2 - 1) * i % MOD } return res.toInt() } } class CountOrdersRecursion : CountOrders { override fun invoke(n: Int): Int { return if (n > 0) (invoke(n - 1).toLong() * (n * 2 - 1) * n % (MOD + 7)).toInt() else 1 } } class CountOrdersFactorial : CountOrders { private val memo: MutableMap<Int, Long> = HashMap() override fun invoke(n: Int): Int { val factorial = factorial(n * 2) return (factorial.shr(n) % MOD).toInt() } private fun factorial(n: Int): Long { if (n <= 1) { return 1L // Base case: factorial of 0 and 1 is 1 } if (memo.containsKey(n)) { return memo.getOrDefault(n, 1) } val result = n.toLong() * factorial(n - 1) memo[n] = result return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,888
kotlab
Apache License 2.0
2021/src/test/kotlin/Day25.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.test.Test import kotlin.test.assertEquals class Day25 { enum class Direction { EAST, SOUTH } data class Coord(val x: Int, val y: Int, val maxX: Int, val maxY: Int) { fun next(direction: Direction) = Coord( if (direction == Direction.EAST) { if (x.inc() < maxX) x.inc() else 0 } else x, if (direction == Direction.SOUTH) { if (y.inc() < maxY) y.inc() else 0 } else y, maxX, maxY ) } @Test fun `run part 01`() { val map = Util.getInputAsListOfString("day25-input.txt") val cucumbers = map .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, it -> when (it) { 'v' -> Coord(x, y, line.length, map.size) to Direction.SOUTH '>' -> Coord(x, y, line.length, map.size) to Direction.EAST else -> null } } } .toMap() val steps = generateSequence(cucumbers) { if (it.count { cucumber -> !it.containsKey(cucumber.key.next(cucumber.value)) } > 0) it .move(Direction.EAST) .move(Direction.SOUTH) else null } .count() assertEquals(429, steps) } private fun Map<Coord, Direction>.move(direction: Direction) = this .map { if (it.value == direction && !this.containsKey(it.key.next(it.value))) it.key.next(it.value) to it.value else it.key to it.value } .toMap() }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
1,727
adventofcode
MIT License
src/main/kotlin/com/leetcode/P187.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://leetcode.com/problems/repeated-dna-sequences/ class P187 { fun findRepeatedDnaSequences(s: String): List<String> { val answer = mutableSetOf<String>() if (s.length <= 10) return listOf() // 해시값들이 들어갈 Set val seen = mutableSetOf<Int>() // 처음 10자리를 해싱한다. var hash = 0 for (i in 0 until 10) { hash = hash.shl(2) + int(s[i]) } // 처음 만들어진 해시를 저장 seen += hash // 나머지 해시값 비교 for (i in 10 until s.length) { // 해시값을 조정한다. hash = hash.and(1.shl(18) - 1) hash = hash.shl(2) + int(s[i]) // Set에 add() 했을 때 false면 이미 값이 있다는 것이다. if (!seen.add(hash)) { answer.add(s.substring(i - 9, i + 1)) } } return answer.toList() } private fun int(ch: Char): Int { return when (ch) { 'A' -> 0 'C' -> 1 'G' -> 2 'T' -> 3 else -> 0 } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,166
algorithm
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FlattenBinaryTree.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack /** * 114. Flatten Binary Tree to Linked List * @see <a href="https://leetcode.com/problems/flatten-binary-tree-to-linked-list/">Source</a> */ fun interface FlattenBinaryTree { fun flatten(root: TreeNode?) } class FlattenRecursion : FlattenBinaryTree { override fun flatten(root: TreeNode?) { flattenTree(root) } private fun flattenTree(node: TreeNode?): TreeNode? { if (node == null) { return null } if (node.left == null && node.right == null) { return node } val leftTail = flattenTree(node.left) val rightTail = flattenTree(node.right) if (leftTail != null) { leftTail.right = node.right node.right = node.left node.left = null } return rightTail ?: leftTail } } class FlattenStack : FlattenBinaryTree { override fun flatten(root: TreeNode?) { if (root == null) { return } val start = 1 val end = 2 var tailNode: TreeNode? = null val stack: Stack<Pair<TreeNode, Int>> = Stack<Pair<TreeNode, Int>>() stack.push(root to start) while (stack.isNotEmpty()) { val nodeData: Pair<TreeNode, Int> = stack.pop() val currentNode: TreeNode = nodeData.first val recursionState: Int = nodeData.second if (currentNode.left == null && currentNode.right == null) { tailNode = currentNode continue } if (recursionState == start) { if (currentNode.left != null) { stack.push(Pair(currentNode, end)) currentNode.left?.let { stack.push(it to start) } } else if (currentNode.right != null) { stack.push(Pair(currentNode.right!!, start)) } } else { var rightNode = currentNode.right if (tailNode != null) { tailNode.right = currentNode.right currentNode.right = currentNode.left currentNode.left = null rightNode = tailNode.right } if (rightNode != null) { stack.push(Pair(rightNode, start)) } } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,072
kotlab
Apache License 2.0
common/inference.kt
waterlink
53,756,002
false
null
package com.tddfellow.inference data class Relation(val name: String, val subject: String, val relative: String) { private fun matcherFor(getter: (Relation) -> String): (Relation) -> Boolean { val value = getter(this) return if (value == "?") { { getter(it) != "?" } } else { { getter(it) == value } } } val extractors: List<(Relation) -> String> = listOf( { it -> it.name }, { it -> it.subject }, { it -> it.relative } ) val matchers = extractors.map { matcherFor(it) } val freeExtractors = extractors.filter { it(this) == "?" } fun match(other: Relation): Boolean { return matchers.all { it(other) } } } val relations = mutableListOf<Relation>() fun _clear() { relations.clear() } fun query(relation: Relation): List<Relation> { if (!relations.contains(relation)) { relations.add(relation) } return relations.filter { relation.match(it) } } fun query(relationString: String): List<Relation> { return query(relationFromString(relationString)) } fun relationFromString(relationString: String): Relation { val found = relations .map { relationString.split(it.name) + listOf(it.name) } .find { it.count() == 3 } return if (found == null) { newRelationFromString(relationString) } else { Relation(found[2], found[0], found[1]) } } fun newRelationFromString(relationString: String): Relation { val components = relationString.split("?") if (components.count() != 3) { throw RuntimeException("New relation should be in format '? <relation name> ?'") } return Relation(components[1], "?", "?") } fun join( left: List<Relation>, leftValue: (Relation) -> String, right: List<Relation>, rightValue: (Relation) -> String): List<String> { return left.flatMap { relation -> right.map { rightValue(it) } .filter { it == leftValue(relation) } }.distinct() } fun join( left: String, leftValue: (Relation) -> String, right: String, rightValue: (Relation) -> String): List<String> { val leftRelation = relationFromString(left) val rightRelation = relationFromString(right) return join( query(leftRelation), leftValue, query(rightRelation), rightValue) } fun join(left: String, right: String): List<String> { val leftRelation = relationFromString(left) if (leftRelation.freeExtractors.count() == 0) { throw RuntimeException("join(left, right): left should have at least one '?' token") } val rightRelation = relationFromString(right) if (rightRelation.freeExtractors.count() == 0) { throw RuntimeException("join(left, right): right should have at least one '?' token") } return join( query(leftRelation), leftRelation.freeExtractors.first(), query(rightRelation), rightRelation.freeExtractors.first() ) }
3
Kotlin
0
0
159f87bf7eb94519933f1348a4dde232ce012db6
3,021
inference
MIT License
Problems/Algorithms/53. Maximum Subarray/MaxSubarray2.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun maxSubArray(nums: IntArray): Int { return maxSum(nums, 0, nums.size-1) } private fun maxSum(nums: IntArray, start: Int, end: Int): Int { if (start == end) return nums[start] val middle: Int = (start + end) / 2 val leftMax: Int = maxSum(nums, start, middle) val rightMax: Int = maxSum(nums, middle+1, end) val crossMax: Int = maxCrossSum(nums, start, middle, end) return maxOf(leftMax, rightMax, crossMax) } private fun maxCrossSum(nums: IntArray, start: Int, middle: Int, end: Int): Int { var leftSum = 0 var leftMax = Int.MIN_VALUE for (i in middle downTo start) { leftSum += nums[i] leftMax = maxOf(leftSum, leftMax) } var rightSum = 0 var rightMax = Int.MIN_VALUE for (i in middle+1..end) { rightSum += nums[i] rightMax = maxOf(rightSum, rightMax) } return leftMax + rightMax } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,060
leet-code
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/arrays/LongestPeak.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.arrays import kotlin.math.max fun main() { val arr = listOf(3, -4, 7, 12, 4, 20, 15, 6, -2, 5, 16, 11, 1) print(longestPeak(arr)) // 5 } // O(n) time | O(1) space private fun longestPeak(arr: List<Int>): Int { var longestPeakLen = 0 var i = 1 while (i < arr.size - 1) { val isPeak = arr[i] > arr[i - 1] && arr[i] > arr[i + 1] if (!isPeak) { i++ continue } var low = i - 2 while (low >= 0 && arr[low] < arr[low + 1]) low-- var high = i + 2 while (high < arr.size && arr[high] < arr[high - 1]) high++ val currPeakLen = high - low - 1 longestPeakLen = max(longestPeakLen, currPeakLen) i = high } return longestPeakLen }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
807
algs4-leprosorium
MIT License
src/Day09.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.Coordinate2D import utils.readInputAsLines import kotlin.math.abs import kotlin.math.sign fun main() { val input = readInputAsLines("day09_input") val moves = input.asSequence() .map { it.substringBefore(' ').single() to it.substringAfter(' ').toInt() } val directions = mapOf( 'U' to Coordinate2D(0, 1), 'D' to Coordinate2D(0, -1), 'L' to Coordinate2D(-1, 0), 'R' to Coordinate2D(1, 0) ) fun countVisitedTailPositions(knotCount: Int): Int { val visited = mutableSetOf<Coordinate2D>() val knots = MutableList(knotCount) { Coordinate2D(x = 0, y = 0) } moves.forEach { (d, r) -> repeat(r) { knots[0] += directions.getValue(d) knots.indices.windowed(2) { (head, tail) -> if (!(knots[tail] isAdjacentTo knots[head])) { knots[tail] = knots[tail] movedTowards knots[head] } } visited.add(knots.last()) } } return visited.size } val result1 = countVisitedTailPositions(2) println(result1) val result2 = countVisitedTailPositions(10) println(result2) } private infix fun Coordinate2D.isAdjacentTo(other: Coordinate2D) = abs(other.x - x) < 2 && abs(other.y - y) < 2 private infix fun Coordinate2D.movedTowards(other: Coordinate2D) = this + Coordinate2D((other.x - x).sign, (other.y - y).sign)
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
1,480
advent-of-code-2022
Apache License 2.0
learning-algorithm/src/main/kotlin/io/vincent/learning/stack/algorithm/leetcode/No206ReverseLinkedList.kt
search-cloud
137,825,867
false
{"Kotlin": 172535, "Java": 154592, "C": 89374, "HTML": 1736, "Python": 502, "Go": 130}
package io.vincent.learning.stack.algorithm.leetcode import io.vincent.learning.stack.algorithm.leetcode.linked.ListNode import org.jetbrains.annotations.Contract /** * Reverse linked List. (Iteratively) * </p> * https://leetcode.com/problems/reverse-linked-list/ * * @author Vincent * @since 1.0, 2019/3/23 */ object No206ReverseLinkedList { /** * Approach #1 (Iterative) * Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3. * * While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end! * * Complexity analysis * * Time complexity : O(n)O(n). Assume that nn is the list's length, the time complexity is O(n)O(n). * * Space complexity : O(1)O(1). */ @Contract("null -> null") fun reverse(head: ListNode?): ListNode? { if (head?.next == null) { return head } // 记录前驱节点, Default null var prev: ListNode? = null // 记录当前节点 var curr = head while (curr != null) { val nextTemp = curr.next curr.next = prev prev = curr curr = nextTemp } return prev } /** * Approach #2 (Recursive) * The recursive version is slightly trickier and the key is to work backwards. Assume that the rest of the list had already been reversed, now how do I reverse the front part? Let's assume the list is: n1 → … → nk-1 → nk → nk+1 → … → nm → Ø * * Assume from node nk+1 to nm had been reversed and you are at node nk. * * n1 → … → nk-1 → nk → nk+1 ← … ← nm * * We want nk+1’s next node to point to nk. * * So, * * nk.next.next = nk; * * Be very careful that n1's next must point to Ø. If you forget about this, your linked list has a cycle in it. This bug could be caught if you test your code with a linked list of size 2. * * Complexity analysis * * Time complexity : O(n)O(n). Assume that nn is the list's length, the time complexity is O(n)O(n). * * Space complexity : O(n)O(n). The extra space comes from implicit stack space due to recursion. The recursion could go up to nn levels deep. */ @Contract("null -> null") fun recursivelyReverse(head: ListNode?): ListNode? { if (head?.next == null) { return head } val result = recursivelyReverse(head.next) head.next?.next = head head.next = null return result } }
0
Kotlin
0
1
5011813d9796c0ccc8a174c98549d5b3727adfb4
2,938
learning-stack
Apache License 2.0
src/main/kotlin/astminer/featureextraction/TreeFeature.kt
neomatrix369
273,848,522
true
{"Java": 199970, "Kotlin": 170672, "ANTLR": 76421, "C++": 25952, "Python": 12730, "JavaScript": 7698, "Shell": 754}
package astminer.featureextraction import astminer.common.model.Node import astminer.common.preOrder /** * Interface that describes tree feature. * @param T tree feature's type */ interface TreeFeature<out T> { /** * Computes this feature for given tree. * @param tree tree for which this feature is computed * @return computed feature */ fun compute(tree: Node) : T } /** * Tree feature for computing depth of a given tree. */ object Depth : TreeFeature<Int> { override fun compute(tree: Node): Int { val max = tree.getChildren().map { compute(it) }.max() ?: 0 return max + 1 } } /** * Tree feature for computing branching factor of a given tree. */ object BranchingFactor : TreeFeature<Double> { override fun compute(tree: Node): Double { if (tree.isLeaf()) { return 0.0 } val isLeafByNodes = tree.preOrder().groupBy { it.isLeaf() } val leavesNumber = isLeafByNodes[true]?.size ?: 0 val branchingNodesNumber = isLeafByNodes[false]?.size ?: 0 val edgesNumber = (branchingNodesNumber + leavesNumber - 1).toDouble() return edgesNumber / branchingNodesNumber } } /** * Tree feature for computing the number of nodes in a given tree. */ object NumberOfNodes : TreeFeature<Int> { override fun compute(tree: Node): Int { return tree.getChildren().map { compute(it) }.sum() + 1 } } /** * Tree feature for computing list of all node tokens from a given tree. */ object Tokens : TreeFeature<List<String>> { override fun compute(tree: Node): List<String> { return findTokens(tree, ArrayList()) } private fun findTokens(node: Node, tokensList: MutableList<String>): List<String> { node.getChildren().forEach { findTokens(it, tokensList) } tokensList.add(node.getToken()) return tokensList } } /** * Tree feature for computing list of all node types from a given tree. */ object NodeTypes : TreeFeature<List<String>> { override fun compute(tree: Node): List<String> { return findNodeTypes(tree, ArrayList()) } private fun findNodeTypes(node: Node, nodeTypesList: MutableList<String>): List<String> { node.getChildren().forEach { findNodeTypes(it, nodeTypesList) } nodeTypesList.add(node.getTypeLabel()) return nodeTypesList } } /** * Tree feature for computing list of all compressible path lengths in a given tree. * A path is called compressible if it consists of consistent nodes that have only one child. */ object CompressiblePathLengths : TreeFeature<List<Int>> { override fun compute(tree: Node): List<Int> { val pathLengths = ArrayList<Int>() tree.preOrder().filter { it.isStartingNode() }.forEach { pathLengths.add(findPathLengthFromStartingNode(it)) } return pathLengths } private fun Node.isStartingNode() : Boolean { return this.hasOneChild() && !(this.getParent()?.hasOneChild() ?: false) } private fun Node.hasOneChild() : Boolean = getChildren().size == 1 private fun findPathLengthFromStartingNode(node: Node) : Int { var length = 1 var next = node.getChildren().first() while (next.hasOneChild()) { length++ next = next.getChildren().first() } return length } }
1
null
1
2
6e53d0245ef4980bf2b46bf3741947b632227d16
3,363
astminer
MIT License
src/main/kotlin/days/day3/Day3.kt
Stenz123
725,707,248
false
{"Kotlin": 123279, "Shell": 862}
package days.day3 import days.Day import java.util.* import kotlin.collections.HashMap import kotlin.collections.HashSet class Day3: Day(false) { //NOTE: I Didn't impliment the edgecase for the edge. If you just add a padding of '.' it works. override fun partOne(): Any { val input: HashMap<Coordinate, Char> = HashMap() val rawInput = readInput() for (i in rawInput.indices) { for (j in rawInput[i].indices) { input[Coordinate(i, j)] = rawInput[i][j] } } val digits = input.filter { it.value.isDigit() } var numberCoordinates :HashSet<HashSet<Coordinate>> = hashSetOf() for (digit in digits) { numberCoordinates.add(findConnectedNumbers(input, digit.key)) } val validNumberCOordinates = numberCoordinates.filter {coordinateList -> coordinateList.any { coordinate -> coordinate.getNeighbours().any { neighbour -> input.containsKey(neighbour) && input[neighbour]!! != '.' && !input[neighbour]!!.isDigit() } } } var result = 0 for (i in rawInput.indices) { var stringBuilder = StringBuilder() for (j in rawInput[i].indices) { if (validNumberCOordinates.flatten().contains(Coordinate(i, j))) { stringBuilder.append(input[Coordinate(i, j)]) print(input[Coordinate(i, j)]) } else { val string = stringBuilder.toString() if (string.isNotEmpty()) { result+= string.toInt() println() } stringBuilder = StringBuilder() } } println() } return result } fun findConnectedNumbers(input: HashMap<Coordinate, Char>, currentCoordinate: Coordinate): HashSet<Coordinate> { var neighbours = currentCoordinate.getNeighboursLeftRight().filter{neighbour -> input.containsKey(neighbour) && input[neighbour]!!.isDigit()}.toHashSet() var neighboursCache = HashSet<Coordinate>() neighbours.forEach{ neighbour -> val newNeighbours = neighbour.getNeighbours().filter { newNeighbour -> input.containsKey(newNeighbour) && input[newNeighbour]!!.isDigit() } neighboursCache.addAll(newNeighbours) } for(i in 0..100) { neighbours.addAll(neighboursCache) neighbours.forEach{ neighbour -> val newNeighbours = neighbour.getNeighbours().filter { newNeighbour -> input.containsKey(newNeighbour) && input[newNeighbour]!!.isDigit() } neighboursCache.addAll(newNeighbours) } } return neighbours } override fun partTwo(): Any { val input: HashMap<Coordinate, Char> = HashMap() val rawInput = readInput() for (i in rawInput.indices) { for (j in rawInput[i].indices) { input[Coordinate(i, j)] = rawInput[i][j] } } val digits = input.filter { it.value.isDigit() } val numberCoordinates :HashSet<HashSet<Coordinate>> = hashSetOf() for (digit in digits) { numberCoordinates.add(findConnectedNumbers(input, digit.key)) } val validNumberCOordinates = numberCoordinates.filter {coordinateList -> coordinateList.any { coordinate -> coordinate.getNeighbours().any { neighbour -> input.containsKey(neighbour) && input[neighbour]!! == '*' } } } val gears = input.filter { it.value == '*' } var realRes = 1 for (gear in gears) { var numberCount = 0 var result = 1 for (number in validNumberCOordinates) { if(isNextToGear(input, number, gear.key)) { numberCount++ result*= toNumber(input, number) } } if (numberCount == 2) { realRes+= result } } return realRes -1 } fun isNextToGear(input: HashMap<Coordinate, Char>, coordinates: HashSet<Coordinate>, gear: Coordinate): Boolean { return coordinates.any{it.getNeighbours().any { neighbour -> neighbour == gear } }} fun toNumber(input: HashMap<Coordinate, Char>, coordinates: HashSet<Coordinate>): Int { val linkedList = LinkedList<Coordinate>(coordinates) linkedList.sort() val stringBuilder = StringBuilder() for (coordinate in linkedList) { stringBuilder.append(input[coordinate]) } return stringBuilder.toString().toInt() } } class Coordinate(val x: Int, val y: Int):Comparable<Coordinate> { fun getNeighbours(): MutableList<Coordinate> { return mutableListOf( Coordinate(x - 1, y - 1), Coordinate(x - 1, y), Coordinate(x - 1, y + 1), Coordinate(x, y - 1), Coordinate(x, y + 1), Coordinate(x + 1, y - 1), Coordinate(x + 1, y), Coordinate(x + 1, y + 1) ) } fun getNeighboursLeftRight(): MutableList<Coordinate> { return mutableListOf( Coordinate(x, y - 1) ,this , Coordinate(x, y + 1) ) } override fun compareTo(other: Coordinate): Int { if (this.y == other.y) { return this.x.compareTo(other.x) } return this.y.compareTo(other.y) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Coordinate if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } override fun toString(): String { return "Coordinate(x=$x, y=$y)" } }
0
Kotlin
1
0
3de47ec31c5241947d38400d0a4d40c681c197be
6,162
advent-of-code_2023
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[400]第 N 位数字.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...] 中找出并返回第 n 位上的数字。 // // // // // 示例 1: // // //输入:n = 3 //输出:3 // // // 示例 2: // // //输入:n = 11 //输出:0 //解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。 // // // // // 提示: // // // 1 <= n <= 231 - 1 // 第 n 位上的数字是按计数单位(digit)从前往后数的第 n 个数,参见 示例 2 。 // // Related Topics 数学 二分查找 // 👍 267 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findNthDigit(n: Int): Int { var len = 1 var n1 =n while (len * 9 * Math.pow(10.0, len - 1.toDouble()) < n1) { n1 -= ( len * 9 * Math.pow(10.0, len - 1.toDouble())).toInt() len++ } var s = Math.pow(10.0, len - 1.toDouble()).toLong() s += n1 / len - 1 n1 -= len * (n1 / len) return if (n1 == 0) (s % 10).toInt() else ((s + 1) / Math.pow(10.0, (len - n1).toDouble()) % 10).toInt() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,246
MyLeetCode
Apache License 2.0
code/graph/MCMM.kt
hakiobo
397,069,173
false
null
//i make no guarantess about the accuracy of this code private class MCMM(private val d: Int, private val costs: Array<DoubleArray>) { companion object { const val EPSILON = 1E-9 } private val n = 2 + (d shl 1) private val src = n - 1 private val snk = n - 2 private val prices = DoubleArray(n) { 0.0 } private val usedFromSrc = BooleanArray(d) private val usedToSnk = BooleanArray(d) private val used = Array(d) { BooleanArray(d) } init { var low = costs[0][0] for (nfId in 0 until d) { prices[nfId + d] = costs[0][nfId] for (fId in 1 until d) { prices[nfId + d] = min(prices[nfId + d], costs[fId][nfId]) } low = min(low, prices[nfId]) } prices[snk] = low } fun findPath(): Double { val pq = PriorityQueue<Pair<Double, Int>> { a, b -> a.first.compareTo(b.first) } val dists = DoubleArray(n) { Double.MAX_VALUE } val prev = IntArray(n) { -1 } dists[src] = 0.0 pq += 0.0 to src while (pq.isNotEmpty()) { val (cost, node) = pq.poll() if (cost == dists[node]) { when (node) { src -> { for (dest in 0 until d) { if (!usedFromSrc[dest]) { val newCost = cost + prices[node] - prices[dest] if (newCost + EPSILON < dists[dest]) { prev[dest] = node dists[dest] = newCost pq += newCost to dest } } } } snk -> { for (nfId in 0 until d) { val dest = d + nfId if (usedToSnk[nfId]) { val newCost = cost + prices[node] - prices[dest] if (newCost + EPSILON < dists[dest]) { prev[dest] = node dists[dest] = newCost pq += newCost to dest } } } } in 0 until d -> { for (nfId in 0 until d) { val dest = nfId + d if (!used[node][nfId]) { val newCost = cost + prices[node] + costs[node][nfId] - prices[dest] if (newCost + EPSILON < dists[dest]) { prev[dest] = node dists[dest] = newCost pq += newCost to dest } } } } else -> { val nfId = node - d for (dest in 0 until d) { if (used[dest][nfId]) { val newCost = cost + prices[node] - costs[dest][nfId] - prices[dest] if (newCost + EPSILON < dists[dest]) { prev[dest] = node dists[dest] = newCost pq += newCost to dest } } } if (!usedToSnk[nfId]) { val newCost = cost + prices[node] - prices[snk] if (newCost + EPSILON < dists[snk]) { prev[snk] = node dists[snk] = newCost pq += newCost to snk } } } } } } var cost = 0.0 if (dists[snk] == Double.MAX_VALUE) { exitProcess(-4) } else { var cn = snk while (prev[cn] != -1) { val pn = prev[cn] when (pn) { src -> { usedFromSrc[cn] = true } in 0 until d -> { used[pn][cn - d] = true cost += costs[pn][cn - d] } else -> { if (cn == snk) { usedToSnk[pn - d] = true } else { used[cn][pn - d] = false cost -= costs[cn][pn - d] } } } cn = pn } for (x in 0 until n) { prices[x] += dists[x] } return cost } } }
0
Kotlin
1
2
f862cc5e7fb6a81715d6ea8ccf7fb08833a58173
5,103
Kotlinaughts
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-09.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.TspGraph import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "09-input") val test1 = readInputLines(2015, "09-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val graph = readGraph(input) return graph.solveTsp { d1, d2 -> d1 - d2 } } private fun part2(input: List<String>): Int { val graph = readGraph(input) return graph.solveTsp { d1, d2 -> d2 - d1 } } private fun readGraph(input: List<String>): TspGraph { val graph = TspGraph() val regex = """(\w+) to (\w+) = (\d+)""".toRegex() input.forEach { val (from, to, dist) = regex.matchEntire(it)!!.destructured graph.addBidirectionalEdge(from, to, dist.toInt()) } return graph }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,056
advent-of-code
MIT License
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day7HandyHaversacks.kt
Scavi
68,294,098
false
{"Java": 1449516, "Kotlin": 59149}
package com.scavi.brainsqueeze.adventofcode import com.scavi.brainsqueeze.adventofcode.util.GraphAccess import java.lang.IllegalArgumentException class Day7HandyHaversacks { private val bagSplit = """[a-z]*\s[a-z]*(?=\sbag)|((?<=\s)\d+)""".toRegex() fun solveA(input: List<String>): Int { val graph = createGraphAccess(input) return graph.findPossiblePathTo("shiny gold") } fun solveB(input: List<String>): Int { val graph = createGraphAccess(input) return calc(graph, "shiny gold") - 1 } private fun calc(graphAccess: GraphAccess<String>, bagName: String): Int { if (graphAccess.getGraph()[bagName]?.isEmpty() ?: error("Unknown bag: $bagName")) { return 1 } var count = 1 for (nextBag in graphAccess.getGraph()[bagName] ?: error("Unknown bag: $bagName")) { count += nextBag.weight * calc(graphAccess, nextBag.targetNode) } return count } private fun createGraphAccess(input: List<String>): GraphAccess<String> { val graphAccess = GraphAccess<String>() for (rule in input) { val tokens = split(rule) if (tokens.size >= 3) { for (i in 1 until tokens.size step 2) { graphAccess.addEdge(tokens[0], tokens[i + 1], tokens[i].toInt()) } } else { if (tokens.size != 2) { throw IllegalArgumentException("woot?!") } } } return graphAccess } fun split(input: String) = bagSplit.findAll(input).map { it.groupValues[0] }.toList() }
0
Java
0
1
79550cb8ce504295f762e9439e806b1acfa057c9
1,656
BrainSqueeze
Apache License 2.0
src/Day01.kt
alexaldev
573,318,666
false
{"Kotlin": 10807}
fun main() { fun part1(input: List<String>): Int { val caloriesPerElf = mutableListOf<Int>() var elfIndex = 0 input.forEachIndexed { index, s -> if (s == "") { elfIndex += 1 return@forEachIndexed } if (caloriesPerElf.getOrNull(elfIndex) == null) { caloriesPerElf.add(elfIndex, 0) } caloriesPerElf[elfIndex] += s.toInt() } return caloriesPerElf.maxOf { it } } fun part2(input: List<String>): Int { val caloriesPerElf = mutableListOf<Int>() var elfIndex = 0 input.forEachIndexed { index, s -> if (s == "") { elfIndex += 1 return@forEachIndexed } if (caloriesPerElf.getOrNull(elfIndex) == null) { caloriesPerElf.add(elfIndex, 0) } caloriesPerElf[elfIndex] += s.toInt() } return caloriesPerElf.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("In01.txt") print(part2(testInput)) } fun <T> List<T>.indicesOf(predicate: (T) -> Boolean): List<Int> { val result = mutableListOf<Int>() this.forEachIndexed { index, t -> if (predicate(t)) result += index } return result }
0
Kotlin
0
0
5abf10b2947e1c6379d179a48f1bdcc719e7062b
1,406
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/de/huddeldaddel/euler/Problem050.kt
huddeldaddel
171,357,298
false
null
package de.huddeldaddel.euler import de.huddeldaddel.euler.sequences.PrimeSequence import de.huddeldaddel.euler.extensions.isPrime /** * Solution for https://projecteuler.net/problem=50 */ fun main() { val upperLimit = 1_000_000L val primes = getPrimes(upperLimit) var result = listOf<Long>() for(i in 0 until primes.size) { val longestSequence = getLongestSequence(i, primes) if(longestSequence.size > result.size) result = longestSequence } println(result.sum()) } fun getLongestSequence(startIndex: Int, primes: List<Long>): List<Long> { var highestHit = startIndex for(i in startIndex until primes.size) { val sum = primes.subList(startIndex, i).sum() if(sum >= 1_000_000) { break } if(sum.isPrime()) { highestHit = i } } return primes.subList(startIndex, highestHit) } fun getPrimes(upperLimit: Long): List<Long> { val result = mutableListOf<Long>() val primeSequence = PrimeSequence() var prime = primeSequence.nextValue() while(prime < upperLimit) { result.add(prime) prime = primeSequence.nextValue() } return result }
0
Kotlin
1
0
df514adde8c62481d59e78a44060dc80703b8f9f
1,206
euler
MIT License
Kotlin/src/main/kotlin/org/algorithm/problems/0059_rotting_oranges.kt
raulhsant
213,479,201
true
{"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187}
//Problem Statement // In a given grid, each cell can have one of three values: // // the value 0 representing an empty cell; // the value 1 representing a fresh orange; // the value 2 representing a rotten orange. // Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. // // Return the minimum number of minutes that must elapse until no cell has a fresh orange. // If this is impossible, return -1 instead. package org.algorithm.problems import java.util.ArrayDeque class `0059_rotting_oranges` { private val walkMask: Array<Pair<Int, Int>> = arrayOf(Pair(0, 1), Pair(1, 0), Pair(-1, 0), Pair(0, -1)) fun canWalk(grid: Array<IntArray>, row: Int, col: Int, dir: Pair<Int, Int>): Boolean { return row + dir.first >= 0 && row + dir.first < grid.size && col + dir.second >= 0 && col + dir.second < grid[0].size && grid[row + dir.first][col + dir.second] == 1 } fun orangesRotting(grid: Array<IntArray>): Int { var bfs: ArrayDeque<Pair<Int, Int>> = ArrayDeque<Pair<Int, Int>>() var result: Int = -1 for (row in 0..grid.size - 1) { for (col in 0..grid[0].size - 1) { if (grid[row][col] == 2) { bfs.add(Pair(row, col)); } } } while (bfs.isNotEmpty()) { var tam: Int = bfs.size; for (index in 0..tam - 1) { var coord: Pair<Int, Int> = bfs.pollFirst(); for (dir in walkMask) { if (canWalk(grid, coord.first, coord.second, dir)) { val row = coord.first + dir.first val col = coord.second + dir.second grid[row][col] = 2 bfs.add(Pair(row, col)) } } } result++ } for (row in 0..grid.size - 1) { for (col in 0..grid[0].size - 1) { if (grid[row][col] == 1) { return -1 } } } if (result < 0) return 0 return result } }
0
C++
0
0
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
2,170
algorithms
MIT License
src/year2023/22/Day22.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`22` import readInput import kotlin.math.max import kotlin.math.min private const val CURRENT_DAY = "22" data class Point( val x: Int, val y: Int, val z: Int, ) { override fun toString(): String = "[$x,$y,$z]" } private val cache = mutableMapOf<Brick, Set<Point>>() data class Brick( val start: Point, val end: Point, ) { override fun toString(): String = "[start=$start,end=$end]" val maxX = max(start.x, end.x) val maxY = max(start.y, end.y) private val maxZ = max(start.z, end.z) val minX = min(start.x, end.x) val minY = min(start.y, end.y) private val minZ = min(start.z, end.z) fun setOfPoints(): Set<Point> { val cachedValue = cache[this] if (cachedValue != null) return cachedValue val result = when { start.x != end.x -> { val range = minX..maxX assert(start.y == end.y) assert(start.z == end.z) range .map { start.copy(x = it) } .toSet() } start.y != end.y -> { val range = minY..maxY assert(start.x == end.x) assert(start.z == end.z) range .map { start.copy(y = it) } .toSet() } start.z != end.z -> { val range = minZ..maxZ assert(start.x == end.x) assert(start.y == end.y) range .map { start.copy(z = it) } .toSet() } start == end -> { setOf(start) } else -> error("ILLEGAL STATE $this") } cache[this] = result return result } fun dropN(n: Int): Brick { return copy( start = start.copy(z = start.z - n), end = end.copy(z = end.z - n), ) } } private fun parseLineInto( line: String ): Brick { val (first, second) = line.split("~").filter { it.isNotBlank() } val (x1, y1, z1) = first.split(",").filter { it.isNotBlank() }.map { it.toInt() } val (x2, y2, z2) = second.split(",").filter { it.isNotBlank() }.map { it.toInt() } return Brick( start = Point(x1, y1, z1), end = Point(x2, y2, z2), ) } fun dropAllUntilItFalls( bricks: Set<Brick>, ): Pair<Set<Brick>, Int> { var currentDroppedBricks = emptySet<Brick>() var droppedCount = 0 val flatPanel = prepareFlatPanel(bricks) bricks.forEachIndexed { _, currentBrick -> val (newBricks, wasDropped) = dropTillTheEnd( flatGrid = flatPanel, droppedBricks = currentDroppedBricks, currentBrick = currentBrick, ) currentDroppedBricks = newBricks if (wasDropped) droppedCount++ } return currentDroppedBricks to droppedCount } fun dropTillTheEnd( flatGrid: Set<Point>, droppedBricks: Set<Brick>, currentBrick: Brick, ): Pair<Set<Brick>, Boolean> { val droppedBricksPoints = droppedBricks .flatMap { it.setOfPoints() } val allPointsHere: Set<Point> = flatGrid + droppedBricksPoints val res = currentBrick.setOfPoints() .minOf { point -> val maxZPoint = allPointsHere .filter { point.x == it.x && point.y == it.y } .maxBy { it.z } val something = point.z - maxZPoint.z - 1 something } return (droppedBricks + currentBrick.dropN(res)) to (res != 0) } private fun prepareFlatPanel(bricks: Set<Brick>): Set<Point> { val maxX = bricks.maxOf { it.maxX } val minX = bricks.minOf { it.minX } val maxY = bricks.maxOf { it.maxY } val minY = bricks.minOf { it.minY } val res = mutableSetOf<Point>() (minX..maxX).forEach { x -> (minY..maxY).forEach { y -> res.add(Point(x, y, 0)) } } return res } private fun returnBricksThatAreSaveToDelete(initialBricks: Set<Brick>): Map<Brick, Int> { val setToReturn = mutableMapOf<Brick, Int>() println("returnBricksThatAreSaveToDelete size${initialBricks.size}") initialBricks.forEachIndexed { index, brick -> println("returnBricksThatAreSaveToDelete index $index") val bricksWithoutIt = initialBricks - brick val (_, count) = dropAllUntilItFalls(bricksWithoutIt) setToReturn[brick] = count } return setToReturn } fun main() { fun part1(input: List<String>): Int { val bricks = input.map { parseLineInto(it) } .sortedBy { minOf(it.end.z, it.start.z) } .onEach { println(it) } .toSet() val resBricks = dropAllUntilItFalls(bricks).first val resMap = returnBricksThatAreSaveToDelete(resBricks) return resMap.filter { it.value == 0 }.size } fun part2(input: List<String>): Int { val bricks = input.map { parseLineInto(it) } .sortedBy { minOf(it.end.z, it.start.z) } .onEach { println(it) } val resBricks = dropAllUntilItFalls(bricks.toSet()) .first .onEach { println(it) } val res = returnBricksThatAreSaveToDelete(resBricks) return res.values.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 5) val part2Test = part2(testInput) println(part2Test) check(part2Test == 7) val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 507) // Part 2 val part2 = part2(input) println(part2) check(part2 == 51733) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
5,837
KotlinAdventOfCode
Apache License 2.0
src/main/kotlin/io/github/t45k/scm/matching/algorithms/suffixArray/DoublingConstructor.kt
T45K
255,912,849
false
null
package io.github.t45k.scm.matching.algorithms.suffixArray import io.github.t45k.scm.entity.TokenSequence class DoublingConstructor : ArrayConstructor { override fun construct(from: TokenSequence, querySize: Int): SuffixArray { val size: Int = from.size - querySize val sortedIndices: Array<Int> = Array(size) { it } var rank: Array<Int> = Array(size) { from[it] } var k = 1 val compareByRank: Comparator<Int> = Comparator<Int> { i, j -> rank[i] - rank[j] }.thenComparing { i, j -> val iWithRank = if (i + k < size) rank[i + k] else -1 val jWithRank = if (j + k < size) rank[j + k] else -1 iWithRank - jWithRank } while (k <= size) { sortedIndices.sortWith(compareByRank) rank = updateRank(sortedIndices, compareByRank, size) k *= 2 } return sortedIndices .map { it to from.subList(it, from.size) } .toList() } private fun updateRank(sortedIndices: Array<Int>, compareByRank: Comparator<Int>, size: Int): Array<Int> { val tmp: Array<Int> = Array(size) { 0 } tmp[sortedIndices[0]] = 0 for (i in 1 until size) { tmp[sortedIndices[i]] = tmp[sortedIndices[i - 1]] + if (compareByRank.compare(sortedIndices[i - 1], sortedIndices[i]) >= 0) 0 else 1 } return tmp } }
0
Kotlin
0
0
37b3ffac9bdf6e24a3fc3ae9282f3f692ec8d12d
1,423
SCM
MIT License
src/Day01.kt
ciprig
573,478,617
false
null
import java.util.TreeSet fun main() { fun parseInput(input: List<String>): TreeSet<Int> { val elfs = sortedSetOf<Int>(compareByDescending { it }) var sum = 0 for (s in input) { if (s.isEmpty()) { elfs.add(sum) sum = 0 } else { sum += s.toInt() } } elfs.add(sum) return elfs } fun part1(input: List<String>): Int { return parseInput(input).first() } fun part2(input: List<String>): Int { return parseInput(input).take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(testInput)) check(part2(testInput) == 45000) println(part2(input)) println(parseInput(testInput)) }
0
Kotlin
0
0
e24dd65a22106bf5375d9d99c8b9d3b3a90e28da
983
aoc2022
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day10.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.max import fr.outadoc.aoc.scaffold.min import fr.outadoc.aoc.scaffold.readDayInput class Day10 : Day<Long> { companion object { const val OUTLET_JOLTS = 0L const val BUILT_IN_ADAPTER_JOLTS_DIFFERENCE = 3 val ADAPTER_TOLERANCE: IntRange = 1..3 } private val input: List<Long> = readDayInput() .lines() .map { it.toLong() } .sorted() private val maxAdapterJolts: Long = input.max() private val builtInAdapterJolts: Long = maxAdapterJolts + BUILT_IN_ADAPTER_JOLTS_DIFFERENCE private val adapterList: List<Long> = input + builtInAdapterJolts private tailrec fun makeAdapterChain( remainingAdapters: List<Long>, currentChain: List<Long> = listOf(OUTLET_JOLTS) ): List<Long> { return when { remainingAdapters.isEmpty() -> currentChain else -> { val tail = currentChain.last() val nextAdapter: Long = remainingAdapters .filter { it - tail in ADAPTER_TOLERANCE } .min() makeAdapterChain( remainingAdapters = remainingAdapters - nextAdapter, currentChain = currentChain + nextAdapter ) } } } private fun List<Long>.countDifferences(n: Long): Int { // Compare the difference between each consecutive pair of items in the list return windowed(size = 2).count { it[1] - it[0] == n } } override fun step1(): Long { return makeAdapterChain(adapterList) .run { countDifferences(1) * countDifferences(3) } .toLong() } override fun step2(): Long { val initial = mapOf( OUTLET_JOLTS to 1L ) // For each adapter, count the number of chains that use it. val res = adapterList .fold(initial) { acc, adapter -> acc.toMutableMap() .withDefault { 0L } .apply { // For this adapter, increment the number of chains // for possible *previous* elements in the chain this[adapter] = ADAPTER_TOLERANCE.sumOf { difference -> getValue(adapter - difference) } } } // Since every *possible* chain ends at the built-in adapter, the maximum // value in the map contains the number of possible chains. return res.getValue(builtInAdapterJolts) } override val expectedStep1: Long = 1885 override val expectedStep2: Long = 2024782584832 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,827
adventofcode
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day22.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.doubleLines import com.grappenmaker.aoc.toQueue fun PuzzleSet.day22() = puzzle(day = 22) { val (initialP1, initialP2) = input.doubleLines().map { it.lines().drop(1).map(String::toInt) } data class Outcome(val p1: List<Int> = initialP1, val p2: List<Int> = initialP2) fun Outcome.score() = (p1.takeIf { it.isNotEmpty() } ?: p2) .asReversed().foldIndexed(0L) { idx, acc, v -> acc + (idx + 1) * v }.s() fun Outcome.playerOneWins() = p1.isNotEmpty() fun step( startP1: List<Int> = initialP1, startP2: List<Int> = initialP2, partTwo: Boolean = false, update: (p1: MutableList<Int>, p2: MutableList<Int>) -> Unit ): Outcome { val p1 = startP1.toQueue() val p2 = startP2.toQueue() val seen = hashSetOf((p1 to p2).hashCode()) while (p1.isNotEmpty() && p2.isNotEmpty()) { update(p1, p2) if (partTwo && !seen.add((p1 to p2).hashCode())) break } return Outcome(p1, p2) } partOne = step { p1, p2 -> val a = p1.removeFirst() val b = p2.removeFirst() val target = if (a > b) p1 else p2 target += maxOf(a, b) target += minOf(a, b) }.score() fun recurse(sp1: List<Int> = initialP1, sp2: List<Int> = initialP2): Outcome = step(sp1, sp2, true) { p1, p2 -> val a = p1.removeFirst() val b = p2.removeFirst() val p1Wins = when { p1.size < a || p2.size < b -> a > b else -> recurse(p1.take(a), p2.take(b)).playerOneWins() } val winner = if (p1Wins) p1 else p2 winner += if (p1Wins) a else b winner += if (p1Wins) b else a } partTwo = recurse().score() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,825
advent-of-code
The Unlicense
day05/part2.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Part Two --- // Everyone will starve if you only plant such a small number of seeds. // Re-reading the almanac, it looks like the seeds: line actually describes // ranges of seed numbers. // // The values on the initial seeds: line come in pairs. Within each pair, the // first value is the start of the range and the second value is the length of // the range. So, in the first line of the example above: // // seeds: 79 14 55 13 // // This line describes two ranges of seed numbers to be planted in the garden. // The first range starts with seed number 79 and contains 14 values: 79, 80, // ..., 91, 92. The second range starts with seed number 55 and contains 13 // values: 55, 56, ..., 66, 67. // // Now, rather than considering four seed numbers, you need to consider a total // of 27 seed numbers. // // In the above example, the lowest location number can be obtained from seed // number 82, which corresponds to soil 84, fertilizer 84, water 84, light 77, // temperature 45, humidity 46, and location 46. So, the lowest location number // is 46. // // Consider all of the initial seed numbers listed in the ranges on the first // line of the almanac. What is the lowest location number that corresponds to // any of the initial seed numbers? import java.io.* import kotlin.math.* // The values of `maps` is a sorted list of pairs where the first pair element // is a range of destination numbers (the list is sorted on this), and the // second element of the pair is an "adjustment" - a number added to a // destination number in the range to obtain a source number. var seeds: List<Long> = listOf() val mapsTo: MutableMap<String, String> = hashMapOf() val maps: MutableMap<String, MutableList<Pair<LongRange, Long>>> = hashMapOf() var currentMap: MutableList<Pair<LongRange, Long>> = mutableListOf() var currentMapName = "" val MAP_RGX = Regex("(\\w+)-to-(\\w+) map:") File("input.txt").forEachLine { if (it.isBlank()) return@forEachLine if (it.startsWith("seeds:")) { seeds = it.drop(7).split(' ').map(String::toLong) return@forEachLine } val mapLine = MAP_RGX.find(it) if (mapLine != null) { currentMap = mutableListOf() currentMapName = mapLine.groupValues[2] mapsTo[currentMapName] = mapLine.groupValues[1] maps[currentMapName] = currentMap return@forEachLine } val (destinationStart, sourceStart, length) = it.split(' ').map(String::toLong) val destinationEnd = destinationStart + length - 1 val adjustment = sourceStart - destinationStart var idx = currentMap.indexOfFirst { it.first.start > destinationStart } if (idx == -1) { idx = currentMap.size } currentMap.add(idx, (destinationStart..destinationEnd) to adjustment) } // Basic idea is to work backward... just try every possible location, starting // with zero, and working up until we find a location that has a corresponding // seed in the input. I spent hours on more complicated algos that always // seemed to return zero - and I found other people complaining about the same // issue. So, there must be some trick in the input that I didn't see. But // working backward actually runs fairly quickly, so whatever. fun locationToPossibleSeed(category: String, num: Long): Long { val pairs = maps[category]!! val pair = pairs.find { it.first.contains(num) } val newNum = if (pair == null) num else (num + pair.second) val nextCategory = mapsTo[category]!! if (nextCategory == "seed") { return newNum } return locationToPossibleSeed(nextCategory, newNum) } val seedRanges = seeds.chunked(2).map { (seed, length) -> seed..(seed + length - 1) } val location = generateSequence(0L) { it + 1L }.find { val possibleSeed = locationToPossibleSeed("location", it) seedRanges.any { it.contains(possibleSeed) } } println(location)
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
3,789
adventofcode2023
MIT License
kotlin/376.Wiggle Subsequence(摆动序列).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p>A sequence of numbers is called a <strong>wiggle sequence</strong> if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. </p> <p>For example, <code>[1,7,4,9,2,5]</code> is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, <code>[1,4,7,2,5]</code> and <code>[1,7,4,5,5]</code> are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.</p> <p>Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.</p> <p><b>Examples:</b><br /> <pre> <b>Input:</b> [1,7,4,9,2,5] <b>Output:</b> 6 The entire sequence is a wiggle sequence. <b>Input:</b> [1,17,5,10,13,15,10,5,16,8] <b>Output:</b> 7 There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. <b>Input:</b> [1,2,3,4,5,6,7,8,9] <b>Output:</b> 2 </pre> </p> <p><b>Follow up:</b><br /> Can you do it in O(<i>n</i>) time? </p> <p><b>Credits:</b><br />Special thanks to <a href="https://leetcode.com/agave/">@agave</a> and <a href="https://leetcode.com/stefanpochmann/">@StefanPochmann</a> for adding this problem and creating all test cases.</p><p>如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为<strong>摆动序列。</strong>第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。</p> <p>例如,&nbsp;<code>[1,7,4,9,2,5]</code> 是一个摆动序列,因为差值 <code>(6,-3,5,-7,3)</code>&nbsp;是正负交替出现的。相反, <code>[1,4,7,2,5]</code>&nbsp;和&nbsp;<code>[1,7,4,5,5]</code> 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。</p> <p>给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。</p> <p><strong>示例:</strong></p> <pre> <strong>输入:</strong> [1,7,4,9,2,5] <strong>输出:</strong> 6 <strong>解释:</strong> 整个序列就是一个摆动序列。 <strong>输入:</strong> [1,17,5,10,13,15,10,5,16,8] <strong>输出:</strong> 7 <strong>解释: </strong>它的几个子序列满足摆动序列。其中一个是[1,17,10,13,10,16,8]。 <strong>输入:</strong> [1,2,3,4,5,6,7,8,9] <strong>输出:</strong> 2 </pre> <p><strong>进阶:</strong><br /> 你能否用&nbsp;O(<em>n</em>) 时间复杂度完成此题?</p> <p>如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为<strong>摆动序列。</strong>第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。</p> <p>例如,&nbsp;<code>[1,7,4,9,2,5]</code> 是一个摆动序列,因为差值 <code>(6,-3,5,-7,3)</code>&nbsp;是正负交替出现的。相反, <code>[1,4,7,2,5]</code>&nbsp;和&nbsp;<code>[1,7,4,5,5]</code> 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。</p> <p>给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。</p> <p><strong>示例:</strong></p> <pre> <strong>输入:</strong> [1,7,4,9,2,5] <strong>输出:</strong> 6 <strong>解释:</strong> 整个序列就是一个摆动序列。 <strong>输入:</strong> [1,17,5,10,13,15,10,5,16,8] <strong>输出:</strong> 7 <strong>解释: </strong>它的几个子序列满足摆动序列。其中一个是[1,17,10,13,10,16,8]。 <strong>输入:</strong> [1,2,3,4,5,6,7,8,9] <strong>输出:</strong> 2 </pre> <p><strong>进阶:</strong><br /> 你能否用&nbsp;O(<em>n</em>) 时间复杂度完成此题?</p> **/ class Solution { fun wiggleMaxLength(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
4,363
leetcode
MIT License
src/test/kotlin/Test.kt
lhDream
708,889,856
false
{"Kotlin": 20990}
import java.util.* import kotlin.math.abs // 棋盘大小 const val BOARD_SIZE = 15 // 评估函数(简化版本,根据棋局评估得分) // 五子棋中针对当前局面的评估函数 fun evaluate(board: Array<Array<Int>>, player: Int): Int { val opponent = if (player == 2) 1 else 2 var score = 0 // 检查每个位置的行、列、对角线是否存在连续的棋子 for (i in 0 until BOARD_SIZE) { for (j in 0 until BOARD_SIZE) { // 检查水平、垂直和对角线上的棋子情况 val directions = arrayOf( intArrayOf(1, 0), intArrayOf(1, -1), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 0), intArrayOf(-1, 1), intArrayOf(0, 1), intArrayOf(1, 1) ) for (dir in directions) { var countPlayer = 0 var countOpponent = 0 var association = 0 for (k in 0 until 6) { val r = i + k * dir[0] val c = j + k * dir[1] if (r in 0 until BOARD_SIZE && c in 0 until BOARD_SIZE) { if (board[r][c] == player) { countPlayer++ } else if (board[r][c] == opponent) { countOpponent++ } association = association * 10 + board[r][c] } else { break } } score += when(association){ 22222 -> 50000 // 活五 22220, 22202, 22022, 20222 -> 10000 // 活四 122220, 122202, 122022, 120222, 102222, 22221 -> 5000 // 冲四 222, 2202, 2022, 2220 -> 2000 // 活三 12220, 12202, 12022, 10222, 2221 -> 1000 // 眠三 22, 202, 20 -> 500 // 活二 1220, 1202, 1020, 210, 2120 -> 200 // 眠二 else -> 0 } } } } return score } // Minimax 算法 fun minimax(board: Array<Array<Int>>, depth: Int, player: Int): Int { if (depth == 0) { return evaluate(board,player) } var bestScore = 0 val opponent = if (player == 2) 1 else 2 for (i in 0 until BOARD_SIZE) { for (j in 0 until BOARD_SIZE) { if (board[i][j] == 0) { board[i][j] = opponent val score = minimax(board, depth - 1, opponent) board[i][j] = 0 bestScore = maxOf(bestScore, score) } } } return bestScore } // 寻找最佳下棋位置 fun findBestMove(board: Array<Array<Int>>,player: Int): Pair<Int, Int> { var bestScore = Int.MIN_VALUE var bestMove = Pair(-1, -1) for (i in 0 until BOARD_SIZE) { for (j in 0 until BOARD_SIZE) { if (board[i][j] == 0) { board[i][j] = player // 模拟落子 var score = minimax(board, 3, player) // 这里设定最大搜索深度为3 score = score * major[i][j] + major[i][j] // 位置价值 board[i][j] = 0 // 撤销落子 if (score > bestScore) { bestScore = score // 更新最高分 bestMove = Pair(i, j) // 更新最佳落子位置 } } } } return bestMove } // 初始化位置价值矩阵 fun initMatrix(matrix:Array<Array<Int>>){ val centerX = matrix.size / 2 val centerY = matrix.size / 2 for (i in matrix.indices) { for (j in matrix.indices) { val distance = abs(i - centerX) + abs(j - centerY) matrix[i][j] = matrix.size - distance } } } // 位置价值矩阵 val major = Array(BOARD_SIZE) { Array(BOARD_SIZE) { 0 } } // 主函数 fun main() { initMatrix(major) val board = Array(BOARD_SIZE) { Array(BOARD_SIZE) { 0 } } // 模拟当前棋盘状态 val scan = Scanner(System.`in`) while (true){ // ... val (x,y) = findBestMove(board,2) board[x][y] = 2 println("Best Move: ${x}, $y") for (i in board.indices){ println(board[i].contentToString()) } val p = scan.nextLine().split(",") board[p[0].toInt()][p[1].toInt()] = 1 } }
0
Kotlin
0
0
c83c58cba821f0b8663bea53750495f3dfbfce34
4,428
wuziqi
MIT License
src/main/kotlin/g1701_1800/s1719_number_of_ways_to_reconstruct_a_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1719_number_of_ways_to_reconstruct_a_tree // #Hard #Tree #Graph #Topological_Sort #2023_06_16_Time_1015_ms_(100.00%)_Space_102_MB_(100.00%) class Solution { fun checkWays(pairs: Array<IntArray>): Int { val adj = Array(501) { IntArray(501) } val set = HashSet<Int>() for (pair in pairs) { adj[pair[0]][pair[1]]++ adj[pair[1]][pair[0]]++ set.add(pair[0]) set.add(pair[1]) } val n = set.size val num = IntArray(501) for (i in 0..500) { for (j in 0..500) { num[i] += adj[i][j] } } var c = 0 for (i in 0..500) { if (num[i] == n - 1) { c++ } } for (j in 0..500) { if (num[j] == n - 1) { num[j] = 0 for (k in 0..500) { if (adj[j][k] > 0) { adj[j][k] = 0 adj[k][j] = 0 num[k]-- } } set.remove(j) break } if (j == 500) { return 0 } } val res = search(adj, num, set) return if (res == 1 && c > 1) { 2 } else res } private fun search(adj: Array<IntArray>, num: IntArray, vals: HashSet<Int>): Int { if (vals.isEmpty()) { return 1 } var max = 0 for (i in vals) { if (num[i] > num[max]) { max = i } } val size = num[max] if (size == 0) { return 1 } var c = false i@ for (i in vals) { if (num[i] == num[max]) { for (j in vals) { if (j != i && num[j] == num[i] && adj[i][j] > 0) { c = true break@i } } } } val set = HashSet<Int>() for (j in 0..500) { if (adj[max][j] > 0 && !vals.contains(j)) { return 0 } if (adj[max][j] > 0) { adj[max][j] = 0 adj[j][max] = 0 num[j]-- set.add(j) } } num[max] = 0 val set2 = HashSet<Int>() for (i in vals) { if (!set.contains(i) && i != max) { set2.add(i) } } val res1 = search(adj, num, set) val res2 = search(adj, num, set2) if (res1 == 0 || res2 == 0) { return 0 } return if (res1 == 2 || res2 == 2 || c) { 2 } else 1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,798
LeetCode-in-Kotlin
MIT License
src/Day08.kt
othimar
573,607,284
false
{"Kotlin": 14557}
fun main() { fun part1(input: List<String>): Int { var number = 0; for (i in 1 until input.size - 1) { val line = input[i] for (j in 1 until line.length - 1) { val tree = line[j].toString().toInt() var visibleTop = true var visibleBottom = true var visibleLeft = true var visibleRight = true for (k in input.indices) { if (k < i) { if (input[k][j].toString().toInt() >= tree) { visibleLeft = false } } if (k > i) { if (input[k][j].toString().toInt() >= tree) { visibleRight = false break } } } for (k in line.indices) { if (k < j) { if (input[i][k].toString().toInt() >= tree) { //println("neighbour top "+input[i][k].toString().toInt()) visibleTop = false } } if (k > j) { if (input[i][k].toString().toInt() >= tree) { visibleBottom = false break } } } if (visibleLeft or visibleRight or visibleTop or visibleBottom) { number++ } } } number += input.size * 2 + input[0].length * 2 - 4 return number } fun part2(input: List<String>): Int { val scenicScore = ArrayList<Int>() for (i in 1 until input.size - 1) { val line = input[i] for (j in 1 until line.length - 1) { val tree = line[j].toString().toInt() println("Tree $tree") var sCTop = 0 var sCBottom = 0 var sCLeft = 0 var sCRight = 0 for (k in i - 1 downTo 0) { if (input[k][j].toString().toInt() < tree) { sCTop++ } else { sCTop++ break } } for (k in i + 1 until input.size) { if (input[k][j].toString().toInt() < tree) { sCBottom++ } else { sCBottom++ break } } for (k in j - 1 downTo 0) { if (input[i][k].toString().toInt() < tree) { sCLeft++ } else { sCLeft++ break } } for (k in j + 1 until line.length) { if (input[i][k].toString().toInt() < tree) { sCRight++ } else { sCRight++ break } } println() scenicScore.add(sCLeft * sCRight * sCTop * sCBottom) } } return scenicScore.max() } check(part1(readInput("Day08_test")) == 21) check(part2(readInput("Day08_test")) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ff62a00123fe817773ff6248d34f606947ffad6d
3,633
advent-of-code-2022
Apache License 2.0
src/Day02.kt
mihansweatpants
573,733,975
false
{"Kotlin": 31704}
import java.lang.IllegalArgumentException fun main() { fun part1(input: List<String>): Int { var totalPoints = 0 for (line in input) { val opponent = PlayerChoice.fromCode(line.first()) val me = PlayerChoice.fromCode(line.last()) totalPoints += me.playAgainst(opponent) } return totalPoints } fun part2(input: List<String>): Int { var totalPoints = 0 for (line in input) { val opponent = PlayerChoice.fromCode(line.first()) val me = when (line.last()) { 'X' -> opponent.beats 'Y' -> opponent 'Z' -> opponent.loses else -> throw IllegalArgumentException("Unknown code ${line.last()}") } totalPoints += me.playAgainst(opponent) } return totalPoints } val input = readInput("Day02").lines() println(part1(input)) println(part2(input)) } enum class PlayerChoice(private val weight: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { fun fromCode(code: Char): PlayerChoice { return when (code) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> throw IllegalArgumentException("Unknown code $code") } } } val beats: PlayerChoice get() = when(this) { ROCK -> SCISSORS PAPER -> ROCK SCISSORS -> PAPER } val loses: PlayerChoice get() = when(this) { ROCK -> PAPER PAPER -> SCISSORS SCISSORS -> ROCK } fun playAgainst(opponentChoice: PlayerChoice): Int { return if (this.beats == opponentChoice) { this.weight + 6 } else if (this == opponentChoice) { return this.weight + 3 } else { this.weight } } }
0
Kotlin
0
0
0de332053f6c8f44e94f857ba7fe2d7c5d0aae91
1,977
aoc-2022
Apache License 2.0
src/Day05.kt
Sasikuttan2163
647,296,570
false
null
import java.util.* fun main() { val input = readInput("Day05") val start = input.indexOf("") - 1 lateinit var data: MutableList<Stack<Char>> fun collectData() { var i = start - 1 data = MutableList(input[start].trim().substringAfterLast(" ").toInt()) { Stack<Char>() } while (i >= 0) { var j = 1 val line = input[i] while (j < line.length) { if (line[j] != ' ') { data[(j - 1) / 4].push(line[j]) } j += 4 } i -= 1 } } collectData() var stacks = data input.filter { it.startsWith("move") } .forEach { l -> l.split(" ") .filter { it.toIntOrNull() != null } .map { it.toInt() } .let { array -> repeat(array[0]) { stacks[array[2] - 1].push(stacks[array[1] - 1].pop()) } } } val part1 = stacks.fold("") { final, element -> final + element.last() } collectData() stacks = data input.filter { it.startsWith("move") } .forEach { l -> l.split(" ") .filter { it.toIntOrNull() != null } .map { it.toInt() } .let { array -> val stack = mutableListOf<Char>() repeat(array[0]) { stack.add(stacks[array[1] - 1].pop()) } stack.reversed() .forEach { stacks[array[2] - 1].push(it) } } } val part2 = stacks.fold("") { final, element -> final + element.last() } part1.println() part2.println() }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
1,796
AoC-2022-Solutions-In-Kotlin
MIT License
src/main/kotlin/g1301_1400/s1349_maximum_students_taking_exam/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1349_maximum_students_taking_exam // #Hard #Array #Dynamic_Programming #Matrix #Bit_Manipulation #Bitmask // #2023_06_06_Time_173_ms_(100.00%)_Space_35.7_MB_(100.00%) class Solution { fun maxStudents(seats: Array<CharArray>): Int { val m = seats.size val n = seats[0].size val validRows = IntArray(m) for (i in 0 until m) { for (j in 0 until n) { validRows[i] = (validRows[i] shl 1) + if (seats[i][j] == '.') 1 else 0 } } val stateSize = 1 shl n val dp = Array(m) { IntArray(stateSize) } for (i in 0 until m) { dp[i].fill(-1) } var ans = 0 for (i in 0 until m) { for (j in 0 until stateSize) { if (j and validRows[i] == j && j and (j shl 1) == 0) { if (i == 0) { dp[i][j] = Integer.bitCount(j) } else { for (k in 0 until stateSize) { if (k shl 1 and j == 0 && j shl 1 and k == 0 && dp[i - 1][k] != -1) { dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + Integer.bitCount(j)) } } } ans = Math.max(ans, dp[i][j]) } } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,409
LeetCode-in-Kotlin
MIT License
src/main/aoc2021/Day24.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2021 class Day24(input: List<String>) { // The input has 14 chunks, one for each digit, of 18 instructions each where // the 6th and 16th instructions varies and the rest are the same. private val variantOne = input.chunked(18).map { it[5].split(" ").last().toInt() } private val variantTwo = input.chunked(18).map { it[15].split(" ").last().toInt() } /** * The result of running the program * @param first The first digit in the input that might have to be modified * @param second The second digit in the input that might have to be modified * @param amount The amount the first digit needs to be increased, or alternatively how much the second digit * must be decreased. If increase is zero the program completed as expected. */ data class Result(val first: Int, val second: Int, val amount: Int) /** * A rewrite in Kotlin of the program given as puzzle input. For z to be 0 at the end x and w must * be the same every time variantOne is negative. So this function returns early if that is not * the case with instructions on how to modify the input in order for x == w to be true. * * The program pushes 7 values to a stack and pops 7 values. When it pops a value it compares * if the current digit matches the corresponding one pushed earlier with some additions based * on variantOne and variantTwo. Each character in the input is therefore connected to another * character in the input and the diff between the characters is important. So the characters * can have several accepted values as long as the diff between them are constant. */ private fun theProgram4(input: List<Int>): Result { var w: Int var x: Int val stack = mutableListOf(-1 to 0) // <digit that the current value is based on> to <value> repeat(14) { digit -> w = input[digit] x = stack.last().second % 26 val beforeRemoval = stack.last().first if (variantOne[digit] < 0) { stack.removeLast() } x += variantOne[digit] if (variantOne[digit] < 0 && x != w) { // For z to be 0 at the end x must equal w every time variantOne is negative, // if it isn't return how much the digit at 'beforeRemoval' or at 'digit' // needs to be adjusted for x to equal w return Result(beforeRemoval, digit, (w - x)) } if (x != w) { stack.add(digit to w + variantTwo[digit]) } } return Result(0, 0, 0) } fun solvePart1(): Long { // Start from all 9:s and decrease the required digit once an error is detected val testInput = "99999999999999".map { it.digitToInt() }.toMutableList() do { val (first, second, amount) = theProgram4(testInput) if (amount < 0) { testInput[first] += amount } else if (amount > 0) { testInput[second] -= amount } } while (amount != 0) return testInput.joinToString("").toLong() } fun solvePart2(): Long { // Start from all 1:s and increase the required digit once an error is detected val testInput = "11111111111111".map { it.digitToInt() }.toMutableList() do { val (first, second, amount) = theProgram4(testInput) if (amount < 0) { testInput[second] -= amount } else if (amount > 0) { testInput[first] += amount } } while (amount != 0) return testInput.joinToString("").toLong() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,718
aoc
MIT License
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/middle/Operations.kt
scientificCommunity
352,868,267
false
{"Java": 154453, "Kotlin": 69817}
package org.baichuan.sample.algorithms.leetcode.middle /** * @author: tk (<EMAIL>) * @date: 2022/1/11 */ class Operations { var negatives = LongArray(32) var positives = LongArray(32) var cacheA = LongArray(32) var cacheB = LongArray(32) val NEGATIVE_UNIT = -1 fun Operations() { negatives[0] = NEGATIVE_UNIT.toLong() positives[0] = 1 for (i in 1..31) { negatives[i] = negatives[i + NEGATIVE_UNIT] + negatives[i + NEGATIVE_UNIT] positives[i] = positives[i + NEGATIVE_UNIT] + positives[i + NEGATIVE_UNIT] } } fun minus(a: Int, b: Int): Int { var aVar = a var bVar = b if (aVar == bVar) { return 0 } var index = 31 while (index >= 0) { if (bVar > 0) { if (bVar >= positives[index]) { bVar += (negatives[index]).toInt() aVar += (negatives[index]).toInt() } else { index += NEGATIVE_UNIT } } else { if (bVar <= negatives[index]) { bVar += (positives[index]).toInt() aVar += (positives[index]).toInt() } else { index += NEGATIVE_UNIT } } } return aVar } fun multiply(a: Int, b: Int): Int { var aVar = a var bVar = b if (aVar == 0 || bVar == 0) return 0 if (aVar == 1) return bVar if (bVar == 1) return aVar if (aVar == NEGATIVE_UNIT) return minus(0, bVar) if (bVar == NEGATIVE_UNIT) return minus(0, aVar) val aSign = aVar > 0 //最终结果的正负,true:正 false:负 val resultSign = aVar > 0 && bVar > 0 || aVar < 0 && bVar < 0 /** * 转负数是为了简化代码 * 为什么不转正数?因为-2147483648无法转成有效的4字节正数 */ if (aVar > 0) { aVar = minus(0, aVar) } if (bVar > 0) { bVar = minus(0, bVar) } cacheA[0] = aVar.toLong() for (i in 1..30) { cacheA[i] = cacheA[i + NEGATIVE_UNIT] + cacheA[i + NEGATIVE_UNIT] } var result = 0 var index = 31 while (index >= 0) { if (bVar <= negatives[index]) { bVar += (positives[index]).toInt() result += (cacheA[index]).toInt() } index += NEGATIVE_UNIT } //原始结果符号,用来判断计算结果是否溢出 val originalResultSign = result > 0 //确保溢出的情况不会影响结果的正负 if (originalResultSign != aSign) { result = minus(0, result) } //确定最终结果的正负 if (resultSign && result < 0 || !resultSign && result > 0) { result = minus(0, result) } return result } fun divide(a: Int, b: Int): Int { var aVar = a var bVar = b if (aVar == 0 || aVar > 0 && aVar < bVar || aVar < 0 && aVar > bVar) return 0 var result = 0 val resultSign = aVar > 0 && bVar > 0 || aVar < 0 && bVar < 0 if (aVar > 0) { aVar = minus(0, aVar) } if (bVar > 0) { bVar = minus(0, bVar) } //cacheB[0] = b* 2^0 cacheB[0] = bVar.toLong() for (i in 1..31) { cacheB[i] = cacheB[i + NEGATIVE_UNIT] + cacheB[i + NEGATIVE_UNIT] } var index = 31 var preDividedB: Long = 0 while (index >= 0) { if (aVar <= cacheB[index] + preDividedB) { preDividedB += cacheB[index] result += (positives[index]).toInt() } index += NEGATIVE_UNIT } //确定最终结果的正负 if (resultSign && result < 0 || !resultSign && result > 0) { result = minus(0, result) } return result } }
1
Java
0
8
36e291c0135a06f3064e6ac0e573691ac70714b6
4,084
blog-sample
Apache License 2.0
src/main/kotlin/io/github/fbiville/solver/Tree.kt
fbiville
129,937,320
false
null
package io.github.fbiville.solver import kotlin.coroutines.experimental.buildIterator class Tree<T>(private val breadth: Int, private val depth: Int, private val root: T) { internal val values: MutableList<T> = MutableList(capacity(breadth, depth), { _ -> root }) internal val capacity: Int get() = values.size fun setChildrenOf(parent: Int, vararg children: T): Tree<T> { checkArguments(parent, children) val start = breadth * parent + 1 for (position in start until start + breadth) { values[position] = children[position - start] } return this } fun matchBranchesByLeaf(predicate: (T) -> Boolean): List<List<T>> { return matchLeaves(predicate).map { val start = TreeDimension(it.index, depth) val end = TreeDimension(0, 0) BottomUpProgression(start, end, { parentDimension(it) }) .map { values[it.index] } .reversed() } } fun nonLeafIndices() = 0 until firstLeafIndex() operator fun get(index: Int): T = values[index] private fun matchLeaves(filter: (T) -> Boolean): List<IndexedValue<T>> { val indexRange = firstLeafIndex() until capacity return values.withIndex() .filter { it.value != null } .filter { it.index in indexRange } .filter { filter(it.value) } } private fun parentDimension(currentDimension: TreeDimension) = TreeDimension((currentDimension.index - 1) / breadth, currentDimension.depth - 1) private fun capacity(breadth: Int, depth: Int): Int { return ((Math.pow(breadth.toDouble(), depth.toDouble() + 1) - 1) / (breadth - 1)).toInt() } private fun checkArguments(parent: Int, children: Array<out T>) { val firstLeafIndex = firstLeafIndex() if (parent !in 0 until firstLeafIndex) { throw IllegalArgumentException("Invalid parent position, got $parent, valid index between 0 and ${firstLeafIndex - 1} incl.") } if (children.size != breadth) { throw IllegalArgumentException("Wrong number of children, got ${children.size}, expected $breadth") } } private fun firstLeafIndex() = capacity - numberOfLeaves() private fun numberOfLeaves() = Math.pow(breadth.toDouble(), depth.toDouble()).toInt() } class BottomUpProgression(private val initialDimension: TreeDimension, private val endDimension: TreeDimension, private val progression: (TreeDimension) -> TreeDimension) : Iterable<TreeDimension> { override fun iterator(): Iterator<TreeDimension> { var dimension = initialDimension return buildIterator { while (dimension.index >= endDimension.index && dimension.depth >= endDimension.depth) { yield(dimension) dimension = progression(dimension) } } } } data class TreeDimension(val index: Int, val depth: Int)
4
Kotlin
0
0
490d55d8b6af8fc40704439c19effbcc1a8f9e1b
3,047
calculator-solver
Apache License 2.0
src/year2020/day4/Solution.kt
Niallfitzy1
319,123,397
false
null
package year2020.day4 import com.github.ajalt.mordant.TermColors import java.io.File fun main() { val passports: MutableList<Passport> = mutableListOf() val fields: MutableList<Field> = mutableListOf() File("src/year2020/day4/input").forEachLine { line -> if (line.isNotEmpty()) { line.split(' ').map { rawField -> val splitField = rawField.split(':') fields.add(Field(splitField[0], splitField[1])) } } else { passports.add( Passport(fields.sortedBy { field -> field.name }.toList()) ) fields.clear() } } with(TermColors()) { passports.forEach { passport -> print("${if (!passport.validatedFieldsPresent) (yellow) else (reset)}Passport $reset") passport.fields.forEach { print("${it.name}: ${if (it.isValidField) (green)(it.value) else (red)(it.value)} $reset") } print( " -> " + (if (!passport.validatedFieldsPresent) "${(reset + yellow)}missing fields" else if (!passport.validatedFieldsPassChecks) "${(red)}invalid field values" else "${(green)}passed") + "\n$reset" ) } val partOne = passports.count { passport -> passport.validatedFieldsPresent } val partTwo = passports.count { passport -> passport.validatedFieldsPassChecks } println("${(brightMagenta)}Found $partOne passports with all fields & $partTwo with fields passing validation$reset") } } data class Passport( val fields: List<Field> ) { private val validatedFields: List<Field> = fields.filter { field -> field.name != "cid" } val validatedFieldsPresent = validatedFields.size == 7 val validatedFieldsPassChecks = validatedFieldsPresent && validatedFields.all { passportField -> passportField.isValidField } } data class Field(val name: String, val value: String) { val isValidField = when (name) { "byr" -> value.toInt() in 1920..2002 "iyr" -> value.toInt() in 2010..2020 "eyr" -> value.toInt() in 2020..2030 "hgt" -> when (value.takeLast(2)) { "cm" -> value.dropLast(2).toInt() in 150..193 "in" -> value.dropLast(2).toInt() in 59..76 else -> false } "hcl" -> value.matches(Regex("#[0-9a-f]{6}\$")) "ecl" -> value.matches(Regex("(amb\$)|(blu\$)|(brn\$)|(gry\$)|(grn\$)|(hzl\$)|(oth\$)")) "pid" -> value.matches(Regex("[0-9]{9}$")) else -> true } }
0
Kotlin
0
0
67a69b89f22b7198995d5abc19c4840ab2099e96
2,737
AdventOfCode
The Unlicense
src/Day01.kt
laricchia
434,141,174
false
{"Kotlin": 38143}
fun firstPart(measurements : List<Int>) { var count = 0 if (measurements.isNotEmpty()) { var currItem = measurements.first().toInt() measurements.subList(1, measurements.size).map { if (it > currItem) count++ currItem = it } } println("Increases = $count") } fun secondPart(measurements: List<Int>) { val windows = measurements.windowed(3) val windowsSums = windows.map { it.reduce { acc, i -> acc + i } } firstPart(windowsSums) } fun main() { /* * count the number of times a depth measurement increases from the previous measurement. * (There is no measurement before the first measurement.) * */ val input : List<String> = readInput("Day01") val measurements = input.filter { it.isNotEmpty() }.map { it.toInt() } firstPart(measurements) secondPart(measurements) }
0
Kotlin
0
0
7041d15fafa7256628df5c52fea2a137bdc60727
883
Advent_of_Code_2021_Kotlin
Apache License 2.0
src/Day24.kt
rod41732
572,917,438
false
{"Kotlin": 85344}
import java.util.* private data class Blizzard(val coord: Coord2D, val direction: Char) /** wrap the integer if it goes outside the range e.g. * (1..5).wrap(0) == 5 * (1..5).wrap(6) == 1 * (1..5).wrap(3) == 1 */ private fun IntRange.wrap(num: Int): Int { return first + (num - first).mod(last - first + 1) } private fun progressBlizzard(blizzards: List<Blizzard>, xRange: IntRange, yRange: IntRange): List<Blizzard> { return blizzards.map { val newCoord = move(it.coord, it.direction).let { Coord2D(xRange.wrap(it.x), yRange.wrap(it.y)) } Blizzard(newCoord, it.direction) } } private data class PlayerState24(val coord: Coord2D, val time: Int) private inline fun Coord2D.forEachPossibleMoves(action: (Coord2D) -> Unit) { action(copy(x = x + 1)) action(copy(x = x - 1)) action(copy(y = y + 1)) action(copy(y = y - 1)) action(copy()) } fun main() { fun findPath( blizzInit: List<Blizzard>, startPos: Coord2D, validX: IntRange, validY: IntRange, endPos: Coord2D, map: List<List<Char>> ): Pair<List<Blizzard>, Int> { var blizzards = blizzInit var blizzTime = 0 var blizzCoords = blizzards.map { it.coord }.toSet() val lastVisit = mutableMapOf<Coord2D, Int>() val q: Queue<PlayerState24> = LinkedList() q.add(PlayerState24(startPos, 0)) while (!q.isEmpty()) { val (coord, time) = q.remove() // println("at $coord, time $time") if (time == blizzTime) { // println("blizztime progress at $time") blizzards = progressBlizzard(blizzards, validX, validY) blizzTime += 1 blizzCoords = blizzards.map { it.coord }.toSet() } coord.forEachPossibleMoves { if (it != endPos && it != startPos && (it.x !in validX || it.y !in validY)) return@forEachPossibleMoves if (it in blizzCoords) return@forEachPossibleMoves if (map[it.y][it.x] == '#') return@forEachPossibleMoves // prevent same state multiple times if (lastVisit.getOrPut(it) { 0 } >= time + 1) return@forEachPossibleMoves lastVisit[it] = time + 1 if (it == endPos) { println("took ${time + 1}") return blizzards to time + 1 } q.add(PlayerState24(it, time + 1)) } } throw Error("BUG: not reached goal") } fun part1(input: List<String>): Int { val startPos = Coord2D(x = input.first().indexOf('.'), y = 0) val endPos = Coord2D(x = input.last().indexOf('.'), y = input.lastIndex) val validX = 1 until input[0].length - 1 val validY = 1 until input.size - 1 val map = input.map { it.toList() } var blizzards = buildList<Blizzard> { input.map { it.toList() }.forEachIndexed { i, row -> row.forEachIndexed { j, c -> when (c) { '^', 'v', '<', '>' -> add(Blizzard(Coord2D(x = j, y = i), c)) } } } } val (_, time) = findPath(blizzards, startPos, validX, validY, endPos, map) return time } fun part2(input: List<String>): Int { val startPos = Coord2D(x = input.first().indexOf('.'), y = 0) val endPos = Coord2D(x = input.last().indexOf('.'), y = input.lastIndex) val validX = 1 until input[0].length - 1 val validY = 1 until input.size - 1 val map = input.map { it.toList() } val blizzards = buildList<Blizzard> { input.map { it.toList() }.forEachIndexed { i, row -> row.forEachIndexed { j, c -> when (c) { '^', 'v', '<', '>' -> add(Blizzard(Coord2D(x = j, y = i), c)) } } } } val (b1, t1) = findPath(blizzards, startPos, validX, validY, endPos, map) val (b2, t2) = findPath(b1, endPos, validX, validY, startPos, map) val (_, t3) = findPath(b2, startPos, validX, validY, endPos, map) return t1 + t2 + t3 } val testInput = readInput("Day24_test") println(part1(testInput)) check(part1(testInput) == 18) println(part2(testInput)) check(part2(testInput) == 18 + 23 + 13) val input = readInput("Day24") println("Part 1") println(part1(input)) println("Part 2") println(part2(input)) }
0
Kotlin
0
0
1d2d3d00e90b222085e0989d2b19e6164dfdb1ce
4,615
advent-of-code-kotlin-2022
Apache License 2.0
30 Days of Code (Kotlin)/day11-2dArrays.kt
swapnanildutta
259,629,657
false
null
/* Question Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video! Context Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation: a b c d e f g There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Task Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. Input Format There are lines of input, where each line contains space-separated integers describing 2D Array ; every value in will be in the inclusive range of to . Constraints Output Format Print the largest (maximum) hourglass sum found in . Sample Input 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample Output 19 Explanation contains the following hourglasses: 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0 The hourglass with the maximum sum ( ) is: 2 4 4 2 1 2 4 */ import java.util.Scanner fun main(args: Array<String>) { var matrix=Array(6){IntArray(6)} val input = Scanner(System.`in`); for(i in 0..5){ for(j in 0..5){ matrix[i][j]=input.nextInt(); } } var sum=Int.MIN_VALUE; for(i in 0..3){ for(j in 0..3){ val curSum=matrix[i][j] + matrix[i][j+1] + matrix[i][j+2]+ matrix[i+1][j+1]+ matrix[i+2][j] + matrix[i+2][j+1] + matrix[i+2][j+2]; if(curSum>sum){ sum=curSum; } } } print(sum); }
41
Python
202
65
01b04ee56f1e4b151ff5b98094accfeb09b55a95
1,978
Hackerrank-Codes
MIT License
src/main/kotlin/day23.kt
Gitvert
433,947,508
false
{"Kotlin": 82286}
fun day23() { val lines: List<String> = readFile("day23.txt") day23part1(lines) day23part2(lines) } fun day23part1(burrow: List<String>) { val amphipods = initAmphipods(burrow) val answer = "TBD" println("23a: $answer") } fun day23part2(lines: List<String>) { val answer = "TBD" println("23b: $answer") } fun initAmphipods(burrow: List<String>): List<Amphipod> { return listOf( Amphipod(Position2D(2, 3), burrow[2][3], getTargetPositions(burrow[2][3]), getMoveCost(burrow[2][3]), 2), Amphipod(Position2D(3, 3), burrow[3][3], getTargetPositions(burrow[3][3]), getMoveCost(burrow[3][3]), 2), Amphipod(Position2D(2, 5), burrow[2][5], getTargetPositions(burrow[2][5]), getMoveCost(burrow[2][5]), 2), Amphipod(Position2D(3, 5), burrow[3][5], getTargetPositions(burrow[3][5]), getMoveCost(burrow[3][5]), 2), Amphipod(Position2D(2, 7), burrow[2][7], getTargetPositions(burrow[2][7]), getMoveCost(burrow[2][7]), 2), Amphipod(Position2D(3, 7), burrow[3][7], getTargetPositions(burrow[3][7]), getMoveCost(burrow[3][7]), 2), Amphipod(Position2D(2, 9), burrow[2][9], getTargetPositions(burrow[2][9]), getMoveCost(burrow[2][9]), 2), Amphipod(Position2D(3, 9), burrow[3][9], getTargetPositions(burrow[3][9]), getMoveCost(burrow[3][9]), 2), ) } fun getTargetPositions(name: Char): Pair<Position2D, Position2D> { return when (name) { 'A' -> Pair(Position2D(2, 3), Position2D(3, 3)) 'B' -> Pair(Position2D(2, 5), Position2D(3, 5)) 'C' -> Pair(Position2D(2, 7), Position2D(3, 7)) 'D' -> Pair(Position2D(2, 9), Position2D(3, 9)) else -> Pair(Position2D(0, 0), Position2D(0, 0)) } } fun getMoveCost(name: Char): Int { return when (name) { 'A' -> 1 'B' -> 10 'C' -> 100 'D' -> 1000 else -> 0 } } data class Position2D(val x: Int, val y: Int) data class Amphipod(val position: Position2D, val Name: Char, val targetPositions: Pair<Position2D, Position2D>, val moveCost: Int, var movesLeft: Int)
0
Kotlin
0
0
02484bd3bcb921094bc83368843773f7912fe757
2,086
advent_of_code_2021
MIT License
archive/691/solve.kt
daniellionel01
435,306,139
false
null
/* === #691 Long substring with many repetitions - Project Euler === Given a character string $s$, we define $L(k,s)$ to be the length of the longest substring of $s$ which appears at least $k$ times in $s$, or $0$ if such a substring does not exist. For example, $L(3,\text{“bbabcabcabcacba”})=4$ because of the three occurrences of the substring $\text{“abca”}$, and $L(2,\text{“bbabcabcabcacba”})=7$ because of the repeated substring $\text{“abcabca”}$. Note that the occurrences can overlap. Let $a_n$, $b_n$ and $c_n$ be the $0/1$ sequences defined by: $a_0 = 0$ $a_{2n} = a_{n}$ $a_{2n+1} = 1-a_{n}$ $b_n = \lfloor\frac{n+1}{\varphi}\rfloor - \lfloor\frac{n}{\varphi}\rfloor$ (where $\varphi$ is the golden ratio) $c_n = a_n + b_n - 2a_nb_n$ and $S_n$ the character string $c_0\ldots c_{n-1}$. You are given that $L(2,S_{10})=5$, $L(3,S_{10})=2$, $L(2,S_{100})=14$, $L(4,S_{100})=6$, $L(2,S_{1000})=86$, $L(3,S_{1000}) = 45$, $L(5,S_{1000}) = 31$, and that the sum of non-zero $L(k,S_{1000})$ for $k\ge 1$ is $2460$. Find the sum of non-zero $L(k,S_{5000000})$ for $k\ge 1$. Difficulty rating: 40% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
1,230
euler
MIT License
src/ad/kata/aoc2021/day12/CaveSystem.kt
andrej-dyck
433,401,789
false
{"Kotlin": 161613}
package ad.kata.aoc2021.day12 import ad.kata.aoc2021.PuzzleInput data class CaveSystem(private val connections: Graph<Cave>) { fun findPaths(): Paths<Cave> = connections.distinctPaths(start, end, canRevisit = { c, _ -> c.isLargeCave() }) fun findPathsWithSlightlyMoreTime(): Paths<Cave> = connections.distinctPaths(start, end, canRevisit = { c, p -> c.isLargeCave() || p.noSmallCaveVisitedTwice() }) private fun Path<Cave>.noSmallCaveVisitedTwice() = filter(Cave::isSmallCave).groupingBy { it }.eachCount().none { it.value > 1 } companion object { private val start = Cave("start") private val end = Cave("end") } } @JvmInline value class Cave(private val name: String) { fun isLargeCave() = name.all { it.isUpperCase() } fun isSmallCave() = !isLargeCave() override fun toString() = "Cave('$name')" } fun caveSystemFromInput(filename: String) = CaveSystem(unidirectionalGraphOf(PuzzleInput(filename).lines().toList()) { Cave(it) })
0
Kotlin
0
0
28d374fee4178e5944cb51114c1804d0c55d1052
1,038
advent-of-code-2021
MIT License
src/day11/Day11.kt
jpveilleux
573,221,738
false
{"Kotlin": 42252}
package day11 import utils.Setup val daySetup = Setup(11) data class Player (var worryLevel: Int) class Monkey ( var itemsList: MutableList<Int> = mutableListOf(), var operation: String = "", var test: Int = 0, var nextMonkey: MutableList<Int> = mutableListOf(), var inspectedItems: Int = 0 ) { fun getNextMonkeyId(playerWorryLevel: Int): Int { if (playerWorryLevel % test == 0) { return nextMonkey[0] } return nextMonkey[1] } fun readOperation (player: Player): Int { val splitOperation = operation.split(" ") val firstOperand = splitOperation[0] val operator = splitOperation[1] val secondOperand = splitOperation[2] val playerWorryLevel = player.worryLevel val a = when (firstOperand) { "old" -> playerWorryLevel else -> firstOperand.toInt() } val b = when (secondOperand) { "old" -> playerWorryLevel else -> secondOperand.toInt() } return when (operator) { "+" -> a + b "-" -> a - b "*" -> a * b else -> a / b } } fun inspectNextItem(player: Player, listOfMonkeys: MutableList<Monkey>) { for (i in 0 until itemsList.size) { var currentItem = itemsList[i] player.worryLevel = currentItem player.worryLevel = readOperation(player) player.worryLevel = player.worryLevel.floorDiv(3) currentItem = player.worryLevel val nextMonkeyId = getNextMonkeyId(player.worryLevel) listOfMonkeys[nextMonkeyId].itemsList.add(currentItem) //println("player worry level after operation: ${player.worryLevel}") } inspectedItems += itemsList.size itemsList.clear() } override fun toString(): String { return "Items: $itemsList \n" + "Operation: $operation \n" + "Test: $test \n" + "Next Monkey: $nextMonkey \n" + "Inspected items: $inspectedItems \n" } } fun getMonkeys(monkeysInfo: MutableList<MutableList<String>>): MutableList<Monkey> { val listOfMonkeys = mutableListOf<Monkey>() monkeysInfo.map {line -> val currentMonkey = Monkey() line.map{subLine -> if(subLine.startsWith("Starting")) { currentMonkey.itemsList = subLine.split(":")[1].trim().split(",").map {it.trim().toInt()}.toMutableList() } else if (subLine.startsWith("Operation")) { currentMonkey.operation = subLine.split("=")[1].trim() } else if (subLine.startsWith("Test")) { val testLine = subLine.split(" ") currentMonkey.test = testLine[testLine.lastIndex].toInt() } else { val nextMonkeyLine = subLine.split(" ") val nextMonkeyNumber = nextMonkeyLine[nextMonkeyLine.lastIndex].toInt() currentMonkey.nextMonkey.add(nextMonkeyNumber) } } listOfMonkeys.add(currentMonkey) } return listOfMonkeys } fun main () { fun part1(input: List<String>) { val monkeysInfo = mutableListOf<MutableList<String>>() val currentMonkeyInfo = mutableListOf<String>() val player = Player(0) val inputCleaned = input.filter {line -> line.isNotEmpty() && !line.startsWith("Monkey") } var count = 0; for (i in inputCleaned.indices) { val line = inputCleaned[i] count++ if (count == 5) { currentMonkeyInfo.add(line.trim()) val monkeyInfoArray = currentMonkeyInfo.toMutableList() monkeysInfo.add(monkeyInfoArray) currentMonkeyInfo.clear() count = 0 } else { currentMonkeyInfo.add(line.trim()) } } var monkeys = getMonkeys(monkeysInfo) repeat(20) { monkeys.map {monkey -> monkey.inspectNextItem(player, monkeys) //println(monkey) } } monkeys = monkeys.sortedWith(compareByDescending { it.inspectedItems }).toMutableList() println(monkeys[0].inspectedItems * monkeys[1].inspectedItems) //println(monkeys) } //part1(daySetup.controlInput) part1(daySetup.input) }
0
Kotlin
0
0
5ece22f84f2373272b26d77f92c92cf9c9e5f4df
4,680
jpadventofcode2022
Apache License 2.0
src/main/kotlin/Day9.kt
Walop
573,012,840
false
{"Kotlin": 53630}
import java.io.InputStream import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt data class Vec2( var x: Int, var y: Int ) { operator fun plus(other: Vec2): Vec2 { return Vec2(x + other.x, y + other.y) } operator fun minus(other: Vec2): Vec2 { return Vec2(x - other.x, y - other.y) } fun toUnits(): Vec2 { val uX = if (abs(x) > 1) x / 2 else x val uY = if (abs(y) > 1) y / 2 else y return Vec2(uX, uY) } fun length(): Float { return sqrt(x.toFloat().pow(2) + y.toFloat().pow(2)) } } class Day9 { companion object { fun process(input: InputStream?): Int { if (input == null) { throw Exception("Input missing") } var head = Vec2(0, 0) var prevHead = Vec2(0, 0) var tail = Vec2(0, 0) val visited = mutableSetOf(tail) input.bufferedReader() .useLines { lines -> lines.map { it.split(" ") } .map { Pair(it[0], it[1].toInt()) } .forEach { c -> //println("${head.x},${head.y}") val dir = when (c.first) { "U" -> Vec2(0, 1) "D" -> Vec2(0, -1) "L" -> Vec2(-1, 0) else -> Vec2(1, 0) } repeat(c.second) { head += dir if ((head - tail).length() > 1.5) { tail = prevHead visited.add(tail) } prevHead = head } } } return visited.size } fun process2(input: InputStream?): Int { if (input == null) { throw Exception("Input missing") } val rope = Array(10) { Vec2(0, 0) } val visited = mutableSetOf(rope[9]) input.bufferedReader() .useLines { lines -> lines.map { it.split(" ") } .map { Pair(it[0], it[1].toInt()) } .forEach { c -> val dir = when (c.first) { "U" -> Vec2(0, 1) "D" -> Vec2(0, -1) "L" -> Vec2(-1, 0) else -> Vec2(1, 0) } repeat(c.second) { rope[0] += dir for (i in 1..9) { val sectionVec = rope[i - 1] - rope[i] if (sectionVec.length() > 1.5) { rope[i] += sectionVec.toUnits() } } visited.add(rope[9]) } } } return visited.size } } }
0
Kotlin
0
0
7a13f6500da8cb2240972fbea780c0d8e0fde910
3,326
AdventOfCode2022
The Unlicense
src/day1/Day01.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
package day1 import readInput fun main() { fun part1(input: List<String>): Int { var mostAmountOfCaloriesByElf = 0 var currentCalories = 0 input.forEach { if (it.isBlank()) { currentCalories = 0 return@forEach } currentCalories += it.toInt() if (currentCalories > mostAmountOfCaloriesByElf) { mostAmountOfCaloriesByElf = currentCalories } } return mostAmountOfCaloriesByElf } fun part2(input: List<String>): Int { var currentCalories = 0 val listOfCaloriesByElf = mutableListOf<Int>() input.forEach { if (it.isBlank()) { listOfCaloriesByElf.add(currentCalories) currentCalories = 0 return@forEach } currentCalories += it.toInt() } return listOfCaloriesByElf.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day01_test") // #check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
1,233
AoC2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/GraphColoring.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* println("Test") Solution().test() class Solution { fun test() { //https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/ val vertice0 = Vertice(0) val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val graph = UndirectedGraph( listOf( vertice0, vertice1, vertice2, vertice3, vertice4 ) ) graph.addEdge(vertice0, vertice1) graph.addEdge(vertice0, vertice2) graph.addEdge(vertice1, vertice2) graph.addEdge(vertice1, vertice3) graph.addEdge(vertice2, vertice3) graph.addEdge(vertice3, vertice4) val coloring = GraphColoring() println(coloring.colorGraph(graph)) val vertice0_2 = Vertice(0) val vertice1_2 = Vertice(1) val vertice2_2 = Vertice(2) val vertice3_2 = Vertice(3) val vertice4_2 = Vertice(4) val graph2 = UndirectedGraph( listOf( vertice0_2, vertice1_2, vertice2_2, vertice3_2, vertice4_2 ) ) graph2.addEdge(vertice0_2, vertice1_2) graph2.addEdge(vertice0_2, vertice2_2) graph2.addEdge(vertice1_2, vertice2_2) graph2.addEdge(vertice1_2, vertice4_2) graph2.addEdge(vertice2_2, vertice4_2) graph2.addEdge(vertice3_2, vertice4_2) println(coloring.colorGraph(graph2)) } } data class Vertice(val value: Int, var color: Int = -1) data class UndirectedGraph(val vertices: List<Vertice>) { var adjList: MutableMap<Vertice, MutableList<Vertice>> = mutableMapOf() fun addEdge(first: Vertice, second: Vertice) { val firstList = adjList.getOrDefault(first, mutableListOf()) firstList.add(second) adjList[first] = firstList val secondList = adjList.getOrDefault(second, mutableListOf()) secondList.add(first) adjList[second] = secondList } } // https://www.geeksforgeeks.org/graph-coloring-set-2-greedy-algorithm/ class GraphColoring { fun colorGraph(graph: UndirectedGraph): Int { graph.vertices.forEach { it.color = -1 } /* for each vertice: find min color used by checking all neighbours (putting adj colors > -1 in TreeSet, and find first gap color) color vertice with found color update numColors with Math.max(numColors, curColor) return numColors + 1 (includes color 0) */ if (graph.vertices.isEmpty()) return 0 var numColors = 0 //1 // [0, -1, 1, -1, -1] graph.vertices.forEach { //O(V) val minColor = findMinColor(graph, it) // O(V+E) it.color = minColor println("Vertice ${it.value} -> ${it.color}") numColors = Math.max(numColors, minColor + 1) } // total: O(V^2 + E) return numColors } private fun findMinColor(graph: UndirectedGraph, vertice: Vertice): Int { var usedColors = TreeSet<Int>() graph.adjList[vertice]?.forEach { //O(E) if (it.color != -1) usedColors.add(it.color) } println(vertice) println(usedColors) if (usedColors.isEmpty()) return 0 var lastColor = -1 usedColors.forEach { //O(V) if (it != lastColor + 1) return lastColor + 1 lastColor = it } return usedColors.size } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
3,613
KotlinAlgs
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDeletionSize.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 944. Delete Columns to Make Sorted * @see <a href="https://leetcode.com/problems/delete-columns-to-make-sorted/">Source</a> */ fun interface MinDeletionSize { operator fun invoke(strs: Array<String>): Int } class MinDeletionSizeBruteForce : MinDeletionSize { override operator fun invoke(strs: Array<String>): Int { var count = 0 for (i in 0 until strs[0].length) { for (j in 1 until strs.size) { if (strs[j][i] < strs[j - 1][i]) { count++ break } } } return count } } class MinDeletionSizeFast : MinDeletionSize { override operator fun invoke(strs: Array<String>): Int { val len: Int = strs.size val wordLen: Int = strs[0].length var ans = 0 for (i in 0 until wordLen) { var prev: Char = strs[0][i] for (j in 1 until len) { val ch: Char = strs[j][i] if (ch < prev) { ans++ break } prev = ch } } return ans } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,801
kotlab
Apache License 2.0
src/main/kotlin/day2/Aoc.kt
widarlein
225,589,345
false
null
package day2 fun main(args: Array<String>) { if (args.size < 1) { println("Must provide input program") System.exit(0) } val inputProgram = args[0].split(",").map { it.toInt() }.toIntArray() val program = inputProgram.clone() val output = runProgram(program) println("Part 1 output: $output") val code = findNounAndVerb(19690720, inputProgram.clone()) println("Part 2 code: $code") } /* * Finds the first pair of noun and verb to produce an expected output from given program memory */ private fun findNounAndVerb(expectedOutput: Int, initMemory: IntArray): Int { // loop over all possible nouns and verbs for (noun in (0..99)) { for (verb in (0..99)) { val memory = initMemory.clone() memory[1] = noun memory[2] = verb val output = runProgram(memory) if (output == expectedOutput) { return 100 * noun + verb } } } // no pair of noun and verb found to produce output return -1 } private fun runProgram(memory: IntArray): Int { var pointer = 0 while (memory[pointer] != 99 || pointer > memory.size) { when(memory[pointer]) { 1 -> add(pointer + 1, pointer + 2, pointer + 3, memory) 2 -> multiply(pointer + 1, pointer + 2, pointer + 3, memory) else -> println("Unsupported Opcode found at position $pointer: ${memory[pointer]}") } pointer += 4 } if (pointer > memory.size) { println("Program ran out without exit opcode 99.") } //println("Execution ended. Program state:\n${memory.joinToString(",")}") return memory[0] } private fun add(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray) { memory[memory[resultPos]] = memory[memory[firstPos]] + memory[memory[secondPos]] } private fun multiply(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray) { memory[memory[resultPos]] = memory[memory[firstPos]] * memory[memory[secondPos]] }
0
Kotlin
0
0
b4977e4a97ad61177977b8eeb1dcf298067e8ab4
2,043
AdventOfCode2019
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumRookCaptures.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode private const val ROOK = 'R' private const val PAWN = 'p' private const val BISHOP = 'B' private const val BOARD_MAX_SIZE = 8 /** * 999. Available Captures for Rook * @see <a href="https://leetcode.com/problems/available-captures-for-rook/">Source</a> */ fun interface NumRookCaptures { operator fun invoke(board: Array<CharArray>): Int } /** * Straight Forward Solution * Time O(64) * Space O(1) */ class NumRookCapturesSF : NumRookCaptures { override operator fun invoke(board: Array<CharArray>): Int { var x0 = 0 var y0 = 0 var res = 0 for (i in 0 until BOARD_MAX_SIZE) { for (j in 0 until BOARD_MAX_SIZE) { if (board[i][j] == ROOK) { x0 = i y0 = j } } } for (d in arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1))) { var x = x0 + d[0] var y = y0 + d[1] while (x in 0 until BOARD_MAX_SIZE && 0 <= y && y < BOARD_MAX_SIZE) { if (board[x][y] == PAWN) res++ if (board[x][y] != '.') break x += d[0] y += d[1] } } return res } } /** * Runtime: O(n) * Memory: O(1) */ class NumRookCapturesSearch : NumRookCaptures { override operator fun invoke(board: Array<CharArray>): Int { for (i in board.indices) { for (j in board[i].indices) { if (board[i][j] == ROOK) { val twoSum = cap(board, i, j, 0, 1).plus(cap(board, i, j, 0, -1)) return twoSum.plus(cap(board, i, j, 1, 0).plus(cap(board, i, j, -1, 0))) } } } return 0 } private fun cap(b: Array<CharArray>, x: Int, y: Int, dx: Int, dy: Int): Int { var m = x var n = y while (b.isXRange(m) && b.isYRange(m, n) && b.isNotBishop(m, n)) { if (b[m][n] == PAWN) return 1 m += dx n += dy } return 0 } private fun Array<CharArray>.isXRange(x: Int): Boolean { return x >= 0 && x < this.size } private fun Array<CharArray>.isYRange(x: Int, y: Int): Boolean { return y >= 0 && y < this[x].size } private fun Array<CharArray>.isNotBishop(x: Int, y: Int): Boolean { return this[x][y] != BISHOP } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,065
kotlab
Apache License 2.0
src/main/kotlin/leetcode/Problem1801.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import java.util.* /** * https://leetcode.com/problems/number-of-orders-in-the-backlog/ */ class Problem1801 { fun getNumberOfBacklogOrders(orders: Array<IntArray>): Int { val buyMap = TreeMap<Int, Long> { a, b -> b.compareTo(a) } val sellMap = TreeMap<Int, Long> { a, b -> a.compareTo(b) } for ((price, amount, type) in orders) { if (type == 0) { // buy var remainingAmount = amount.toLong() while (sellMap.isNotEmpty() && sellMap.firstKey() <= price) { val count = sellMap[sellMap.firstKey()] ?: 0 if (count - remainingAmount <= 0) { remainingAmount -= count sellMap.pollFirstEntry() } else { sellMap[sellMap.firstKey()] = count - remainingAmount remainingAmount = 0 break } } if (remainingAmount > 0) { buyMap[price] = (buyMap[price] ?: 0) + remainingAmount } } else { // sell var remainingAmount = amount.toLong() while (buyMap.isNotEmpty() && buyMap.firstKey() >= price) { val count = buyMap[buyMap.firstKey()] ?: 0 if (count - remainingAmount <= 0) { remainingAmount -= count buyMap.pollFirstEntry() } else { buyMap[buyMap.firstKey()] = count - remainingAmount remainingAmount = 0 break } } if (remainingAmount > 0) { sellMap[price] = (sellMap[price] ?: 0) + remainingAmount } } } var answer = 0L for ((_, count) in buyMap) { answer = (answer + count) % 1_000_000_007 } for ((_, count) in sellMap) { answer = (answer + count) % 1_000_000_007 } return answer.toInt() } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
2,145
leetcode
MIT License
src/Day06.kt
Olivki
573,156,936
false
{"Kotlin": 11297}
fun main() { data class DataChunk(val chunk: String, val lastCharacter: Int) fun String.findUniqueDataChunk(chunkSize: Int): DataChunk = asSequence() .withIndex() .windowed(chunkSize) { chars -> val chunk = chars.joinToString(separator = "") { it.value.toString() } DataChunk(chunk, chars.last().index + 1) } .first { (chunk, _) -> chunk.toSet().size == chunk.length } fun part1(input: List<String>) = input.map { it.findUniqueDataChunk(4) } fun part2(input: List<String>) = input.map { it.findUniqueDataChunk(14) } val testInput = readTestInput("Day06") // p1 with(part1(testInput)) { check(this[0].lastCharacter == 7) check(this[1].lastCharacter == 5) check(this[2].lastCharacter == 6) check(this[3].lastCharacter == 10) check(this[4].lastCharacter == 11) } // p2 with(part2(testInput)) { check(this[0].lastCharacter == 19) check(this[1].lastCharacter == 23) check(this[2].lastCharacter == 23) check(this[3].lastCharacter == 29) check(this[4].lastCharacter == 26) } val input = readInput("Day06") println(part1(input).single().lastCharacter) println(part2(input).single().lastCharacter) }
0
Kotlin
0
1
51c408f62589eada3d8454740c9f6fc378e2d09b
1,288
aoc-2022
Apache License 2.0
src/leetcode_study_badge/dynamic_programming/Day2.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.dynamic_programming class Day2 { // https://leetcode.com/problems/climbing-stairs/ // Bottom up fun climbStairs(n: Int): Int { if (n <= 3) return n var one = 1 var two = 2 var result = one + two for (i in 3..n) { result = one + two one = two two = result } return result } // in place fun minCostClimbingStairs(cost: IntArray): Int { for (i in cost.size - 1 downTo 0) { if (i == cost.lastIndex || i == cost.lastIndex - 1) cost[i] += 0 else cost[i] += minOf(cost[i + 1], cost[i + 2]) } return minOf(cost[0], cost[1]) } // +dp fun minCost(cost: IntArray): Int { val n: Int = cost.size val dp = IntArray(n + 1) dp[n - 1] = cost[n - 1] for (i in n - 2 downTo 0) { dp[i] = cost[i] + minOf(dp[i + 1], dp[i + 2]) } return minOf(dp[0], dp[1]) } } fun main() { println(Day2().minCostClimbingStairs(intArrayOf(1, 100, 1, 1, 1, 100, 1, 1, 100, 1))) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,117
dsa-kotlin
MIT License
src/Day02.kt
punx120
573,421,386
false
{"Kotlin": 30825}
fun main() { fun score(opp: String, me:String) : Int { if (opp == "A") { if (me == "X") { return 3 } else if (me == "Y") { return 6 } else if (me == "Z") { return 0 } } else if (opp == "B") { if (me == "X") { return 0 } else if (me == "Y") { return 3 } else if (me == "Z") { return 6 } } else if (opp == "C") { if (me == "X") { return 6 } else if (me == "Y") { return 0 } else if (me == "Z") { return 3 } } throw Exception("Invalid combination ($opp, $me)") } fun moveScore(move: String) = when (move) { "X" -> 1 "A" -> 1 "Y" -> 2 "B" -> 2 "Z" -> 3 "C" -> 3 else -> throw Exception("Invalid move $move") } fun scoreFromResult(result: String) = when (result) { "X" -> 0 "Y" -> 3 "Z" -> 6 else -> throw Exception("Invalid move $result") } fun getMoveScoreForGivenResult(move: String, result: String) : Int { if (result == "X") { if (move == "A") { return moveScore("C") } else if (move == "B") { return moveScore("A") } else if (move == "C") { return moveScore("B") } } else if (result == "Y") { return moveScore(move) } else if (result == "Z") { if (move == "A") { return moveScore("B") } else if (move == "B") { return moveScore("C") } else if (move == "C") { return moveScore("A") } } throw Exception("Invalid result $result") } fun part1(input: List<String>): Int { var res = 0 for (row : String in input) { val parts = row.split(' ') res += score(parts[0], parts[1]) + moveScore(parts[1]) } return res } fun part2(input: List<String>): Int { var res = 0 for (row : String in input) { val parts = row.split(' ') res += scoreFromResult(parts[1]) + getMoveScoreForGivenResult(parts[0], parts[1]) } return res } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
eda0e2d6455dd8daa58ffc7292fc41d7411e1693
2,704
aoc-2022
Apache License 2.0
advent-of-code2016/src/main/kotlin/day21/Advent21.kt
REDNBLACK
128,669,137
false
null
package day21 import day21.Operation.Type.* import move import parseInput import reverseSubstring import rotate import splitToLines import swap /** --- Day 21: Scrambled Letters and Hash --- The computer system you're breaking into uses a weird scrambling function to store its passwords. It shouldn't be much trouble to create your own scrambled password so you can add it to the system; you just have to implement the scrambler. The scrambling function is a series of operations (the exact list is provided in your puzzle input). Starting with the password to be scrambled, apply each operation in succession to the string. The individual operations behave as follows: swap position X with position Y means that the letters at indexes X and Y (counting from 0) should be swapped. swap letter X with letter Y means that the letters X and Y should be swapped (regardless of where they appear in the string). rotate left/right X steps means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc. rotate based on position of letter X means that the whole string should be rotated to the right based on the index of letter X (counting from 0) as determined before this instruction does any rotations. Once the index is determined, rotate the string to the right one time, plus a number of times equal to that index, plus one additional time if the index was at least 4. reverse positions X through Y means that the span of letters at indexes X through Y (including the letters at X and Y) should be reversed in order. move position X to position Y means that the letter which is at index X should be removed from the string, then inserted such that it ends up at index Y. For example, suppose you start with abcde and perform the following operations: swap position 4 with position 0 swaps the first and last letters, producing the input for the next step, ebcda. swap letter d with letter b swaps the positions of d and b: edcba. reverse positions 0 through 4 causes the entire string to be reversed, producing abcde. rotate left 1 step shifts all letters left one position, causing the first letter to wrap to the end of the string: bcdea. move position 1 to position 4 removes the letter at position 1 (c), then inserts it at position 4 (the end of the string): bdeac. move position 3 to position 0 removes the letter at position 3 (a), then inserts it at position 0 (the front of the string): abdec. rotate based on position of letter b finds the index of letter b (1), then rotates the string right once plus a number of times equal to that index (2): ecabd. rotate based on position of letter d finds the index of letter d (4), then rotates the string right once, plus a number of times equal to that index, plus an additional time because the index was at least 4, for a total of 6 right rotations: decab. After these steps, the resulting scrambled password is <PASSWORD>. Now, you just need to generate a new scrambled password and you can access the system. Given the list of scrambling operations in your puzzle input, what is the result of scrambling abcdefgh? --- Part Two --- You scrambled the password correctly, but you discover that you can't actually modify the password file on the system. You'll need to un-scramble one of the existing passwords by reversing the scrambling process. What is the un-scrambled version of the scrambled password fbgdceah? */ fun main(args: Array<String>) { val test = """|swap position 4 with position 0 |swap letter d with letter b |reverse positions 0 through 4 |rotate left 1 step |move position 1 to position 4 |move position 3 to position 0 |rotate based on position of letter b |rotate based on position of letter d |""".trimMargin() val input = parseInput("day21-input.txt") println(scramble("abcde", test) == "decab") println(scramble("abcdefgh", input)) println(scramble("fbgdceah", input, true)) } fun scramble(string: String, operationsInput: String, reversed: Boolean = false) = parseOperations(operationsInput) .let { if (reversed) it.reversed() else it } .fold(string, { s, o -> when (o.type) { SWAP_POS -> { val (from, to) = o.argsAsInt() s.swap(from, to) } SWAP_LETTER -> { val (from, to) = o.argsAsString().map { s.indexOf(it) } s.swap(from, to) } ROTATE -> { val times = o.argsAsInt().first() s.rotate(times * (if (reversed) -1 else 1)) } ROTATE_BASED -> { val i = o.argsAsString().first().let { s.indexOf(it) } val times = when (reversed) { true -> i / 2 + (if (i % 2 == 1 || i == 0) 1 else 5) false -> -(1 + i + (if (i >= 4) 1 else 0)) } s.rotate(times) } REVERSE -> { val (from, to) = o.argsAsInt() s.reverseSubstring(from, to) } MOVE -> { val (from, to) = o.argsAsInt().let { if (reversed) it.reversed() else it } s.move(from, to) } } }) data class Operation(val type: Type, val args: List<Any>) { enum class Type { SWAP_POS, SWAP_LETTER, ROTATE, ROTATE_BASED, REVERSE, MOVE } fun argsAsInt() = args.map { it as Int } fun argsAsString() = args.map { it as String } } private fun parseOperations(input: String) = input.splitToLines() .map { fun String.indexes() = Regex("""(\d+)""").findAll(this) .map { it.groupValues.drop(1) } .toList() .flatMap { it.map(String::toInt) } fun String.letters() = split(" ").filter { it.length == 1 } when { it.startsWith("swap position") -> Operation(SWAP_POS, it.indexes()) it.startsWith("swap letter") -> Operation(SWAP_LETTER, it.letters()) it.startsWith("reverse") -> Operation(REVERSE, it.indexes()) it.startsWith("rotate based") -> Operation(ROTATE_BASED, it.letters()) it.startsWith("rotate") -> Operation( ROTATE, Regex("""rotate (left|right) (\d+) step""") .findAll(it) .map { it.groupValues.drop(1) } .toList() .flatMap { it } .let { listOf(if (it.first() == "left") it.last().toInt() else -it.last().toInt()) } ) it.startsWith("move") -> Operation(MOVE, it.indexes()) else -> throw IllegalArgumentException(it) } }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
7,051
courses
MIT License
src/main/kotlin/g0401_0500/s0450_delete_node_in_a_bst/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0401_0500.s0450_delete_node_in_a_bst // #Medium #Tree #Binary_Tree #Binary_Search_Tree #Data_Structure_II_Day_16_Tree // #2022_12_25_Time_257_ms_(84.62%)_Space_38.6_MB_(92.31%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun deleteNode(root: TreeNode?, key: Int): TreeNode? { if (root == null) return root // find the correct node if (key < root.`val`) { root.left = deleteNode(root.left, key) } else if (key > root.`val`) { root.right = deleteNode(root.right, key) } else { // case 1 - both children are null if (root.left == null && root.right == null) { return null } else if (root.left != null && root.right != null) { // case 2 - both children are NOT null val successor = minimum(root.right!!) // inorder successor root.right = deleteNode(root.right, successor) root.`val` = successor } else { // case 3 - only one of the child is null return root.left ?: root.right } } return root } private fun minimum(root: TreeNode): Int { var node = root while (node.left != null) { node = node.left!! } return node.`val` } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,534
LeetCode-in-Kotlin
MIT License
2020/day/13/bus.kt
mboos
318,232,614
false
{"Python": 45197, "Swift": 25305, "Kotlin": 3701}
/** * Solution to https://adventofcode.com/2020/day/13 */ import java.io.File fun gcf(a: Long, b: Long): Long { var tmp: Long var aa = a var bb = b while (bb != 0L) { tmp = aa % bb aa = bb bb = tmp } return aa } fun lcm(vals: List<Long>): Long { return vals.reduce{a, b -> a*b/gcf(a,b)} } fun main(args: Array<String>) { var input: String = args[0] var raw: String = File(input).readText() var secondLine: String = raw.split("\n")[1] // Part 1 var desiredDepartureTime: Long = raw.split("\n")[0].toLong() var waitTime = Long.MAX_VALUE var bestRoute: Long = 0 for (routeLabel in secondLine.split(",")) { if (routeLabel.equals("x")) { continue } var routeNum = routeLabel.toLong() var remainder = desiredDepartureTime % routeNum var potentialWaitTime: Long if (remainder > 0) { potentialWaitTime = routeNum - remainder } else { potentialWaitTime = 0 } if (potentialWaitTime < waitTime) { waitTime = potentialWaitTime bestRoute = routeNum } } println("Product of route num and wait time: ${bestRoute * waitTime}") // Part 2 var increment: Long var startTime = 0L while (true) { var failedYet: Boolean = false var goodNums: MutableList<Long> = ArrayList() for ((index, routeName) in secondLine.split(",").withIndex()) { if (routeName.equals("x")) { continue } var routeNum = routeName.toInt() if ((startTime + index) % routeNum != 0L) { failedYet = true } else { goodNums.add(routeNum.toLong()) } } if (!failedYet) { break } increment = lcm(goodNums) startTime += increment } println("Earliest timestamp: ${startTime}") }
0
Python
0
0
4477bb32c50b951b0a1be4850ed28a2c6f78e65d
1,752
advent-of-code
Apache License 2.0
src/Day06.kt
f1qwase
572,888,869
false
{"Kotlin": 33268}
private fun findUniqueSymbolsSequence(input: String, uniqueCount: Int): Int = input.windowed(uniqueCount) { it.toSet().size == uniqueCount }.indexOf(true) + uniqueCount fun main() { fun part1(input: List<String>): Int = findUniqueSymbolsSequence(input.single(), 4) fun part2(input: List<String>): Int = findUniqueSymbolsSequence(input.single(), 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 10) { part1(testInput) } val input = readInput("Day06") println(part1(input)) check(part2(testInput) == 29) { part2(testInput) } println(part2(input)) }
0
Kotlin
0
0
3fc7b74df8b6595d7cd48915c717905c4d124729
707
aoc-2022
Apache License 2.0
src/org/aoc2021/Day16.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day16 { interface Packet { val version: Int val typeId: Int fun sumSubPacketVersions(): Int fun evaluate(): Long } data class LiteralValuePacket( override val version: Int, override val typeId: Int, val value: Long, ) : Packet { override fun sumSubPacketVersions() = 0 override fun evaluate() = value } data class OperatorPacket( override val version: Int, override val typeId: Int, val subPackets: List<Packet>, ) : Packet { override fun sumSubPacketVersions() = subPackets.sumOf { p -> p.version + p.sumSubPacketVersions() } override fun evaluate() = when (typeId) { 0 -> subPackets.sumOf(Packet::evaluate) 1 -> subPackets.fold(1L) { p, packet -> p * packet.evaluate() } 2 -> subPackets.minOf(Packet::evaluate) 3 -> subPackets.maxOf(Packet::evaluate) 5 -> if (subPackets[0].evaluate() > subPackets[1].evaluate()) 1L else 0L 6 -> if (subPackets[0].evaluate() < subPackets[1].evaluate()) 1L else 0L 7 -> if (subPackets[0].evaluate() == subPackets[1].evaluate()) 1L else 0L else -> throw IllegalArgumentException("$typeId") } } private fun solvePart1(lines: List<String>): Int { val binary = hexToBinary(lines[0]) val outerPacket = parsePacket(binary).first return outerPacket.version + outerPacket.sumSubPacketVersions() } private fun solvePart2(lines: List<String>): Long { val binary = hexToBinary(lines[0]) val outerPacket = parsePacket(binary).first return outerPacket.evaluate() } private fun hexToBinary(line: String): String { return line.map { c -> val binary = c.toString().toInt(16).toString(2) if (binary.length == 4) { binary } else { "0".repeat(4 - (binary.length % 4)) + binary } }.joinToString(separator = "") } private fun parsePacket(binary: String, i: Int = 0): Pair<Packet, Int> { val version = binary.substring(i..i+2).toInt(2) val typeId = binary.substring(i+3..i+5).toInt(2) if (typeId == 4) { return parseLiteralValuePacket(binary, i, version, typeId) } return parseOperatorPacket(binary, i, version, typeId) } private fun parseLiteralValuePacket(binary: String, i: Int, version: Int, typeId: Int): Pair<LiteralValuePacket, Int> { var currentIndex = i + 6 var currentValue = 0L while (true) { currentValue = 16 * currentValue + binary.substring(currentIndex+1..currentIndex+4).toInt(2) if (binary[currentIndex] == '0') { break } currentIndex += 5 } val packet = LiteralValuePacket(version, typeId, currentValue) return packet to (currentIndex + 5) } private fun parseOperatorPacket(binary: String, i: Int, version: Int, typeId: Int): Pair<OperatorPacket, Int> { if (binary[i + 6] == '0') { val totalSubPacketLength = binary.substring(i+7..i+21).toInt(2) val subPackets = mutableListOf<Packet>() var currentIndex = i + 22 while (currentIndex - (i + 22) != totalSubPacketLength) { val (packet, nextPacketIndex) = parsePacket(binary, currentIndex) subPackets.add(packet) currentIndex = nextPacketIndex } return OperatorPacket(version, typeId, subPackets.toList()) to currentIndex } else { val numSubPackets = binary.substring(i+7..i+17).toInt(2) val subPackets = mutableListOf<Packet>() var currentIndex = i + 18 (1..numSubPackets).forEach { _ -> val (packet, nextPacketIndex) = parsePacket(binary, currentIndex) subPackets.add(packet) currentIndex = nextPacketIndex } return OperatorPacket(version, typeId, subPackets.toList()) to currentIndex } } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input16.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
4,536
advent-of-code-2021
The Unlicense
day3/src/main/kotlin/part1.kt
Lysoun
725,939,287
false
{"Kotlin": 16038, "OCaml": 224}
package day3 import java.io.File fun isSymbol(char: Char): Boolean = !char.isDigit() && char != '.' fun isNextToASymbol(position: Pair<Int, Int>, engineSchematic: Map<Pair<Int, Int>, Char>): Boolean { val neighbourPositions = listOf( position.first to position.second -1, position.first + 1 to position.second -1, position.first - 1 to position.second -1, position.first to position.second +1, position.first + 1 to position.second +1, position.first - 1 to position.second +1, position.first + 1 to position.second, position.first - 1 to position.second ) return neighbourPositions.mapNotNull { engineSchematic[it] }.any { isSymbol(it) } } fun main() { val inputFileName = "day3/input.txt" val engineSchematic: MutableMap<Pair<Int, Int>, Char> = mutableMapOf() val numbers: MutableList<Pair<Int, List<Pair<Int, Int>>>> = mutableListOf() var lineNumber = 0 File(inputFileName).forEachLine { var number = "" var digitsIndices = mutableListOf<Pair<Int, Int>>() it.forEachIndexed { index, c -> engineSchematic[lineNumber to index] = c if (c.isDigit()) { number += c.toString() digitsIndices.add(lineNumber to index) } else if(number != "") { numbers.add( number.toInt() to digitsIndices ) number = "" digitsIndices = mutableListOf() } } if(number != "") { numbers.add( number.toInt() to digitsIndices ) number = "" digitsIndices = mutableListOf() } ++lineNumber } println(numbers.filter { val nextToASymbol = it.second.any { digitsIndices -> isNextToASymbol(digitsIndices, engineSchematic) } println("number: ${it.first} indices: ${it.second} nextToASymbol: $nextToASymbol") nextToASymbol }.sumOf { it.first }) }
0
Kotlin
0
0
96ecbcef1bd29a97f2230457f4e233ca6b1cc108
2,034
advent-of-code-2023
MIT License
src/main/kotlin/days/aoc2022/Day15.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day import util.Point2d import kotlin.math.abs import kotlin.math.min import kotlin.math.max import kotlin.time.ExperimentalTime import kotlin.time.TimeMark import kotlin.time.TimeSource class Day15 : Day(2022, 15) { override fun partOne(): Any { return countCoveredBeaconPositionsForRow(inputList, 2000000) } override fun partTwo(): Any { return calculateTuningFrequencyOfBeacon(inputList, 4000000) } // Sensor at x=2432913, y=3069935: closest beacon is at x=2475123, y=3089709 fun countCoveredBeaconPositionsForRow(input: List<String>, rowToAnalyze: Int): Int { val sensors = input.map { parseInputLine(it) } var minX = Int.MAX_VALUE var minY = Int.MAX_VALUE var maxX = Int.MIN_VALUE var maxY = Int.MIN_VALUE sensors.forEach { sensor -> if (sensor.location.x < minX || sensor.nearestBeacon.x < minX) { minX = min(sensor.location.x, sensor.nearestBeacon.x) } if (sensor.location.y < minY || sensor.nearestBeacon.y < minY) { minY = min(sensor.location.y, sensor.nearestBeacon.y) } if (sensor.location.x > maxX || sensor.nearestBeacon.x > maxX) { maxX = max(sensor.location.x, sensor.nearestBeacon.x) } if (sensor.location.y > maxY || sensor.nearestBeacon.y > maxY) { maxY = max(sensor.location.y, sensor.nearestBeacon.y) } minX = min(sensor.location.x - sensor.distanceToNearestBeacon, minX) maxX = max(sensor.location.x + sensor.distanceToNearestBeacon, maxX) } val coveredRange = mutableSetOf<Int>() sensors.forEach { sensor -> // determine if this sensor's area intersects the line we're interested in if (rowToAnalyze in (sensor.location.y - sensor.distanceToNearestBeacon)..(sensor.location.y + sensor.distanceToNearestBeacon)) { val range = sensor.distanceToNearestBeacon - abs(sensor.location.y - rowToAnalyze) coveredRange.addAll((sensor.location.x - range)..(sensor.location.x + range)) } } return coveredRange.size - sensors.map { it.nearestBeacon }.distinct().count { it.y == rowToAnalyze && it.x in coveredRange } } private fun parseInputLine(line: String): Sensor { return Regex("Sensor at x=(\\d+), y=(\\d+): closest beacon is at x=(-?)(\\d+), y=(-?)(\\d+)") .matchEntire(line)?.destructured?.let { (x, y, signX, beaconX, signY, beaconY) -> Sensor(Point2d(x.toInt(), y.toInt()), Point2d((if (signX == "-") beaconX.toInt().unaryMinus() else beaconX.toInt()), (if (signY == "-") beaconY.toInt().unaryMinus() else beaconY.toInt()))) } ?: throw IllegalStateException() } fun calculateTuningFrequencyOfBeacon(input: List<String>, maxExtent: Int): Long { val sensors = input.map { parseInputLine(it) } sensors.forEach { sensor -> for (x in 0..sensor.distanceToNearestBeacon + 1) { val pointsToTest = listOf( Point2d(sensor.location.x + x, sensor.location.y + (sensor.distanceToNearestBeacon + 1) - x), Point2d(sensor.location.x - x, sensor.location.y + (sensor.distanceToNearestBeacon + 1) - x), Point2d(sensor.location.x + x, sensor.location.y - (sensor.distanceToNearestBeacon + 1) - x), Point2d(sensor.location.x - x, sensor.location.y - (sensor.distanceToNearestBeacon + 1) - x), ) pointsToTest.filter { it.x in 0..maxExtent && it.y in 0..maxExtent }.forEach { point -> if (!sensors.any { point.distanceTo(it.location) <= it.distanceToNearestBeacon }) { return point.x * 4000000L + point.y } } } } throw IllegalStateException() } data class Sensor(val location: Point2d, val nearestBeacon: Point2d) { val distanceToNearestBeacon = location.distanceTo(nearestBeacon) } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
4,247
Advent-Of-Code
Creative Commons Zero v1.0 Universal
solutions/src/solutions/y19/day 24.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.solutions.y19.d24 import helpers.* import kotlin.collections.* import grid.entityGrid private fun bio1(s: Set<Point>): Int { var b = 0 var p = 1 for (i in (0..4)) for (j in (0..4)) { if (i toP j in s) b += p p *= 2 } return b } private fun part1(data: Data) { val bios = mutableSetOf<Int>() var current = data while (true) { for (i in (0..4)) { for (j in (0..4)) { if (i toP j in current) print('#') else print('.') } println() } println() val bio = bio1(current) if( bio in bios){ println(bio) return } bios.add(bio) val counts = current.flatMap { it.getQuadNeighbours() }.groupingBy { it }.eachCount() current = counts.filter { (p, c) -> p in (0 toP 0) toB (4 toP 4) && if (p in current) { c == 1 } else{ c == 1 || c == 2 } }.map{(p,_)->p}.toSet() } } private val empty = setOf<Point>() private fun part2(data: Data) { var layers = mutableMapOf(0 to data) repeat(200){ val leftO = layers.map{(k,v) -> k to v.count{it.y == 0}}.toMap() val rightO = layers.map{(k,v) -> k to v.count{it.y == 4}}.toMap() val upO = layers.map{(k,v) -> k to v.count{it.x == 0}}.toMap() val downO = layers.map{(k,v) -> k to v.count{it.x == 4}}.toMap() for(l in layers.keys.flatMap { listOf(it-1, it+1) }.filter { it !in layers }){ layers[l] = empty } layers = layers.map{(i,current) -> val counts = current.flatMap { it.getQuadNeighbours()} .groupingBy { it }.eachCount().toMutableMap() counts.merge(1 toP 2, upO[i+1]?:0, Int::plus) counts.merge(3 toP 2, downO[i+1]?:0, Int::plus) counts.merge(2 toP 1, leftO[i+1]?:0, Int::plus) counts.merge(2 toP 3, rightO[i+1]?:0, Int::plus) for(c in 0..4){ counts.merge(0 toP c, if(layers[i-1]?.contains(1 toP 2) == true) 1 else 0, Int::plus) counts.merge(c toP 0, if(layers[i-1]?.contains(2 toP 1) == true) 1 else 0, Int::plus) counts.merge(4 toP c, if(layers[i-1]?.contains(3 toP 2) == true) 1 else 0, Int::plus) counts.merge(c toP 4, if(layers[i-1]?.contains(2 toP 3) == true) 1 else 0, Int::plus) } counts[2 toP 2] = 0 i to counts.filter { (p, c) -> p in (0 toP 0) toB (4 toP 4) && if (p in current) { c == 1 } else{ c == 1 || c == 2 } }.map{(p,_)->p}.toSet() }.filter{(_,v) -> v.isNotEmpty()}.toMap().toMutableMap() /* println("step ${it+1}") println() for((i, l) in layers.map{it}.sortedBy { it.key }){ println("Depth $i:") for (i in (0..4)) { for (j in (0..4)) { if (i toP j in l) print('#') else print('.') } println() } }*/ } println(layers.map{(_,v)->v.size}.sum()) } typealias Data = Set<Point> fun main() { val data: Data = getLines(2019_24).map { it.map { it } }.entityGrid { it == '#' }.points //part1(data) part2(data) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
2,893
AdventOfCodeSolutions
MIT License
src/commonMain/kotlin/com/github/knok16/regrunch/dfa/DFAIntersection.kt
knok16
593,302,527
false
null
package com.github.knok16.regrunch.dfa import com.github.knok16.regrunch.State fun <A, S1, S2> intersection(dfa1: DFA<A, S1>, dfa2: DFA<A, S2>): DFA<A, State> { if (dfa1.alphabet != dfa2.alphabet) throw IllegalArgumentException("DFAs have different alphabets") val alphabet = dfa1.alphabet val builder = DFABuilder(alphabet) val correspondence = HashMap<Pair<S1, S2>, State>() correspondence[dfa1.startState to dfa2.startState] = builder.startState fun dfs(state1: S1, state2: S2, state: State) { for (symbol in alphabet) { val to1 = dfa1.transition(state1, symbol) val to2 = dfa2.transition(state2, symbol) val key = to1 to to2 val to = if (key in correspondence) { correspondence.getValue(key) } else { val r = builder.newState() correspondence[key] = r dfs(to1, to2, r) r } builder.transition(state, to, symbol) } } dfs(dfa1.startState, dfa2.startState, builder.startState) correspondence .filterKeys { (s1, s2) -> s1 in dfa1.finalStates && s2 in dfa2.finalStates } .values .forEach(builder::markAsFinal) return builder.build() } infix fun <A, S1, S2> DFA<A, S1>.intersect(another: DFA<A, S2>): DFA<A, State> = intersection(this, another)
0
Kotlin
1
11
87c6a7ab9f6db4e48e9d3caf88b278c59297ed7b
1,395
regrunch
MIT License
src/main/kotlin/de/startat/aoc2023/Day8.kt
Arondc
727,396,875
false
{"Kotlin": 194620}
package de.startat.aoc2023 import java.math.BigInteger import kotlin.math.sqrt class Day8 { data class WastelandMap(val map : Map<String,Pair<String,String>>) { operator fun get(currentNode: String): Pair<String, String> = map[currentNode]!! } private val mapLineRegex = Regex("(\\w*) = \\((\\w*), (\\w*)\\)") data class Instructions(val instructions : List<String>) { private var currentInstruction = 0 fun next() : String { val instruction = instructions[currentInstruction] currentInstruction += 1 currentInstruction %= instructions.size return instruction } } data class NavigationTools(val map : WastelandMap, val instructions : Instructions) class Journey(private val navigationTools: NavigationTools, private val startingNode: String = "AAA", private val targetNode: String = "ZZZ"){ var currentNode = startingNode var destinationReached = false var stepCounter = 0 fun step(){ if(destinationReached) return val nextInstruction = navigationTools.instructions.next() val nextDecision = navigationTools.map[currentNode] val nextNode = when(nextInstruction){ "L" -> nextDecision.first "R" -> nextDecision.second else -> throw RuntimeException("We're lost") } //println("Taking a step $nextInstruction from $currentNode to $nextNode") currentNode = nextNode stepCounter++ if(currentNode == targetNode){ println("$stepCounter from $startingNode to $targetNode") destinationReached = true } } } fun star1(){ val tools : NavigationTools = parse(day8input) val journey = Journey(tools) while(!journey.destinationReached){ journey.step() } println("The journey took ${journey.stepCounter} steps") } fun star2(){ //step1() /* Result of step1 12169 from SLA to LQZ 12169 from LQZ to LQZ 13301 from AAA to ZZZ 13301 from ZZZ to ZZZ 14999 from XJA to PDZ 14999 from PDZ to PDZ 16697 from JNA to PBZ 16697 from PBZ to PBZ 17263 from PTA to SNZ 17263 from SNZ to SNZ 18961 from BGA to LCZ 18961 from LCZ to LCZ suspicious :D */ val pathLengths = listOf( BigInteger.valueOf(12169), BigInteger.valueOf(13301), BigInteger.valueOf(14999), BigInteger.valueOf(16697), BigInteger.valueOf(17263), BigInteger.valueOf(18961)) pathLengths.map { p -> Pair(p,primeFactors(p)) }.forEach{(p,primes) -> println("$p $primes") } /* 12169 [43, 283] 13301 [47, 283] 14999 [53, 283] 16697 [59, 283] 17263 [61, 283] 18961 [67, 283] */ val kgv = BigInteger.valueOf(43) * BigInteger.valueOf(47) * BigInteger.valueOf(53) * BigInteger.valueOf(59) * BigInteger.valueOf( 61 ) * BigInteger.valueOf(67) * BigInteger.valueOf(283) println(kgv) } val two = BigInteger.valueOf(2) private fun primeFactors(number: BigInteger): ArrayList<BigInteger> { // Array that contains all the prime factors of given number. val arr: ArrayList<BigInteger> = arrayListOf() var n = number // At first check for divisibility by 2. add it in arr till it is divisible while (n.mod(two) == BigInteger.ZERO) { arr.add(two) n /= two } val squareRoot = sqrt(n.toDouble()).toInt() // Run loop from 3 to square root of n. Check for divisibility by i. Add i in arr till it is divisible by i. for (i in 3L..squareRoot step 2) { val bi = BigInteger.valueOf(i) while (n.mod(bi) == BigInteger.ZERO) { arr.add(bi) n /= bi } } // If n is a prime number greater than 2. if (n > two) { arr.add(n) } return arr } private fun step1() { val baseTools: NavigationTools = parse(day8input) val allStartingNodes = baseTools.map.map.keys.filter { it.endsWith("A") }.toList() val allTargetNodes = baseTools.map.map.keys.filter { it.endsWith("Z") } var allJourneys = mutableListOf<Journey>() for (start in allStartingNodes) { for (target in allTargetNodes) { allJourneys.add( Journey( NavigationTools(baseTools.map.copy(), baseTools.instructions.copy()), start, target ) ) } } for (start in allTargetNodes) { for (target in allTargetNodes) { allJourneys.add( Journey( NavigationTools(baseTools.map.copy(), baseTools.instructions.copy()), start, target ) ) } } while (allJourneys.any { j -> !j.destinationReached }) { allJourneys.forEach { j -> j.step() } allJourneys = allJourneys.filter { !it.destinationReached }.toMutableList() } } private fun parse(input: String): NavigationTools { val instructions = Instructions(input.lines()[0].split("").filter { it.isNotEmpty() }.toList()) val mapEntries = input.lines().asSequence().drop(2).map { l -> mapLineRegex.find(l) } .associateBy({ it!!.groupValues[1] }, { Pair(it!!.groupValues[2], it.groupValues[3]) }) val wastelandMap = WastelandMap(mapEntries) return NavigationTools(wastelandMap, instructions) } val day8testInput1 = """ RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ) """.trimIndent() val day8testInput2 = """ LLR AAA = (BBB, BBB) BBB = (AAA, ZZZ) ZZZ = (ZZZ, ZZZ) """.trimIndent() val day8testInput3 = """ LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX) """.trimIndent() val day8input = """ LRRLRRRLRRLLLRLLRRLRRLLRRRLRRLLRLRRRLRLRRLRLRRRLRLRLRRLLRLRLRRLRRRLRRRLRRRLRLRRLLLLRLLRLLRRLRRRLLLRLRRRLRLRRRLRLRRLRRRLRRRLRLRLLRRRLLRLLRLRLRLRLLRRLRRLRRRLRRLRLRLRLRLRRLRRRLLRRRLLRLLLRRRLLRRRLRRRLRRLRLRRLRLLRRLLRRLRLRLRRLRLRRLLRRRLLRRRLLRLRRRLRLRRRLRLRRRLRRRLRRLRRLRRLLRRRLRRRLLLRRRR RGT = (HDG, QJV) QDM = (GPB, SXG) DJN = (TQD, BQN) QGG = (GGS, PTC) FJP = (MPB, HFP) KNB = (QHC, XBQ) RGR = (LSQ, LJV) HDP = (RLT, LRK) DBQ = (KTM, MPJ) QSG = (QVF, QVF) JKR = (XTK, RQB) BJH = (VKC, SML) LRF = (NPJ, HKK) JRD = (BQX, LGK) HVD = (CJP, TLM) VCG = (JMS, RJB) PCT = (KJC, RCQ) DRK = (PTR, FSH) BJN = (GVD, XXN) CXL = (FMB, NKM) TVM = (TTX, RCG) PTP = (KQQ, XLR) CKX = (VKR, RDH) TCP = (TPX, BSB) KSC = (JFL, CHL) DTF = (BTQ, TTQ) GFQ = (HKK, NPJ) BKD = (CXB, JSB) DJB = (TMG, DDQ) CQV = (SSX, DFT) BPC = (KNR, CGF) KLT = (BMF, XQC) NLB = (DBD, VCL) HJS = (FXK, FLB) PSL = (PBC, XFX) LVL = (JFD, RJD) JMX = (CGG, RRL) TTQ = (XVC, RCT) NLG = (FXK, FLB) LCD = (JSB, CXB) HVR = (CRV, HHM) HGV = (VCG, JDT) LND = (TTL, QCH) CSX = (DHS, JLB) BRJ = (BCT, XFS) XVN = (RDH, VKR) HQB = (BVD, GPC) PGP = (CFB, HQL) NFB = (BDX, JDK) HJK = (VVX, HTP) KKB = (NSF, GPP) JDV = (XJG, FDR) VGC = (HFV, JMT) BBG = (GTF, KTP) HTB = (BTC, KKC) KPL = (MXJ, MBN) NHD = (GCT, TGP) DMP = (KRH, SPM) LRB = (GNP, GGB) BGA = (MPB, HFP) PBZ = (KXQ, CKP) BQF = (LJC, VGC) KKC = (DJB, MCS) RRL = (QCK, RKN) PDZ = (RGF, BHL) SLA = (BCD, VJK) XRC = (SKL, VBP) HHM = (HSJ, NTR) BNP = (GPP, NSF) GHM = (HLC, KQK) LMV = (VTS, NFQ) QKF = (JNG, THN) PCG = (HSQ, DMP) CKG = (XSX, RDF) RMV = (FQL, HJL) LPG = (RJD, JFD) HFJ = (VQX, LQZ) QRF = (BCR, VSV) JSR = (BJJ, DVJ) TKS = (KTP, GTF) JNG = (DJD, XLM) XDG = (JKR, MRR) PFB = (QLT, PBD) NTR = (HBV, NRX) NMN = (BDX, JDK) MGP = (QMT, VLG) PTA = (LSP, TXX) CRK = (CJP, TLM) NVL = (STQ, QFH) VCL = (XFD, MGN) LJM = (VJH, NXV) GCJ = (RFS, QLN) NSF = (TKV, LKQ) PQN = (QHC, XBQ) GHK = (FNT, LCX) SFK = (FQL, HJL) FNX = (VXK, BJN) SSX = (MGK, KRX) FSH = (FNB, QFL) XFS = (BCK, CKG) VLQ = (XJV, HLM) JLB = (MMR, HMQ) GXX = (HLN, SGX) PKX = (QKF, SHQ) VND = (CDN, VVH) HJG = (FXR, VDR) GGR = (QRF, JMB) BQG = (CRV, HHM) RFS = (BHN, MNL) CSK = (DCX, VXG) RSL = (XCG, JGV) KRH = (CKX, XVN) VBP = (NLF, TVM) AAA = (MQQ, VHH) BVX = (LPG, LVL) QCG = (JKJ, CDR) JMQ = (HLR, GGT) NLF = (RCG, TTX) CXB = (NLG, HJS) VXG = (SDN, FCJ) XFT = (GNP, GGB) SST = (GGS, PTC) NNK = (PTD, HPF) RKN = (XVF, MMX) TGP = (SSN, MRT) TSR = (SFK, RMV) GBL = (NKQ, KVH) NKJ = (CGM, TCP) KVH = (VTK, GKV) VBB = (DXX, JVB) KGC = (HMK, TFL) PNL = (QLT, PBD) TNG = (QSG, TPL) HCV = (KVR, PKK) RBB = (TKG, CQK) BJJ = (GCN, PLQ) JRF = (DHC, XCQ) FLJ = (CKP, KXQ) KVR = (DJS, NKJ) HGT = (KVX, LTP) MGN = (JDS, LNS) FRC = (QLM, FHJ) MBN = (TRQ, MRD) TMG = (CTD, SFH) TNT = (JDG, HGV) DXP = (SSX, DFT) VVD = (JXJ, PGP) CHL = (XSL, SNZ) CGS = (GFQ, LRF) BHL = (FNQ, HFD) XHF = (NHD, PQC) PMH = (CNS, SVM) VKR = (TBT, TLT) LLK = (TQD, BQN) LVJ = (PDD, LML) JPB = (PRK, VCV) HSJ = (HBV, NRX) VJH = (DTL, BRL) SNJ = (DXP, CQV) HQL = (KDL, QFN) XHM = (HVG, ZZZ) RDX = (KTM, MPJ) MQQ = (LSC, DGG) TMM = (GMQ, RTL) JKP = (LRF, GFQ) TKG = (BDN, BDN) FBJ = (HLR, GGT) PTD = (LMV, QBR) FMB = (DQT, RRH) TTX = (LVJ, FXX) BXL = (BTQ, TTQ) QMV = (GND, FGG) HFD = (TBQ, VVD) NFQ = (PMH, DMM) RTH = (TPG, VDP) VHH = (DGG, LSC) HLN = (SPP, SPP) XQD = (PNL, PFB) GVD = (BPC, JJG) XRN = (DHJ, LBD) GNP = (NRC, NRC) JLC = (JHB, DRK) LGK = (BSK, BRV) BSB = (MBM, XHF) PBJ = (FRC, RFH) DRH = (VMR, XVK) RDF = (BHV, NGM) MMR = (HGD, PBJ) RGF = (HFD, FNQ) HTR = (RCQ, KJC) NGM = (FJP, LCZ) PJF = (QKF, SHQ) BCK = (XSX, XSX) PBD = (SXM, HTT) VCV = (GRD, VVT) TFL = (CCX, HQB) THT = (NXX, TSR) JMS = (RCF, XRC) FKG = (XRN, PHG) TBQ = (PGP, JXJ) SML = (TCH, DPF) RJB = (RCF, XRC) KJC = (LND, JNR) HPT = (DLM, MVH) NKM = (DQT, RRH) JSJ = (QFH, STQ) KJJ = (XXT, DBC) FGG = (HPT, GMM) RFH = (QLM, FHJ) TLM = (DKN, QGH) MJV = (QSG, TPL) DHG = (RGT, CVS) BVB = (QLJ, SNR) RMH = (JKR, MRR) XFX = (SNJ, QBD) LNS = (SFQ, GGR) QJV = (LRB, XFT) BHV = (FJP, FJP) JMT = (BJM, NPC) BDN = (JFL, JFL) CHC = (CXL, SXC) VBN = (VBB, CFM) SFQ = (QRF, JMB) XXN = (JJG, BPC) MCS = (TMG, DDQ) CFV = (DHG, NKS) FXK = (JSR, GLR) JMB = (VSV, BCR) VVT = (LST, GCJ) VRL = (DJN, LLK) XLB = (FGJ, PGB) JVC = (XXT, DBC) VQX = (BCD, VJK) DVJ = (GCN, PLQ) BTQ = (RCT, XVC) LCX = (JHK, KPL) FSD = (NNC, XLX) TSQ = (FKM, HFJ) HGD = (RFH, FRC) HJL = (JDV, LNV) FSB = (DBD, VCL) DCX = (SDN, FCJ) BHH = (JPK, GVQ) JHB = (PTR, FSH) THP = (SXC, CXL) LRK = (QCT, FPT) PTC = (LMF, DLF) DHS = (HMQ, MMR) GDK = (SNR, QLJ) CNJ = (JKJ, CDR) SBM = (BCT, XFS) GJP = (RJK, DDX) DFT = (KRX, MGK) XBQ = (BNP, KKB) FGJ = (VRL, CKV) QVF = (XTM, XTM) VJK = (BFB, CKT) VJX = (BKD, LCD) KQK = (GBL, HPK) KKX = (BDC, SKC) CRV = (HSJ, NTR) JNR = (QCH, TTL) HTG = (NQK, GJP) QLN = (MNL, BHN) GMB = (VVX, HTP) JDG = (JDT, VCG) QLT = (HTT, SXM) CLK = (VJB, SRH) GSX = (XKX, RSL) MQX = (RTH, LPL) ZZZ = (VHH, MQQ) PKK = (DJS, NKJ) MJT = (MQX, HTF) GLT = (TCD, HXV) PQX = (TGQ, JBF) VSX = (LTP, KVX) FSV = (FKG, NLC) FKR = (CQD, JPR) CKT = (RDX, DBQ) JFD = (TKS, BBG) CNM = (TBH, XRF) PBC = (SNJ, QBD) MRT = (QCG, CNJ) RCQ = (JNR, LND) JJG = (KNR, CGF) CFP = (JVT, GSX) BTG = (SBM, BRJ) BJM = (CRK, HVD) XVK = (CDS, BQF) BCT = (BCK, CKG) LST = (RFS, QLN) DNM = (VMR, XVK) GPB = (GNX, DJV) FDR = (FTG, LFQ) LCZ = (HFP, MPB) XJV = (FCP, JHV) HQC = (TRG, SCP) RMD = (QMV, NNH) SRH = (FLL, QKV) QBD = (CQV, DXP) RRH = (NCB, TSQ) XVF = (NFB, NMN) QMT = (GLT, NTS) GBX = (TKG, CQK) MFP = (TLH, QXD) XKG = (MHN, NLR) HQH = (HPF, PTD) LLR = (CNR, CRF) LSP = (SVQ, VJX) HSH = (LRK, RLT) TTL = (FKR, QMF) CFB = (KDL, QFN) SXG = (GNX, DJV) LTP = (KJJ, JVC) HSQ = (SPM, KRH) SHG = (DRH, DNM) DHJ = (QXR, GHK) GGK = (PRK, VCV) TRG = (PJN, CFV) TTF = (LJV, LSQ) VVH = (HSH, HDP) QXR = (FNT, LCX) DTL = (FSV, VQV) KVX = (JVC, KJJ) HLR = (BTG, MKN) XCG = (QTJ, HTQ) LML = (JMQ, FBJ) FMS = (XTM, VXJ) CTD = (JHQ, XLB) TCD = (CSK, GLS) MRR = (RQB, XTK) SSN = (CNJ, QCG) VLG = (NTS, GLT) JDT = (JMS, RJB) TPJ = (XFX, PBC) PDD = (FBJ, JMQ) QLJ = (NVL, JSJ) TVX = (JPB, GGK) QCT = (GBX, RBB) GMM = (DLM, MVH) RLT = (QCT, FPT) PFH = (HTG, DNF) DQN = (XCQ, DHC) XQC = (QJQ, JLC) QCH = (FKR, QMF) GMQ = (KPJ, RTF) HVJ = (QMV, NNH) VDP = (TVX, VFB) NXV = (DTL, BRL) JHK = (MXJ, MBN) JPK = (GQN, MFP) SSH = (KQK, HLC) FNB = (GPS, LLR) HTP = (SPG, CSX) HHN = (DNF, HTG) QJQ = (JHB, DRK) PFC = (KRJ, JLV) HFP = (JRD, MMT) HGC = (QCJ, CXG) KLG = (BVX, QSM) LHG = (HLM, XJV) CGG = (QCK, RKN) XVC = (CGS, JKP) FCJ = (TMM, MBL) KLC = (CDN, VVH) CRF = (LVG, FNX) PBP = (GSX, JVT) GLS = (DCX, VXG) DJD = (QGG, SST) BJV = (DMP, HSQ) MNL = (JSG, LNC) DNF = (NQK, GJP) NLR = (SSH, GHM) HSP = (JBF, TGQ) NRX = (DTX, CJK) VVX = (CSX, SPG) LSC = (DCL, QBB) VXJ = (FLJ, PBZ) CDR = (NXN, NMT) SGM = (NXV, VJH) XSX = (BHV, BHV) MGK = (FXG, XTG) VPC = (SKC, BDC) HBV = (CJK, DTX) RQB = (PCT, HTR) FXR = (HKP, LVP) BRL = (FSV, VQV) VXK = (GVD, XXN) SDN = (MBL, TMM) FCP = (HXD, SHG) XTG = (KLT, SPX) LBD = (GHK, QXR) JHQ = (FGJ, PGB) XXT = (KNB, PQN) VKC = (TCH, DPF) GQN = (QXD, TLH) HLM = (JHV, FCP) JDK = (TTF, RGR) VTS = (PMH, DMM) VMR = (CDS, BQF) XJA = (BHL, RGF) MMS = (NLR, MHN) DPF = (PQX, HSP) NNH = (FGG, GND) JSB = (NLG, HJS) XLR = (GMB, HJK) RCF = (VBP, SKL) JPD = (HTF, MQX) CJP = (DKN, QGH) BLC = (HGV, JDG) FTG = (PSL, TPJ) JDS = (SFQ, GGR) FQL = (JDV, LNV) JBF = (CHC, THP) HVG = (MQQ, VHH) LKQ = (NLX, HHX) KRX = (FXG, XTG) JNA = (CKP, KXQ) JPR = (CGD, BJH) CJK = (MSQ, HCV) QSM = (LVL, LPG) BQN = (PCG, BJV) SFH = (XLB, JHQ) XLD = (QNN, LVC) GTF = (HTB, RQV) BMF = (QJQ, JLC) THN = (XLM, DJD) VPB = (FXR, VDR) RQX = (XQD, JDL) LNV = (XJG, FDR) NXN = (DSS, KMF) QTJ = (DKR, KLG) VSV = (KHH, FSD) DBD = (MGN, XFD) DHC = (PHH, HQC) QGH = (VBN, DPJ) NTS = (TCD, HXV) BSK = (BQG, HVR) MRD = (VPB, HJG) BQX = (BSK, BRV) BRV = (BQG, HVR) SVM = (PKX, PJF) KRJ = (NMC, TBX) GTH = (HVG, HVG) SCP = (PJN, CFV) CGF = (VFD, GXX) SHQ = (THN, JNG) JVT = (XKX, RSL) RJK = (RVD, CLK) MKN = (SBM, BRJ) JHV = (HXD, SHG) TLT = (JRF, DQN) QBR = (NFQ, VTS) CNR = (FNX, LVG) LVG = (BJN, VXK) FCQ = (BHL, RGF) JXJ = (CFB, HQL) DJV = (BXL, DTF) DTX = (HCV, MSQ) JLV = (NMC, TBX) STQ = (RMH, XDG) NQK = (DDX, RJK) KTP = (RQV, HTB) RLP = (JDL, XQD) TQD = (PCG, BJV) GGT = (MKN, BTG) VJB = (FLL, QKV) JVB = (MJT, JPD) VQV = (FKG, NLC) FXG = (KLT, SPX) XFD = (LNS, JDS) NKS = (CVS, RGT) QFL = (GPS, LLR) CDN = (HSH, HDP) RTL = (RTF, KPJ) CCX = (GPC, BVD) CXG = (THT, VVN) GRC = (CGG, RRL) MXJ = (TRQ, MRD) SXM = (HQH, NNK) LJV = (SMP, VRJ) RJD = (TKS, BBG) HMQ = (PBJ, HGD) MSQ = (KVR, PKK) GPS = (CNR, CRF) FNT = (KPL, JHK) HDG = (LRB, XFT) LFQ = (PSL, TPJ) VFD = (HLN, SGX) SKC = (CFP, PBP) TKV = (HHX, NLX) GPP = (TKV, LKQ) JSG = (PFH, HHN) BCD = (CKT, BFB) MPJ = (HVJ, RMD) GCT = (MRT, SSN) XTM = (FLJ, FLJ) DKN = (DPJ, VBN) SVN = (VLG, QMT) LQZ = (VJK, BCD) PHS = (GPB, SXG) XCQ = (HQC, PHH) QNN = (FCQ, FCQ) DMM = (CNS, SVM) DBC = (PQN, KNB) JFL = (XSL, XSL) MBL = (RTL, GMQ) VTK = (MGP, SVN) SKL = (TVM, NLF) HXD = (DRH, DNM) GNX = (DTF, BXL) XLM = (SST, QGG) QMF = (CQD, JPR) HMK = (HQB, CCX) MMT = (BQX, LGK) PJN = (DHG, NKS) DGG = (DCL, QBB) SPX = (XQC, BMF) MHN = (SSH, GHM) RDH = (TLT, TBT) NMC = (KKX, VPC) GKV = (SVN, MGP) XSL = (LSP, TXX) TGQ = (THP, CHC) TRQ = (HJG, VPB) VHK = (KRJ, JLV) TPX = (MBM, XHF) QXD = (QDM, PHS) VRJ = (GDK, BVB) KXQ = (RLP, RQX) CNS = (PKX, PJF) TPG = (TVX, VFB) PTR = (QFL, FNB) QHC = (KKB, BNP) CDS = (VGC, LJC) BTC = (MCS, DJB) NLC = (PHG, XRN) BDC = (CFP, PBP) FPT = (GBX, RBB) CQD = (BJH, CGD) XKX = (JGV, XCG) TXX = (VJX, SVQ) SPP = (GTH, GTH) KTM = (HVJ, RMD) JGV = (HTQ, QTJ) HKP = (KLC, VND) GLR = (DVJ, BJJ) LMF = (LHG, VLQ) CLG = (TFL, HMK) KHH = (NNC, XLX) HTQ = (KLG, DKR) QFN = (CNM, TCT) FLL = (TNG, MJV) HFV = (NPC, BJM) NPC = (HVD, CRK) HKK = (KGC, CLG) XRF = (PFC, VHK) GGS = (DLF, LMF) LVC = (FCQ, PDZ) DXX = (MJT, JPD) DCL = (HGT, VSX) LNC = (HHN, PFH) TBT = (JRF, DQN) DKR = (QSM, BVX) KNL = (QCJ, CXG) TLH = (PHS, QDM) NMT = (DSS, KMF) HLC = (GBL, HPK) BDX = (TTF, RGR) HXV = (GLS, CSK) TBH = (VHK, PFC) QBB = (HGT, VSX) TCH = (PQX, HSP) QFH = (XDG, RMH) GND = (HPT, GMM) CVS = (QJV, HDG) FNQ = (VVD, TBQ) NCB = (FKM, FKM) FHJ = (MMS, XKG) VFB = (GGK, JPB) RQV = (KKC, BTC) NLX = (KNL, HGC) TCT = (XRF, TBH) GGB = (NRC, XLD) JKJ = (NXN, NMT) SPG = (DHS, JLB) LVP = (VND, KLC) NPJ = (KGC, CLG) RVD = (SRH, VJB) HTT = (NNK, HQH) PQC = (TGP, GCT) MPB = (MMT, JRD) BCR = (FSD, KHH) BHN = (LNC, JSG) SMP = (BVB, GDK) GPC = (NLB, FSB) NMD = (GTH, XHM) CGD = (SML, VKC) CKP = (RQX, RLP) DQT = (NCB, NCB) KDL = (CNM, TCT) CQK = (BDN, KSC) NXX = (SFK, RMV) RTF = (LJM, SGM) KQQ = (HJK, GMB) KMF = (BVK, BHH) HPK = (KVH, NKQ) PLQ = (MLH, PTP) RCG = (LVJ, FXX) HPF = (LMV, QBR) TBX = (VPC, KKX) NKQ = (VTK, GKV) PRK = (GRD, VVT) TPL = (QVF, FMS) CFM = (DXX, JVB) SGX = (SPP, NMD) MLH = (KQQ, XLR) NNC = (TNT, BLC) XLX = (TNT, BLC) MBM = (NHD, PQC) PHH = (TRG, SCP) QKV = (TNG, MJV) XJG = (FTG, LFQ) QCK = (XVF, MMX) SVQ = (LCD, BKD) SXC = (FMB, NKM) RCT = (CGS, JKP) KNR = (VFD, GXX) FKM = (VQX, VQX) CKV = (DJN, LLK) DDX = (CLK, RVD) GCN = (PTP, MLH) BFB = (DBQ, RDX) SNZ = (TXX, LSP) MVH = (JMX, GRC) HHX = (HGC, KNL) GRD = (GCJ, LST) SPM = (CKX, XVN) LPL = (VDP, TPG) CGM = (BSB, TPX) FXX = (LML, PDD) PGB = (CKV, VRL) MMX = (NMN, NFB) DJS = (TCP, CGM) HTF = (LPL, RTH) DSS = (BVK, BHH) KPJ = (SGM, LJM) DLM = (GRC, JMX) LSQ = (SMP, VRJ) SNR = (NVL, JSJ) DPJ = (CFM, VBB) DDQ = (SFH, CTD) VVN = (NXX, TSR) QLM = (XKG, MMS) QCJ = (VVN, THT) JDL = (PFB, PNL) DLF = (LHG, VLQ) LJC = (JMT, HFV) GVQ = (GQN, MFP) XTK = (HTR, PCT) NRC = (QNN, QNN) PHG = (DHJ, LBD) BVD = (NLB, FSB) VDR = (HKP, LVP) BVK = (GVQ, JPK) FLB = (JSR, GLR) """.trimIndent() }
0
Kotlin
0
0
660d1a5733dd533aff822f0e10166282b8e4bed9
23,597
AOC2023
Creative Commons Zero v1.0 Universal
kotlin/src/katas/kotlin/adventofcode/day3/Part1.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.adventofcode.day3 import java.io.* import kotlin.math.* fun main() { val lines = File("src/katas/kotlin/adventofcode/day3/input.txt").readLines() val positions1 = movesToPositions(moves = lines[0].split(",")) val positions2 = movesToPositions(moves = lines[1].split(",")) println(positions1.size) println(positions2.size) val intersections = positions1.toSet().intersect(positions2.toSet()) - Position(0, 0) val minPosition = intersections.minByOrNull { manhattanDistance(it) }!! println(manhattanDistance(minPosition)) } private fun manhattanDistance(it: Position) = it.x.absoluteValue + it.y.absoluteValue fun movesToPositions(moves: List<String>): MutableList<Position> { val positions = mutableListOf(Position(0, 0)) moves.forEach { move -> val shift = move.drop(1).toInt() val last = positions.last() val elements = when (move.first()) { 'R' -> (last.x..last.x + shift).map { Position(it, last.y) } 'L' -> (last.x - shift..last.x).reversed().map { Position(it, last.y) } 'U' -> (last.y - shift..last.y).reversed().map { Position(last.x, it) } 'D' -> (last.y..last.y + shift).map { Position(last.x, it) } else -> error("") } positions.addAll(elements.drop(1)) } return positions } data class Position(val x: Int, val y: Int)
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,407
katas
The Unlicense
08/kotlin/src/main/kotlin/se/nyquist/Digit.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist // abcdefg // 0 = 1110111 // 1 = 0010010 // 2 = 1011101 // 3 = 1011011 // 4 = 0111010 // 5 = 1101011 // 6 = 1101111 // 7 = 1010010 // 8 = 1111111 // 9 = 1111011 enum class Digit(val number: Int, val representation : String, val signals : Int) { ZERO(0, "abcefg", 5), ONE(1, "cf", 2), TWO(2, "acdeg", 5), THREE(3, "acdfg", 5), FOUR(4, "bcdf", 4), FIVE(5, "abdfg",5), SIX(6, "abdefg", 6), SEVEN(7, "acf", 3), EIGHT(8, "abcdefg", 7), NINE(9, "abcdfg", 6), UNKNOWN(-1, "", 0); override fun toString(): String { return "Digit(number=$number)" } fun toInt() : Int { return number } } fun matchDigitsOnPattern(str : String) : Array<Digit> { return when (str.length) { 2 -> arrayOf(Digit.ONE) 3 -> arrayOf(Digit.SEVEN) 4 -> arrayOf(Digit.FOUR) 5 -> arrayOf(Digit.ZERO, Digit.TWO, Digit.THREE, Digit.FIVE) 6 -> arrayOf(Digit.SIX, Digit.NINE) 7 -> arrayOf(Digit.EIGHT) else -> arrayOf() } } fun getDigit(input : String) : Digit { if (input.equals(Digit.ZERO.representation)) return Digit.ZERO else if (input.equals(Digit.ONE.representation)) return Digit.ONE else if (input.equals(Digit.TWO.representation)) return Digit.TWO else if (input.equals(Digit.THREE.representation)) return Digit.THREE else if (input.equals(Digit.FOUR.representation)) return Digit.FOUR else if (input.equals(Digit.FIVE.representation)) return Digit.FIVE else if (input.equals(Digit.SIX.representation)) return Digit.SIX else if (input.equals(Digit.SEVEN.representation)) return Digit.SEVEN else if (input.equals(Digit.EIGHT.representation)) return Digit.EIGHT else if (input.equals(Digit.NINE.representation)) return Digit.NINE else return Digit.UNKNOWN }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
1,924
adventofcode2021
Apache License 2.0
src/main/kotlin/g0001_0100/s0037_sudoku_solver/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0001_0100.s0037_sudoku_solver // #Hard #Array #Matrix #Backtracking #2023_07_05_Time_148_ms_(100.00%)_Space_34.3_MB_(96.30%) class Solution { private val emptyCells: MutableList<IntArray> = ArrayList() private val rows = IntArray(9) private val cols = IntArray(9) private val boxes = IntArray(9) fun solveSudoku(board: Array<CharArray>) { for (r in 0..8) { for (c in 0..8) { if (board[r][c] == '.') { emptyCells.add(intArrayOf(r, c)) } else { val `val` = board[r][c] - '0' val boxPos = r / 3 * 3 + c / 3 rows[r] = rows[r] or (1 shl `val`) cols[c] = cols[c] or (1 shl `val`) boxes[boxPos] = boxes[boxPos] or (1 shl `val`) } } } backtracking(board, 0) } private fun backtracking(board: Array<CharArray>, i: Int): Boolean { // Check if we filled all empty cells? if (i == emptyCells.size) { return true } val r = emptyCells[i][0] val c = emptyCells[i][1] val boxPos = r / 3 * 3 + c / 3 for (`val` in 1..9) { // skip if that value is existed! if (hasBit(rows[r], `val`) || hasBit(cols[c], `val`) || hasBit(boxes[boxPos], `val`)) { continue } board[r][c] = ('0' + `val`) // backup old values val oldRow = rows[r] val oldCol = cols[c] val oldBox = boxes[boxPos] rows[r] = rows[r] or (1 shl `val`) cols[c] = cols[c] or (1 shl `val`) boxes[boxPos] = boxes[boxPos] or (1 shl `val`) if (backtracking(board, i + 1)) { return true } rows[r] = oldRow cols[c] = oldCol boxes[boxPos] = oldBox } return false } private fun hasBit(x: Int, k: Int): Boolean { return x shr k and 1 == 1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,057
LeetCode-in-Kotlin
MIT License
src/main/kotlin/day4/Solution.kt
krazyglitch
573,086,664
false
{"Kotlin": 31494}
package day4 import util.Utils import java.lang.IllegalArgumentException import java.time.Duration import java.time.LocalDateTime class Solution { class Elf(input: String) { private val left: Int private val right: Int init { val splitString = input.split("-") if (splitString.size < 2) throw IllegalArgumentException("$input is not a valid assignment") left = splitString[0].toInt() right = splitString[1].toInt() } fun contains(other: Elf): Boolean { return left <= other.left && right >= other.right } fun overlaps(other: Elf): Boolean { return right - other.left >= 0 && other.right - left >= 0 } } fun part1(data: List<String>): Int { val containingPairs = data.filter { s -> s.contains(",") }.count { s -> val splitString = s.split(",") val danny = Elf(splitString[0]) val evans = Elf(splitString[1]) danny.contains(evans) || evans.contains(danny) } return containingPairs } fun part2(data: List<String>): Int { val overlappingPairs = data.filter { s -> s.contains(",") }.count { s-> val splitString = s.split(",") val charlie = Elf(splitString[0]) val birdie = Elf(splitString[1]) charlie.overlaps(birdie) } return overlappingPairs } } fun main() { val runner = Solution() val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName) println("Solving first part of day 4") var start = LocalDateTime.now() println("The amount of pairs that overlap fully are: ${input?.let { runner.part1(it) }}") var end = LocalDateTime.now() println("Solved first part of day 4") var milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve first part of day 4") println() println("Solving second part of day 4") start = LocalDateTime.now() println("The amount of pairs that overlap is: ${input?.let { runner.part2(it) }}") end = LocalDateTime.now() println("Solved second part of day 4") milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve second part of day 4") }
0
Kotlin
0
0
db6b25f7668532f24d2737bc680feffc71342491
2,342
advent-of-code2022
MIT License
src/day11/puzzle11.kt
brendencapps
572,821,792
false
{"Kotlin": 70597}
package day11 import Puzzle import PuzzleInput import java.io.File import java.util.PriorityQueue fun day11Puzzle() { Day11PuzzleSolution().solve(Day11PuzzleInput("inputs/day11/example.txt", 10605)) Day11PuzzleSolution().solve(Day11PuzzleInput("inputs/day11/input.txt", 120056)) Day11Puzzle2Solution().solve(Day11PuzzleInput("inputs/day11/example.txt", 2713310158)) Day11Puzzle2Solution().solve(Day11PuzzleInput("inputs/day11/input.txt", 21816744824)) } data class Monkey(val input: String) { private val items = mutableListOf<Long>() private val operation: String val test: Long private val monkeyIfTrue: Int private val monkeyIfFalse: Int var itemsInspected = 0.toLong() init { val inputLines = input.lines() inputLines[1].substring(" Starting items: ".length).split(", ").forEach { item -> items.add(item.toLong()) } operation = inputLines[2].substring(" Operation: new = ".length) test = inputLines[3].substring(" Test: divisible by ".length).toLong() monkeyIfTrue = inputLines[4].substring(" If true: throw to monkey ".length).toInt() monkeyIfFalse = inputLines[5].substring(" If false: throw to monkey ".length).toInt() } fun inspectItems(monkeys: List<Monkey>) { itemsInspected += items.size items.forEach { item -> val operationParts = operation.replace("old", item.toString()).split(" ") val itemToThrow = if(operationParts[1] == "+") { (operationParts[0].toLong() + operationParts[2].toLong()) / 3 } else if(operationParts[1] == "*") { (operationParts[0].toLong() * operationParts[2].toLong()) / 3 } else { item } if(itemToThrow % test == 0.toLong()) { monkeys[monkeyIfTrue].catchItem(itemToThrow) } else { monkeys[monkeyIfFalse].catchItem(itemToThrow) } } items.clear() } fun inspectItems2(monkeys: List<Monkey>, normalizer: Long) { itemsInspected += items.size items.forEach { item -> val itemNormalized = item % normalizer val operationParts = operation.replace("old", itemNormalized.toString()).split(" ") val itemToThrow = if(operationParts[1] == "+") { (operationParts[0].toLong() + operationParts[2].toLong()) } else if(operationParts[1] == "*") { (operationParts[0].toLong() * operationParts[2].toLong()) } else { itemNormalized } if(itemToThrow % test == 0.toLong()) { monkeys[monkeyIfTrue].catchItem(itemToThrow) } else { monkeys[monkeyIfFalse].catchItem(itemToThrow) } } items.clear() } fun catchItem(item: Long) { items.add(item) } } class Day11PuzzleInput(val input: String, expectedResult: Long? = null) : PuzzleInput<Long>(expectedResult) { val monkeys = mutableListOf<Monkey>() var normalizer = 1.toLong() init { File(input).readText().split("\r\n\r\n").forEach() { monkey -> monkeys.add(Monkey(monkey)) } monkeys.forEach { monkey -> normalizer *= monkey.test } } } class Day11PuzzleSolution : Puzzle<Long, Day11PuzzleInput>() { override fun solution(input: Day11PuzzleInput): Long { for(i in 1 .. 20) { input.monkeys.forEach { monkey -> monkey.inspectItems(input.monkeys) } } val topMonkeys = PriorityQueue<Long>() input.monkeys.forEach { topMonkeys.add(it.itemsInspected) if(topMonkeys.size > 2) { topMonkeys.poll() } } return topMonkeys.poll() * topMonkeys.poll() } } class Day11Puzzle2Solution : Puzzle<Long, Day11PuzzleInput>() { override fun solution(input: Day11PuzzleInput): Long { for(i in 1 .. 10000) { input.monkeys.forEach { monkey -> monkey.inspectItems2(input.monkeys, input.normalizer) } } val topMonkeys = PriorityQueue<Long>() input.monkeys.forEach { topMonkeys.add(it.itemsInspected) if(topMonkeys.size > 2) { topMonkeys.poll() } } return topMonkeys.poll() * topMonkeys.poll() } }
0
Kotlin
0
0
00e9bd960f8bcf6d4ca1c87cb6e8807707fa28f3
4,701
aoc_2022
Apache License 2.0
src/main/kotlin/solutions/day03/Day3.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day03 import solutions.Solver class Day3 : Solver { private fun findCommonChar(strings: List<String>): Char? { val charSets = strings.map { it.toSet() } if (charSets.isNotEmpty()) { val first = charSets.first() val rest = charSets.drop(1) return first.find { ch -> rest.all { it.contains(ch) } } } return null } private fun findRucksackError(rucksack: String): Char { val compartmentA = rucksack.substring(0, rucksack.length / 2) val compartmentB = rucksack.substring(rucksack.length / 2) return findCommonChar(listOf(compartmentA, compartmentB))!! } override fun solve(input: List<String>, partTwo: Boolean): String = if (!partTwo) { input.map { findRucksackError(it) } .sumOf { getPriority(it) } .toString() } else { input.chunked(3) .map { findCommonChar(it)!! } .sumOf { getPriority(it) } .toString() } private fun getPriority(it: Char): Int = if (it.isLowerCase()) { 27 - it.rangeTo('z').count() } else { 53 - it.rangeTo('Z').count() } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
1,220
Advent-of-Code-2022
MIT License