path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/day7/fr/Day07_2.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day7.fr import kotlin.math.abs 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 main() { var rep = 0L //val vIn = readInput("test7") val vIn = readInput("input7") var lstIn = vIn[0].split(',').map { it.toInt() } as MutableList lstIn.sort() var bestPos = 0 var tabV: Array<Array<Long>> = Array(2000) {Array(1) { 0 } } for (i in 1 until 2000) { var v = 0L var c = 1 for (j in 1..i) { v += c++ } tabV[i][0] = v } var min = Long.MAX_VALUE var deb = lstIn.first() var fin = lstIn.last() for (i in deb..fin) { for (it in lstIn) { val dif = abs(i - it) val sup = tabV[dif][0] rep += sup } val oldMin = min min = minOf(min, rep) rep = 0 } println(min) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
1,665
Advent-of-Code-2021
Apache License 2.0
11/src/main/kotlin/SantaPass.kt
kopernic-pl
109,750,709
false
null
const val INPUT = "hepxcrrq" typealias IncrementResult = Pair<Boolean, Char> fun main() { val generator = SantaPass() val passwords = generator.generateNextPasswords(INPUT, 2) println(passwords) } internal class SantaPass { fun generateNextPasswords(currentPass: String, n: Int): List<String> { return generateSequence(currentPass) { generateNextPass(it) } .drop(1).take(n) .toList() } companion object { val rules = setOf(IOLMustBeAvoided(), MustContainTwoPairs(), MustContainThreeLettersIncrease()) } internal fun generateNextPass(currentPass: String): String { return generateSequence(currentPass) { it.inc() } .drop(1) .filter { pass -> rules.all { rule -> rule.validate(pass) } } .first() } } internal operator fun String.inc(): String { if (this.isEmpty()) throw IllegalStateException() return this.foldRight( listOf(), { char, acc: List<IncrementResult> -> when { acc.isEmpty() -> acc + char.incrementWithCarry() lastHasCarry(acc) -> acc + char.incrementWithCarry() else -> acc + (false to char) } } ) .reversed() .let { if (firstHasCarry(it)) listOf(false to 'a') + it else it } .map { (_, value) -> value } .joinToString("") } private fun firstHasCarry(l: List<IncrementResult>): Boolean = l.first().first private fun lastHasCarry(l: List<IncrementResult>): Boolean = l.last().first internal fun Char.incrementWithCarry(): IncrementResult { check(this in 'a'..'z') return when { this == 'z' -> true to 'a' else -> false to this.inc() } }
0
Kotlin
0
0
06367f7e16c0db340c7bda8bc2ff991756e80e5b
1,778
aoc-2015-kotlin
The Unlicense
src/Day07.kt
RichardLiba
572,867,612
false
{"Kotlin": 16347}
data class TempFile( val name: String, val isDir: Boolean, val parentName: String, val children: MutableList<TempFile>?, val size: Int? = null, ) { override fun toString(): String { return """- $name (${if (isDir) "dir" else "file, size=$size, parent = $parentName"}) ${if (!isDir) "" else "- ${children?.map { it.toString() }}"} """.trimIndent() } } fun main() { var root = TempFile(name = "root", isDir = true, children = mutableListOf(), parentName = "") fun fillFileSystem(inputs: List<String>): TempFile { var parents = mutableListOf<TempFile>() parents.add(root) var currentFile: TempFile = root inputs.forEach { if (it.startsWith("$")) { //commands if (it == "\$ cd /") { //go to root dir currentFile = root } else if (it.startsWith("\$ cd")) { currentFile = if (it.endsWith("..")) { //move level up parents = parents.dropLast(1).toMutableList() parents.last() } else { val nextDir = it.substringAfter("cd ") val nextFile = currentFile.children?.first { file -> nextDir == file.name }!! parents.add(nextFile) nextFile } } } else if (it.first().isDigit()) { val fileSize = it.substringBefore(" ").toIntOrNull() val fileName = it.substringAfter(" ") currentFile.children?.add( TempFile( isDir = false, name = fileName, size = fileSize, children = null, parentName = currentFile.parentName + "/" + currentFile.name ) ) } else if (it.startsWith("dir")) { val dirName = it.substringAfter("dir ") currentFile.children?.add( TempFile( isDir = true, name = dirName, children = mutableListOf(), parentName = currentFile.parentName + "/" + currentFile.name ) ) } } return parents.first() } val folderSizes = mutableListOf<Int>() fun getSubfolderSizes(file: TempFile): Int { val (folders, files) = file.children.orEmpty().partition { it.isDir } val foldersSize = folders.sumOf { getSubfolderSizes(it) } val size = files.sumOf { it.size!! } + foldersSize folderSizes.add(size) return size } fun part1(input: List<String>): Int { folderSizes.clear() val fileSystem = fillFileSystem(input) fileSystem.children!!.forEach { getSubfolderSizes(it) } return folderSizes.also { println(it) }.sumOf { if (it <= 100_000) it else 0 } } fun part2(input: List<String>): Int { val maxSystem = 70_000_000 val atLeast = 30_000_000 folderSizes.clear() val fileSystem = fillFileSystem(input) getSubfolderSizes(fileSystem) println(folderSizes) folderSizes.sortDescending() val totalSize = folderSizes.first() return folderSizes.last { it >= totalSize - (maxSystem - atLeast) } } val input = readInput("Day07") println(part1(input)) root = TempFile(name = "root", isDir = true, children = mutableListOf(), parentName = "") val inputTEst = readInput("Day07_test") println(part1(inputTEst)) root = TempFile(name = "root", isDir = true, children = mutableListOf(), parentName = "") println(part2(input)) }
0
Kotlin
0
0
6a0b6b91b5fb25b8ae9309b8e819320ac70616ed
3,920
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/d14/D14_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d14 import input.Input import kotlin.math.sqrt fun getPlatformString(platform: Array<CharArray>): String { return platform.joinToString("") { it.joinToString("") } } fun parsePlatformStr(platformStr: String): Array<CharArray> { val lineLength = sqrt(platformStr.length.toDouble()).toInt() val lines = (0..<lineLength).map { platformStr.substring(it * lineLength, (it + 1) * lineLength) } return parseInput(lines) } fun spinPlatform(platform: Array<CharArray>) { for (i in 0..3) { tiltWest(platform) rotateLeft(platform) } } fun main() { val lines = Input.read("input.txt") val platform = parseInput(lines) // to start with north rotateRight(platform) val positions = hashMapOf<String, Int>() positions[getPlatformString(platform)] = 0 var index = 1 while (true) { spinPlatform(platform) val platformStr = getPlatformString(platform) if (positions.contains(platformStr)) break positions[platformStr] = index++ } val cycleStartIndex = positions[getPlatformString(platform)]!! val endPosOffset = (1_000_000_000 - cycleStartIndex) % (index - cycleStartIndex) val endPlatformStr = positions.entries.find { it.value == cycleStartIndex + endPosOffset }!!.key val endPlatform = parsePlatformStr(endPlatformStr) var sum = 0 for (row in endPlatform) { for (i in row.indices) { if (row[i] == 'O') sum += row.size - i } } println(sum) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
1,517
aoc2023-kotlin
MIT License
kotlin/src/com/s13g/aoc/aoc2018/Day2.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2018 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** https://adventofcode.com/2018/day/2 */ class Day2 : Solver { override fun solve(lines: List<String>): Result { val counts = Counts() lines.map { s -> count(s) }.forEach { c -> counts.add(c) } return Result(counts.checksum(), solveB(lines)) } private fun count(line: String): Counts { val counts = hashMapOf<Char, Int>() line.forEach { c -> counts[c] = (counts[c] ?: 0) + 1 } return Counts(if (counts.containsValue(2)) 1 else 0, if (counts.containsValue(3)) 1 else 0) } private fun solveB(lines: List<String>): String { for (i in lines.indices) { for (j in i + 1 until lines.size) { val result = findDiffByOne(lines[i], lines[j]) if (result != null) return result } } return "not found" } private fun findDiffByOne(a: String, b: String): String? { var diff = 0 var result = "" for (i in a.indices) { if (a[i] != b[i]) { diff++ } else { result += a[i] } } return if (diff == 1) result else null } } private class Counts(var twos: Int = 0, var threes: Int = 0) { fun add(other: Counts) { twos += other.twos threes += other.threes } fun checksum(): String { return (twos * threes).toString() } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,347
euler
Apache License 2.0
src/main/kotlin/y2023/day05/Day05.kt
TimWestmark
571,510,211
false
{"Kotlin": 97942, "Shell": 1067}
package y2023.day05 fun main() { AoCGenerics.printAndMeasureResults( part1 = { part1() }, part2 = { part2() } ) } data class Input( val seeds: List<Long>, val seedRanges: List<Pair<Long, Long>>, val seedToSoil: List<Triple<Long, Long, Long>>, val soilToFert: List<Triple<Long, Long, Long>>, val fertToWater: List<Triple<Long, Long, Long>>, val waterToLight: List<Triple<Long, Long, Long>>, val lightToTemp: List<Triple<Long, Long, Long>>, val tempToHumidity: List<Triple<Long, Long, Long>>, val humidityToLocation: List<Triple<Long, Long, Long>>, ) fun input(): Input { val seeds = mutableListOf<Long>() val seedRanges = mutableListOf<Pair<Long, Long>>() val seedToSoil = mutableListOf<Triple<Long, Long, Long>>() val soilToFert = mutableListOf<Triple<Long, Long, Long>>() val fertToWater = mutableListOf<Triple<Long, Long, Long>>() val waterToLight = mutableListOf<Triple<Long, Long, Long>>() val lightToTemp = mutableListOf<Triple<Long, Long, Long>>() val tempToHumidity = mutableListOf<Triple<Long, Long, Long>>() val humidityToLocation = mutableListOf<Triple<Long, Long, Long>>() var currentMappings: MutableList<Triple<Long, Long, Long>> = seedToSoil AoCGenerics.getInputLines("/y2023/day05/input.txt").forEach { line -> when { line.trim().isEmpty() -> return@forEach line.trim().startsWith("seeds") -> { // seeds for part 1 seeds.addAll(line.split(":")[1].trim().split(" ").map { it.toLong() }) // seeds for part 2 val numbers = line.split(":")[1].trim().split(" ").map { it.toLong() } numbers.chunked(2).forEach { chunk -> seedRanges.add(Pair(chunk[0], chunk[1])) } } line.trim().startsWith("seed-to-soil") -> currentMappings = seedToSoil line.trim().startsWith("soil-to-fertilizer") -> currentMappings = soilToFert line.trim().startsWith("fertilizer-to-water") -> currentMappings = fertToWater line.trim().startsWith("water-to-light") -> currentMappings = waterToLight line.trim().startsWith("light-to-temperature") -> currentMappings = lightToTemp line.trim().startsWith("temperature-to-humidity") -> currentMappings = tempToHumidity line.trim().startsWith("humidity-to-location") -> currentMappings = humidityToLocation else -> parseLocations(line, currentMappings) } } return Input( seeds = seeds.toList(), seedRanges = seedRanges.toList(), seedToSoil = seedToSoil.toList(), soilToFert = soilToFert.toList(), fertToWater = fertToWater.toList(), waterToLight = waterToLight.toList(), lightToTemp = lightToTemp.toList(), tempToHumidity = tempToHumidity.toList(), humidityToLocation = humidityToLocation.toList() ) } fun List<Triple<Long, Long, Long>>.getMapping(source: Long): Long { val mappingRange = this.find { source >= it.first && source < (it.first + it.third) } return if (mappingRange == null) { source } else { val diff = source - mappingRange.first mappingRange.second + diff } } fun List<Triple<Long, Long, Long>>.getRevMapping(location: Long): Long { val mappingRange = this.find { location >= it.second && location < (it.second + it.third) } return if (mappingRange == null) { location } else { val diff = location - mappingRange.second mappingRange.first + diff } } fun parseLocations(line: String, currentMappings: MutableList<Triple<Long, Long, Long>>) { val destinationRangeStart = line.split(" ")[0].toLong() val sourceRangeStart = line.split(" ")[1].toLong() val range = line.split(" ")[2].toLong() currentMappings.add(Triple(sourceRangeStart, destinationRangeStart, range)) } fun part1(): Long { val input = input() return input.seeds.minOf { seed -> val soil = input.seedToSoil.getMapping(seed) val fert = input.soilToFert.getMapping(soil) val water = input.fertToWater.getMapping(fert) val light = input.waterToLight.getMapping(water) val temp = input.lightToTemp.getMapping(light) val hum = input.tempToHumidity.getMapping(temp) val location = input.humidityToLocation.getMapping(hum) location } } fun isInRange(seedRanges: List<Pair<Long, Long>>, seed: Long) = seedRanges.any { range -> seed >= range.first && seed < (range.first + range.second) } fun part2(): Long { val input = input() var location: Long = 0 while (true) { val hum = input.humidityToLocation.getRevMapping(location) val temp = input.tempToHumidity.getRevMapping(hum) val light = input.lightToTemp.getRevMapping(temp) val water = input.waterToLight.getRevMapping(light) val fert = input.fertToWater.getRevMapping(water) val soil = input.soilToFert.getRevMapping(fert) val seed = input.seedToSoil.getRevMapping(soil) if (isInRange(input.seedRanges, seed)) { return location } location++ } }
0
Kotlin
0
0
23b3edf887e31bef5eed3f00c1826261b9a4bd30
5,276
AdventOfCode
MIT License
src/Day02.kt
ozzush
579,610,908
false
{"Kotlin": 5111}
fun main() { fun winPoints(elf: Char, you: Char): Int { val outcomePoints = mapOf('X' to 0, 'Y' to 3, 'Z' to 6)[you]!! val win = mapOf('A' to 'B', 'B' to 'C', 'C' to 'A') val lose = mapOf('A' to 'C', 'B' to 'A', 'C' to 'B') val points = mapOf('A' to 1, 'B' to 2, 'C' to 3) return outcomePoints + when (you) { 'X' -> points[lose[elf]] 'Y' -> points[elf] 'Z' -> points[win[elf]] else -> null }!! } check(readInput("day02_test").fold(0) { acc, elm -> acc + winPoints(elm[0], elm[2]) } == 12) readInput("day02").fold(0) { acc, elm -> acc + winPoints(elm[0], elm[2]) }.println() }
0
Kotlin
0
0
9b29a13833659f86d3791b5c07f9decb0dcee475
689
AdventOfCode2022
Apache License 2.0
day2-kotlin/src/main/kotlin/GameRequirements.kt
davidwhitney
725,882,326
false
{"Kotlin": 3532, "TypeScript": 3348}
import java.util.stream.Stream class GameRequirements(val gameId: Int, private val requirements: HashMap<String, Int>) { val power: Int get() { return requirements["red"]!! * requirements["green"]!! * requirements["blue"]!!; } fun isViable(red: Int, green: Int, blue: Int): Boolean { return (requirements["red"]!! <= red && requirements["green"]!! <= green && requirements["blue"]!! <= blue); } override fun toString(): String { return this.gameId.toString() + " " + this.requirements.toString() + " Power: " + power.toString(); } companion object { fun fromLine(line: String): GameRequirements { val parts = line.split(": ", "; "); val rounds = parts.slice(1..<parts.size); val gameId = parts[0].replace("Game ", "").toInt(); val highestRankMap = hashMapOf<String, Int>(); highestRankMap["red"] = 0; highestRankMap["blue"] = 0; highestRankMap["green"] = 0; for (set in rounds) { val counts = set.split(", "); for (item in counts) { val itemParts = item.split(" "); val type = itemParts[1]; val count = itemParts[0].toInt(); val previous = highestRankMap[type]!!; if (count > previous) { highestRankMap[type] = count; } } } return GameRequirements(gameId, highestRankMap); } } } fun List<String>.toGameRequirementsStream(): Stream<GameRequirements> { return this.stream().map{ GameRequirements.fromLine(it) }; } fun Stream<GameRequirements>.viableGames(red: Int, green: Int, blue: Int): Stream<GameRequirements> { return this.filter{ it.isViable(red, green, blue)}; } fun Stream<GameRequirements>.sumOfIds(): Int { return this.mapToInt { it.gameId }.sum(); }
0
Kotlin
0
1
7989c1b555e93199f36cdb9a8871f91b9cfe2828
2,013
Aoc2023
MIT License
src/main/kotlin/io/queue/LastStoneWeight.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import io.models.TreeNode import io.utils.runTests import java.util.* // https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3297/ class LastStoneWeight { fun execute(stones: IntArray): Int { val stack = LinkedList(stones.toList()) stack.sortDescending() while (stack.size > 1) { val (first, second) = stack.pop() to stack.pop() if (first != second) { stack.add(first - second) stack.sortDescending() } } return if (stack.size == 1) stack.pop() else 0 } fun executeTreeNode(stones: IntArray): Int { var root: TreeNode? = stones.toBinarySortTree() while (root != null) { val (newRoot, biggestValue) = root.generateRootAndGetBiggestValue() if (newRoot == null) { return biggestValue } val (newRoot2, biggestValue2) = newRoot.generateRootAndGetBiggestValue() if (newRoot2 == null) { return biggestValue - biggestValue2 } root = newRoot2 if (biggestValue != biggestValue2) root.addValue(biggestValue - biggestValue2) } return 0 } private fun IntArray.toBinarySortTree(): TreeNode? = fold(null as TreeNode?) { acc, value -> acc?.apply { addValue(value) } ?: TreeNode(value) } private fun TreeNode.generateRootAndGetBiggestValue(): Pair<TreeNode?, Int> = this.popBiggestValue()?.let { this to it } ?: left to this.`val` private fun TreeNode.popBiggestValue(): Int? { var current = this while (current.right?.right != null) { current = current.right!! } return current.right?.let { right -> current.right = right.left right.`val` } } private fun TreeNode.addValue(value: Int) { var current = this loop@ while (true) { when { value < current.`val` && current.left != null -> { current = current.left!! } value < current.`val` && current.left == null -> { current.left = TreeNode(value) break@loop } value > current.`val` && current.right != null -> { current = current.right!! } else -> { current.right = TreeNode(value, right = current.right) break@loop } } } } } fun main() { runTests(listOf( intArrayOf(2, 7, 4, 1, 8, 1) to 1 )) { (input, value) -> value to LastStoneWeight().executeTreeNode(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
2,424
coding
MIT License
src/main/kotlin/year2021/day-17.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.aoc.Day import lib.aoc.Part import lib.math.product import kotlin.math.sign import kotlin.math.sqrt fun main() { Day(17, 2021, PartA17(), PartB17()).run() } open class PartA17 : Part() { protected var xMin: Int = 0 protected var xMax: Int = 0 protected var yMin: Int = 0 protected var yMax: Int = 0 override fun parse(text: String) { val regex = """.*x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)""".toRegex() val match = regex.find(text) check(match != null) { "Invalid input" } xMin = match.groupValues[1].toInt() xMax = match.groupValues[2].toInt() yMin = match.groupValues[3].toInt() yMax = match.groupValues[4].toInt() } override fun compute(): String { val maxVy = -yMin - 1 return (maxVy * (maxVy + 1) / 2).toString() } override val exampleAnswer: String get() = "45" } class PartB17 : PartA17() { override fun compute(): String { val minVy = yMin val maxVy = -yMin - 1 val minVx = (sqrt(1 + 8f * xMin) / 2f).toInt() val maxVx = xMax val hits = (minVx..maxVx).product(minVy..maxVy) .filter(::isHit) return hits.size.toString() } private fun isHit(velocity: Pair<Int, Int>): Boolean { var vx = velocity.first var vy = velocity.second var x = 0 var y = 0 while (true) { x += vx y += vy vx -= vx.sign vy-- if (x > xMax) { return false } if (y < yMin) { return false } if (x >= xMin && y <= yMax) { return true } } } override val exampleAnswer: String get() = "112" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
1,906
Advent-Of-Code-Kotlin
MIT License
aoc2023/day14.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day14.execute() } private object Day14 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: Platform): Long = input.moveRocksNorth().calculateLoadNorthBeans() private val cache = mutableMapOf<Platform, Pair<Platform, Int>>() private var platformInformation: PlatformInformation = PlatformInformation(setOf(), Position(0, 0)) private fun part2(input: Platform, numberOfTotalCycles: Int = 1_000_000_000): Long { var platform = input var cycle = 1 while (cycle <= numberOfTotalCycles) { cache[platform]?.let { (_, matchedCycle) -> val cycleSize = cycle - matchedCycle println("Cycle of size $cycleSize detected. We are in cycle $cycle and it's the same as $matchedCycle") val remainingCycles = (numberOfTotalCycles - cycle) % cycleSize val targetCycle = matchedCycle + remainingCycles println("Return the load of cycle $targetCycle") return if (targetCycle == matchedCycle) { platform.calculateLoadNorthBeans() } else { val solution = cache.values.first { (_, cycle) -> cycle == targetCycle } solution.first.calculateLoadNorthBeans() } } val result = platform .moveRocksNorth() .moveRocksWest() .moveRocksSouth() .moveRocksEast() cache[platform] = result to cycle platform = result cycle++ } return platform.calculateLoadNorthBeans() } private fun readInput(): Platform = InputRetrieval.getFile(2023, 14).readLines().let { Platform.parse(it) } private data class PlatformInformation(val staticRocks: Set<Position>, val maxPos: Position) private data class Platform(val movingRocks: Set<Position>) { private fun moveRocks(input: Platform, edgeValidation: (Position) -> Boolean, mapping: (Position) -> Position): Platform { // This algorithm is quite slow, it can be optimized var rockMoved = true var platform = input while (rockMoved) { rockMoved = false val newMovingRocksPositions = platform.movingRocks.map { val newPos = mapping.invoke(it) if (edgeValidation.invoke(newPos) && !platformInformation.staticRocks.contains(newPos) && !platform.movingRocks.contains(newPos)) { rockMoved = true newPos } else { it } }.toSet() platform = Platform(newMovingRocksPositions) } return platform } fun moveRocksNorth(): Platform = moveRocks(this, { pos -> pos.y > -1 }) { Position(x = it.x, y = it.y - 1) } fun moveRocksWest(): Platform = moveRocks(this, { pos -> pos.x > -1 }) { Position(x = it.x - 1, y = it.y) } fun moveRocksSouth(): Platform = moveRocks(this, { pos -> pos.y < platformInformation.maxPos.y }) { Position(x = it.x, y = it.y + 1) } fun moveRocksEast(): Platform = moveRocks(this, { pos -> pos.x < platformInformation.maxPos.x }) { Position(x = it.x + 1, y = it.y) } fun calculateLoadNorthBeans(): Long = movingRocks.sumOf { platformInformation.maxPos.y - it.y.toLong() } companion object { fun parse(input: List<String>): Platform { val movingRocks = mutableSetOf<Position>() val staticRocks = mutableSetOf<Position>() for (i in input.indices) { for (z in input.first().indices) { when { input[i][z] == 'O' -> movingRocks.add(Position(z, i)) input[i][z] == '#' -> staticRocks.add(Position(z, i)) } } } platformInformation = PlatformInformation(staticRocks, Position(input.first().length, input.size)) return Platform(movingRocks) } } } private data class Position(val x: Int, val y: Int) }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
4,499
Advent-Of-Code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShipWithinDays.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 kotlin.math.max /** * 1011. Capacity To Ship Packages Within D Days * @see <a href="https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/">Source</a> */ fun interface ShipWithinDays { operator fun invoke(weights: IntArray, days: Int): Int } /** * BINARY Search */ class ShipWithinDaysBS : ShipWithinDays { override operator fun invoke(weights: IntArray, days: Int): Int { var left = 0 var right = 0 for (i in weights) { left = max(left, i) right += i } var mid: Int var ans = right while (left <= right) { mid = (left + right) / 2 if (check(weights, days, mid)) { ans = mid right = mid - 1 } else { left = mid + 1 } } return ans } private fun check(weights: IntArray, days: Int, capacity: Int): Boolean { var requiredDays = 1 var currWeight = 0 for (i in weights) { if (currWeight + i > capacity) { requiredDays++ currWeight = 0 } currWeight += i } return requiredDays <= days } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,875
kotlab
Apache License 2.0
src/aoc2022/Day14.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* import utils.Coord.Companion.get import utils.Coord.Companion.set import kotlin.math.max import kotlin.math.min private class Day14(val lines: List<String>) { val rocks: List<List<Coord>> = lines .map { it.split(" -> ") .map { val (x, y) = it.split(",").map { it.toInt() } Coord.xy(x, y) } } val down = Coord.xy(0, 1) val downLeft = Coord.xy(-1, 1) val downRight = Coord.xy(1, 1) private fun setRockLines(grid: MutableList<MutableList<Boolean>>) { rocks.forEach { it.zipWithNext { a, b -> val xRange = min(a.x, b.x)..max(a.x, b.x) val yRange = min(a.y, b.y)..max(a.y, b.y) for (x in xRange) { for (y in yRange) { grid[y][x] = false } } } } } fun part1(): Any { // Grid where all true means that spot is open. val grid = MutableList(1000) { MutableList(1000) { true } } setRockLines(grid) val maxY = rocks.flatMap { it }.maxOf { it.y } var sandCount = 0 while (true) { // Simulate sand falling. var pos = Coord.xy(500, 0) while (true) { if (grid[pos + down]) { pos += down } else if (grid[pos + downLeft]) { pos += downLeft } else if (grid[pos + downRight]) { pos += downRight } else { // Sand can't move grid[pos] = false break } // Check if the sand is falling below the last rocks. if (pos.y > maxY) { return sandCount } } sandCount++ } } fun part2(): Any { // Grid where all true means that spot is open. val grid = MutableList(1000) { MutableList(1000) { true } } setRockLines(grid) // Draw the floor val floor = rocks.flatMap { it }.maxOf { it.y } + 2 grid[0].indices.forEach { x -> grid[floor][x] = false } var sandCount = 0 while (true) { sandCount++ var pos = Coord.xy(500, 0) // simulate sand while (true) { if (grid[pos + down]) { // We can move pos += down } else if (grid[pos + downLeft]) { // We can move pos += downLeft } else if (grid[pos + downRight]) { // We can move pos += downRight } else { grid[pos] = false // Sand plugs the source if (pos.y <= 0) { return sandCount } break } } } } } fun main() { val day = "14".toInt() val todayTest = Day14(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 24) val today = Day14(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 873) execute(todayTest::part2, "Day[Test] $day: pt 2", 93) execute(today::part2, "Day $day: pt 2", 24813) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
2,844
aoc2022
Apache License 2.0
src/main/kotlin/year2023/day-05.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2023 import lib.aoc.Day import lib.aoc.Part import lib.splitLines fun main() { Day(5, 2023, PartA5(), PartB5()).run() } open class PartA5 : Part() { protected data class Lut(val destinationStart: Long, val sourceStart: Long, val length: Long) { val sourceRange: LongRange get() = sourceStart until (sourceStart + length) val destinationRange: LongRange get() = destinationStart until (destinationStart + length) } protected data class Converter(val luts: List<Lut>, val destination: String) { fun convert(source: Long): Long { val lut = luts.firstOrNull { source in it.sourceRange } ?: return source return lut.destinationStart + (source - lut.sourceStart) } companion object { fun parse(text: String): Pair<String, Converter> { val numRegex = """\d+""".toRegex() val lines = text.splitLines() val (source, destination) = """(\w+)-to-(\w+).*""".toRegex().find(lines[0])!!.destructured val luts = lines .drop(1) .map { val numbers = numRegex.findAll(it).map { it.value.toLong() }.toList() Lut(numbers[0], numbers[1], numbers[2]) } return Pair(source, Converter(luts, destination)) } } } protected lateinit var converters: Map<String, Converter> protected lateinit var seeds: List<Long> override fun parse(text: String) { val numRegex = """\d+""".toRegex() val parts = text.split("\n\n") seeds = numRegex.findAll(parts[0]).map { it.value.toLong() }.toList() converters = parts.drop(1) .associate { Converter.parse(it) } } override fun compute(): String { return seeds.minOf(::convertToLocation).toString() } protected fun convertToLocation(seed: Long): Long { var category = "seed" var number = seed while (category != "location") { number = converters.getValue(category).convert(number) category = converters.getValue(category).destination } return number } override val exampleAnswer: String get() = "35" } class PartB5 : PartA5() { override fun compute(): String { return seeds .chunked(2) .map { it[0] until (it[0] + it[1]) } .map { it.minOf(::convertToLocation) } .min() .toString() } override val exampleAnswer: String get() = "46" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
2,728
Advent-Of-Code-Kotlin
MIT License
src/Day01.kt
PauliusRap
573,434,850
false
{"Kotlin": 20299}
fun main() { fun getSortedCalorieList(input: List<String>): List<Int> { val list = mutableListOf<Int>() var individualCalories = 0 input.forEach { line -> if (line.isBlank()) { list.add(individualCalories) individualCalories = 0 } else { individualCalories += line.toInt() } } if (individualCalories != 0 ) list.add(individualCalories) return list.sortedDescending() } fun part1(input: List<String>): Int { return getSortedCalorieList(input).first() } fun part2(input: List<String>): Int { val list = getSortedCalorieList(input) return list[0] + list[1] + list[2] } // test if implementation meets criteria from the description: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
df510c3afb104c03add6cf2597c433b34b3f7dc7
1,024
advent-of-coding-2022
Apache License 2.0
src/main/kotlin/Dayxx.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
import se.saidaspen.aoc.util.* fun main() = Dayxx.run() object Dayxx : Day(2022, 25) { override fun part1(): Any { var temp = "1=-0-2\n" + "12111\n" + "2=0=\n" + "21\n" + "2=01\n" + "111\n" + "20012\n" + "112\n" + "1=-1=\n" + "1-12\n" + "12\n" + "1=\n" + "122" return dec2Snafu(input.lines().map { snafu2Dec(it) }.sumOf { it }) } public fun dec2Snafu(dec: Long): String { var left = dec var snafu = "" while (left > 0) { val curr = left % 5 val (digit, chr) = when (curr) { 0L -> P(0L, '0') 1L -> P(1L, '1') 2L -> P(2L, '2') 3L -> P(-2L, '=') 4L -> P(-1L, '-') else -> throw RuntimeException("Unsupported") } snafu += chr left -= digit left /= 5 } return snafu.reversed() } var mults = mutableMapOf('-' to -1, '=' to -2) fun snafu2Dec(snafu: String): Long { return snafu.e() .reversed() .foldIndexed(0L){ index, total, item -> var digit = when(item) { '=' -> -2 '-' -> -1 '0' -> 0 '1' -> 1 '2' -> 2 else -> throw RuntimeException("Unsupported") } total + digit * 5L.pow(index) } //.sumOf { 5.pow(it.index) * (if (it.value in mults.keys) mults[it.value] else it.value.digitToInt())!! } } override fun part2(): Any { return "" } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,822
adventofkotlin
MIT License
src/test/kotlin/io/noobymatze/aoc/y2023/Day8.kt
noobymatze
572,677,383
false
{"Kotlin": 90710}
package io.noobymatze.aoc.y2023 import io.noobymatze.aoc.Aoc import kotlin.test.Test class Day8 { @Test fun test() { val (movement, nodesString) = Aoc.getInput(8) .split("\n\n") val map = nodesString.lines().associate { val (start, target) = it.split(" = ") val (left, right) = target.trim('(', ')').split(", ") start to (left to right) } var steps = 0 var node = "AAA" while (node != "ZZZ") { val step = movement[steps % movement.length] if (step == 'R') node = map[node]!!.second else if (step == 'L') node = map[node]!!.first steps++ } println(steps) } @Test fun test2() { val (movement, nodesString) = Aoc.getInput(8) .split("\n\n") val map: Map<String, Pair<String, String>> = nodesString.lines().associate { val (start, target) = it.split(" = ") val (left, right) = target.trim('(', ')').split(", ") start to (left to right) } // Find the steps to the first node ending in Z for each starting node val steps = map.keys.filter { it.endsWith("A") }.map { var steps = 0L var node = it while (!node.endsWith("Z")) { val step = movement[(steps % movement.length).toInt()] if (step == 'R') node = map[node]!!.second else if (step == 'L') node = map[node]!!.first steps++ } steps } // Once a node ending in Z is reached, it takes the same // amount of steps to reach it again, therefore // compute the least common multiple println(steps.reduce { a, b -> lcm(a, b) }) } private fun lcm(a: Long, b: Long): Long = (a * b) / gcd(a, b) private tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) }
0
Kotlin
0
0
da4b9d894acf04eb653dafb81a5ed3802a305901
2,062
aoc
MIT License
src/main/kotlin/Day16.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset enum class Direction(val action: (Pair<Int, Int>) -> Pair<Int, Int>) { UP({ it.first - 1 to it.second }), UP_LEFT({ it.first - 1 to it.second - 1 }), UP_RIGHT({ it.first - 1 to it.second + 1 }), DOWN({ it.first + 1 to it.second }), DOWN_LEFT({ it.first + 1 to it.second - 1 }), DOWN_RIGHT({ it.first + 1 to it.second + 1 }), LEFT({ it.first to it.second - 1 }), RIGHT({ it.first to it.second + 1 }); companion object { fun fromString(s: String): Direction { return when (s) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> error("Input failure: Direction") } } } } fun main() { fun mapEnergizedTiles(layout: List<String>, startPoint: Pair<Int, Int> = 0 to -1): List<List<MutableList<Direction>>> { val tiles = layout.map { s -> s.map { mutableListOf<Direction>() } } fun traverseTile( yAndX: Pair<Int, Int>, direction: Direction ) { val position = direction.action(yAndX) if (position.second < 0 || position.first < 0 || position.second > layout.first.lastIndex || position.first > layout.lastIndex) { return } if (tiles[position.first][position.second].contains(direction)) { return } tiles[position.first][position.second].add(direction) when (layout[position.first][position.second]) { '.' -> { traverseTile(position, direction) } '|' -> { if (direction == Direction.RIGHT || direction == Direction.LEFT) { traverseTile(position, Direction.UP) traverseTile(position, Direction.DOWN) } else { traverseTile(position, direction) } } '-' -> { if (direction == Direction.RIGHT || direction == Direction.LEFT) { traverseTile(position, direction) } else { traverseTile(position, Direction.LEFT) traverseTile(position, Direction.RIGHT) } } '\\' -> { when (direction) { Direction.UP -> traverseTile(position, Direction.LEFT) Direction.DOWN -> traverseTile(position, Direction.RIGHT) Direction.LEFT -> traverseTile(position, Direction.UP) Direction.RIGHT -> traverseTile(position, Direction.DOWN) else -> error("Invalid direction!") } } '/' -> { when (direction) { Direction.UP -> traverseTile(position, Direction.RIGHT) Direction.DOWN -> traverseTile(position, Direction.LEFT) Direction.LEFT -> traverseTile(position, Direction.DOWN) Direction.RIGHT -> traverseTile(position, Direction.UP) else -> error("Invalid direction!") } } } } val direction = if (startPoint.second == -1) { Direction.RIGHT } else if (startPoint.first == -1) { Direction.DOWN } else if (startPoint.first == layout.size) { Direction.UP } else { Direction.LEFT } traverseTile(startPoint, direction) return tiles } fun part1(input: List<String>): Int { val tiles: List<List<MutableList<Direction>>> = mapEnergizedTiles(input) return tiles.sumOf { it.sumOf { list -> if (list.isEmpty()) 0 else 1 as Int } } } // This one might need increased. Runs with vm argument -Xss2m fun part2(input: List<String>): Int { val startPoints = (0..input.lastIndex).map { it to -1 } + (0..input.lastIndex).map { it to input.size } + (0..input.first.lastIndex).map { -1 to it } + (0..input.first.lastIndex).map { input.first.length to it } return startPoints.maxOf { mapEnergizedTiles(input, it).sumOf { tiles -> tiles.sumOf { list -> if (list.isEmpty()) 0 else 1 as Int } } } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day16-input.txt") val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
5,005
aoc-2023-in-kotlin
Apache License 2.0
src/Day14.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
import kotlin.math.max import kotlin.math.min fun main() { var left = 0 var maxDepth = 0 fun Array<CharArray>.print() { for (row in this) { println(row.contentToString().filterNot { it == ',' }) } } fun String.parse() = this.split(" -> ") .map { it.split(",") } .map { elem -> Pair(elem.first().toInt(), elem.last().toInt()) } .zipWithNext() fun initializeMap(rocks: List<List<Pair<Pair<Int, Int>, Pair<Int, Int>>>>): Array<CharArray> { maxDepth = rocks.flatMap { it.map { elem -> listOf(elem.first.second, elem.second.second) } }.flatten().max() val (leftLocal, right) = rocks.flatMap { it.map { elem -> listOf(elem.first.first, elem.second.first) } } .flatten() .let { pos -> listOf(pos.min(), pos.max()) } left = leftLocal val caveMap = Array(maxDepth + 1) { CharArray(right - left + 3) { '.' } } for (rock in rocks) { // println(rock) rock.forEach { r -> val (minRow, maxRow) = listOf( min(r.first.second, r.second.second), max(r.first.second, r.second.second) ) val (minCol, maxCol) = listOf( min(r.first.first - left, r.second.first - left) + 1, max(r.first.first - left, r.second.first - left) + 1 ) for (i in minRow..maxRow) for (j in minCol..maxCol) { caveMap[i][j] = '#' } caveMap[0][500 - left] = '+' // caveMap.print() } } // caveMap.print() return caveMap } fun initializeMapSecondPart(rocks: List<List<Pair<Pair<Int, Int>, Pair<Int, Int>>>>): Array<CharArray> { maxDepth = rocks.flatMap { it.map { elem -> listOf(elem.first.second, elem.second.second) } }.flatten().max() + 2 val (leftLocal, right) = rocks.flatMap { it.map { elem -> listOf(elem.first.first, elem.second.first) } } .flatten() .let { pos -> listOf(pos.min(), pos.max()) } left = leftLocal val caveMap = Array(maxDepth + 1) { CharArray(right - left + 800) { '.' } } for (rock in rocks) { // println(rock) rock.forEach { r -> val (minRow, maxRow) = listOf( min(r.first.second, r.second.second), max(r.first.second, r.second.second) ) val (minCol, maxCol) = listOf( min(r.first.first - left, r.second.first - left) + 400, max(r.first.first - left, r.second.first - left) + 400 ) for (i in minRow..maxRow) for (j in minCol..maxCol) { caveMap[i][j] = '#' } caveMap[0][500 - left + 400] = '+' // caveMap.print() } } caveMap[maxDepth] = CharArray(right - left + 800) {'#'} caveMap.print() return caveMap } fun runGameUntilflowing(cave: Array<CharArray>): Int { fun Pair<Int, Int>.leftDown() = cave[first + 1][second - 1] fun Pair<Int, Int>.down() = cave[first + 1][second] fun Pair<Int, Int>.rightDown() = cave[first + 1][second + 1] fun Pair<Int, Int>.lock() = leftDown() != '.' && down() != '.' && rightDown() != '.' var count = 0 val sandCol = 500 - left + 1 while (true) { var pos = 0 to sandCol while (pos.first != maxDepth && !pos.lock()) { if (pos.down() == '.') pos = pos.first + 1 to pos.second else if (pos.leftDown() == '.') pos = pos.first + 1 to pos.second - 1 else if (pos.rightDown() == '.') pos = pos.first + 1 to pos.second + 1 } if (pos.first == maxDepth) break cave[pos.first][pos.second] = 'o' count++ // cave.print() } // println(count) // cave.print() return count } fun runGameUntilFilled(cave: Array<CharArray>): Int { fun Pair<Int, Int>.leftDown() = cave[first + 1][second - 1] fun Pair<Int, Int>.down() = cave[first + 1][second] fun Pair<Int, Int>.rightDown() = cave[first + 1][second + 1] fun Pair<Int, Int>.lock() = leftDown() != '.' && down() != '.' && rightDown() != '.' var count = 1 val sandCol = 500 - left + 400 while (true) { var pos = 0 to sandCol if(pos.lock()) break while (!pos.lock()) { if (pos.down() == '.') pos = pos.first + 1 to pos.second else if (pos.leftDown() == '.') pos = pos.first + 1 to pos.second - 1 else if (pos.rightDown() == '.') pos = pos.first + 1 to pos.second + 1 } cave[pos.first][pos.second] = 'o' count++ // cave.print() // println() } // println(count) // cave.print() return count } //var pos = caveT[sandCol].indexOfFirst { "[#o]".toRegex().matches(it.toString()) } fun part1(input: List<String>): Int { val rocks = input.map { it.parse() } val cave = initializeMap(rocks) return runGameUntilflowing(cave) } fun part2(input: List<String>): Int { val rocks = input.map { it.parse() } val cave = initializeMapSecondPart(rocks) return runGameUntilFilled(cave) } val testInput = readInput("Day14_test") val input = readInput("Day14") // check(part1(testInput) == 24) // println(part1(testInput)) // println(part1(input)) println(part2(testInput)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
5,982
AoC-2022
Apache License 2.0
src/Day07.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
enum class Type { COMMAND, OUTPUT } fun main() { val TOTAL_SPACE = 70000000 val REQUIRED_SPACE = 30000000 class Node(name: String, parentNode: Node?){ val childNodes = HashMap<String, Node>() var parentNode = parentNode var size = -1 var calculatedSize = -1 fun isSizeCalculated(): Boolean { return calculatedSize != -1 } fun isFile(): Boolean { return size != -1 } fun isDirectory(): Boolean { return size == -1 } fun getCalcSize(): Int { if (isSizeCalculated()) { return calculatedSize } else if (isFile()) { return size } else { calculatedSize = childNodes.keys.sumOf { childNodes[it]?.getCalcSize()!! } return calculatedSize } } fun findSubdirectoriesUnderSize(list: MutableList<Node>, sizeLimit: Int) : List<Node>{ if (isDirectory() && this.calculatedSize <= sizeLimit) { list.add(this) } childNodes.values.forEach{ it.findSubdirectoriesUnderSize(list, sizeLimit) } return list } } fun part1(input: String): Int { var rootNode = Node("/", null) var currentNode = rootNode var lineType = Type.COMMAND input.split("\n") .drop(1) .map { var args = it.split(" ").toMutableList() args.add(" ") args } .forEach {(firstToken, secondToken, thirdToken) -> if (firstToken == "$") { lineType = Type.COMMAND } else { lineType = Type.OUTPUT } if (lineType == Type.COMMAND && secondToken == "cd") { //handle .. if (thirdToken == "..") { currentNode = currentNode.parentNode!! } else { currentNode = currentNode.childNodes.get(thirdToken)!! } } else if (lineType == Type.OUTPUT) { val fileSize = firstToken.toIntOrNull() val fileName = secondToken val childNode = Node(fileName, currentNode) childNode.size = fileSize ?: -1 currentNode.childNodes.put(fileName, childNode) } } rootNode.getCalcSize() var smallDirectories = rootNode.findSubdirectoriesUnderSize(ArrayList<Node>(), 100000) return smallDirectories.sumOf { it.calculatedSize } } fun part2(input: String): Int { var rootNode = Node("/", null) var currentNode = rootNode var lineType = Type.COMMAND input.split("\n") .drop(1) .map { var args = it.split(" ").toMutableList() args.add(" ") args } .forEach {(firstToken, secondToken, thirdToken) -> if (firstToken == "$") { lineType = Type.COMMAND } else { lineType = Type.OUTPUT } if (lineType == Type.COMMAND && secondToken == "cd") { //handle .. if (thirdToken == "..") { currentNode = currentNode.parentNode!! } else { currentNode = currentNode.childNodes.get(thirdToken)!! } } else if (lineType == Type.OUTPUT) { val fileSize = firstToken.toIntOrNull() val fileName = secondToken val childNode = Node(fileName, currentNode) childNode.size = fileSize ?: -1 currentNode.childNodes.put(fileName, childNode) } } val remainingSpace = TOTAL_SPACE - rootNode.getCalcSize() var allDirectories = rootNode.findSubdirectoriesUnderSize(ArrayList<Node>(), Int.MAX_VALUE) var smallestFreeDirectory = 0 allDirectories .map { it.calculatedSize } .sortedDescending() .forEach { if (remainingSpace + it > REQUIRED_SPACE) { smallestFreeDirectory = it } } return smallestFreeDirectory } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") val output = part1(testInput) check(output == 95437) val outputTwo = part2(testInput) check(outputTwo == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
4,953
aoc-kotlin
Apache License 2.0
dcp_kotlin/src/main/kotlin/dcp/day245/day245.kt
sraaphorst
182,330,159
false
{"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315}
package dcp.day245 // day245.kt // By <NAME>, 2019. import kotlin.math.min fun brute_force(moves: List<Int>): Int? { if (moves.isEmpty()) return 0 fun aux(position: Int = 0, movesSoFar: Int = 0): Int? { // Determine the possible moves. if (position == moves.size - 1) return movesSoFar if (moves[position] == 0) return null // Determine the positions to which we can move. val maxPosition = position + moves[position] val newPositions = (position + 1)..min(moves.size - 1, maxPosition) val options = newPositions.map { aux(it, movesSoFar + 1) } return options.filterNotNull().min() } return aux() } fun dynamic_programming(moves: List<Int>): Int? { if (moves.isEmpty()) return 0 // dp[i] is the minimum number of moves needed to get to the end of the array from position i. // Set initially to values that are larger than the array. val N = moves.size val dp = Array(N){N + 1} dp[N - 1] = 0 // Go backward, determining dp[i]. (moves.size - 1 downTo 0).forEach { i -> // Furthest we can go from position. if (moves[i] != 0) { ((i + 1) until min(1 + i + moves[i], N)).forEach { j -> dp[i] = min(dp[i], 1 + dp[j]) } } } return dp[0] }
0
C++
1
0
5981e97106376186241f0fad81ee0e3a9b0270b5
1,377
daily-coding-problem
MIT License
src/main/kotlin/d12_PassagePathing/PassagePathing.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d12_PassagePathing import util.Input import util.Output val upperAlpha = "A".."Z" val lowerAlpha = "a".."z" fun main() { Output.day(12, "Passage Pathing") val startTime = Output.startTime() val input = Input.parseTo2dList<String>(filename = "/input/d12_path_map.txt", delimiter = "-") val caveGraph = mutableMapOf<String, List<String>>() input.forEach { if (it[1] != "start") caveGraph.merge(it[0], listOf(it[1])) { a, b -> a + b } if (it[0] != "start") caveGraph.merge(it[1], listOf(it[0])) { a, b -> a + b } } caveGraph["end"] = listOf() var completePaths = 0 var completePathsNoRepeat = 0 val curPath = mutableListOf<String>() val toDoQ = mutableListOf(Pair("start", 0)) lateinit var curNode: Pair<String, Int> var justPopped = false while (toDoQ.size > 0) { // set current node to end of queue curNode = toDoQ.last() // add current node to tracked path if haven't just popped on off if (!justPopped) curPath.add(curNode.first) else justPopped = false // --- find neighbors val neighbors = caveGraph[curNode.first]!! // start at current node's stored index to avoid previously visited neighbors // if a neighbor is lowercase and in the tracked path, skip to next // also skip to next if there's not room for another small cave var nextIndex = curNode.second while (nextIndex < neighbors.size && ( (neighbors[nextIndex] !in upperAlpha && neighbors[nextIndex] in curPath && !curPath.roomForOneMore())) ) { nextIndex++ } // if at 'end' or no neighbors left, then save, pop, and continue if (curNode.first == "end" || nextIndex >= caveGraph[curNode.first]!!.size) { if (curNode.first == "end") { completePaths++ if (curPath.roomForOneMore()) completePathsNoRepeat++ } curPath.removeLast() toDoQ.removeLast() justPopped = true continue } else { toDoQ[toDoQ.size - 1] = Pair(curNode.first, nextIndex + 1) toDoQ.add(Pair(neighbors[nextIndex], 0)) } } Output.part(1, "Number of Paths", completePathsNoRepeat) Output.part(2, "Number of Longer Paths", completePaths) // recursive solution // Output.part(1, "Number of Paths", findAllPaths(caveGraph, "start").size) // Output.part(2, "Number of Longer Paths", findAllPaths(caveGraph, "start", smallCaveMax = 2).size) Output.executionTime(startTime) } fun MutableList<String>.roomForOneMore(): Boolean { val smalls = this.filter { it in lowerAlpha } return smalls == smalls.distinct() } // recursive solution //fun findAllPaths( // graph: Map<String, List<String>>, // node: String, // curPath: MutableList<String> = mutableListOf(), // smallCaveMax: Int = 1 //): List<List<String>> { // // for returning paths in a list of path lists - yay recursion! // val successPaths = mutableListOf<List<String>>() // // // add node to path immediately on traversal // curPath.add(node) // // // if at 'end', return the current tracked path // if (node == "end") { // successPaths.add(curPath) // return successPaths // } else { // // only traverse through Large nodes or not-traversed small nodes // graph[node]!!.filter { // it in upperAlpha || it !in curPath || // (it in lowerAlpha && smallCaveMax > 1 && curPath.roomForOneMore()) // }.forEach { // successPaths.addAll(findAllPaths(graph, it, curPath.toMutableList(), smallCaveMax)) // } // } // // // nothing left to traverse, don't return path because not at 'end' // return successPaths //}
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
3,894
advent-of-code-2021
MIT License
src/main/kotlin/aoc2022/Day20.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.followedBy import aoc.parser.number import aoc.parser.zeroOrMore class Day20() { val parser = zeroOrMore(number() followedBy "\n") private fun solve(parsed: List<Long>, repeat: Long): Long { val size = parsed.size val sizem1 = size - 1 //println(size) //println(parsed) val indexes = List(size) { it }.toMutableList() (0 until repeat).forEach { parsed.forEachIndexed { idx, move -> val from = indexes.indexOf(idx) val to = (from + move).mod(sizem1) val e = indexes.removeAt(from) indexes.add(to, e) } // val list = indexes.map { parsed[it] } // println(list) } val list = indexes.map { parsed[it] } val indexOf0 = list.indexOf(0) return listOf(1000, 2000, 3000).sumOf { list[(indexOf0 + it).mod(size)] } } fun part1(input: String): Long { val parsed = parser.parse(input).map { it.toLong() } return solve(parsed, 1) } fun part2(input: String): Long { val parsed = parser.parse(input).map { it.toLong() * 811589153 } return solve(parsed, 10) } }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
1,261
aoc-kotlin
Apache License 2.0
src/main/kotlin/leetcode/Problem1559.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/detect-cycles-in-2d-grid/ */ class Problem1559 { fun containsCycle(grid: Array<CharArray>): Boolean { val maxRow = grid.size val maxCol = if (maxRow == 0) 0 else grid[0].size val visited = Array(grid.size) { BooleanArray(maxCol) } var row = 0 while (row < maxRow) { var col = 0 while (col < maxCol) { if (visited[row][col]) { col++ continue } if (containsCycle(grid, maxRow, maxCol, grid[row][col], visited, -1, -1, row, col)) { return true } col++ } row++ } return false } private fun containsCycle(grid: Array<CharArray>, maxRow: Int, maxCol: Int, char: Char, visited: Array<BooleanArray>, previousRow: Int, previousCol: Int, currentRow: Int, currentCol: Int): Boolean { if (visited[currentRow][currentCol]) { return false } visited[currentRow][currentCol] = true for ((r, c) in arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1))) { val newRow = currentRow + r val newCol = currentCol + c if (newRow < 0 || newRow == maxRow || newCol < 0 || newCol == maxCol) { continue } if (grid[newRow][newCol] != char) { continue } if (!(previousRow == newRow && previousCol == newCol)) { if (visited[newRow][newCol]) { return true } if (containsCycle( grid, maxRow, maxCol, char, visited, currentRow, currentCol, newRow, newCol ) ) { return true } } } return false } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
2,044
leetcode
MIT License
src/main/kotlin/day14.kt
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
sealed class CodeInstruction { data class Mask(val off: Long, val on: Long) : CodeInstruction() data class Write(val addr: Long, val value: Long) : CodeInstruction() } fun day14ProblemReader(text: String): List<CodeInstruction> { val maskRegex = "mask\\s=\\s(\\w+)".toRegex() val memRegex = "mem\\[(\\d+)\\]\\s=\\s(\\d+)".toRegex() return text.split('\n').map { line -> if (line.matches(maskRegex)) { val (mask) = maskRegex.matchEntire(line)!!.destructured CodeInstruction.Mask( mask.replace('X', '0').toLong(radix = 2), mask.replace('X', '1').toLong(radix = 2) ) } else { val (address, value) = memRegex.matchEntire(line)!!.destructured CodeInstruction.Write( address.toLong(), value.toLong(), ) } } } // https://adventofcode.com/2020/day/14 class Day14( private val instructions: List<CodeInstruction>, ) { fun solvePart1(): Long { val memory = mutableMapOf<Long, Long>() var maskOff = 0L var maskOn = 0L for (instruction in instructions) { when (instruction) { is CodeInstruction.Mask -> { maskOff = instruction.off maskOn = instruction.on } is CodeInstruction.Write -> { memory[instruction.addr] = instruction.value and maskOn or maskOff } } } return memory.values.sum() } // had to look at this one for this one // https://github.com/ephemient/aoc2020/blob/main/kt/src/main/kotlin/io/github/ephemient/aoc2020/Day14.kt fun solvePart2(): Long { val memory = mutableMapOf<Long, Long>() var maskOff = 0L var maskOn = 0L for (instruction in instructions) { when (instruction) { is CodeInstruction.Mask -> { maskOff = instruction.off maskOn = instruction.on } is CodeInstruction.Write -> { val diff = maskOff xor maskOn val numDiffBits = diff.countOneBits() var addr = instruction.addr or maskOff for (i in 0 until (1 shl numDiffBits)) { memory[addr] = instruction.value var localDiff = diff val flips = i + 1 xor i for (j in 0 until numDiffBits) { val bit = localDiff.takeLowestOneBit() if (1 shl j and flips != 0) { addr = addr xor bit } localDiff = localDiff xor bit } } } } } return memory.values.sum() } } fun main() { val problem = day14ProblemReader(Day14::class.java.getResource("day14.txt").readText()) println("solution = ${Day14(problem).solvePart1()}") println("solution part2 = ${Day14(problem).solvePart2()}") }
0
Kotlin
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
3,190
adventofcode_2020
MIT License
src/Day19.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime import kotlin.time.TimeSource fun main() { day19Part(1) day19Part(2) } @OptIn(ExperimentalTime::class) fun day19Part(part: Int) { println("=============== Solving part$part") val start = TimeSource.Monotonic.markNow() val dayId = "19" val input = readInput("Day${dayId}") var ans = if (part == 1) 0 else 1 val tl = if (part == 1) 24 else 32 val r = listOf("ore", "clay", "obsidian", "geode") val rc = r.size var totalStates = 0 for ((id0, ss) in input.withIndex()) { val name = "Blueprint ${id0 + 1}: " println(name) check(ss.startsWith(name)) val split = ss.substringAfter(": ").split(".") val ds = Array(rc) { i -> val prefix = "Each ${r[i]} robot costs " val si = split[i].trim() check(si.startsWith(prefix)) { "$si, expect=$prefix" } val rem = si.substring(prefix.length).split(" ") val d = IntArray(rc) for (j in 1 until rem.size) if (rem[j] in r) { val k = r.indexOf(rem[j]) d[k] = rem[j - 1].toInt() } d } val max0 = ds.maxOf { it[0] } var cs = LHS() var ns = LHS() cs.add(1L) fun produce(n: Long): Long { var nn = n for (j in 0 until rc) nn = nn.plus(rc + j, n[j]) return nn } for (t in 1..tl) { val rem = tl - t fun Long.gg(): Int { val g = this[2 * rc - 1] val gr = this[rc - 1] return g + rem * gr } var bestGG = -1 cs.forEach { s -> bestGG = maxOf(bestGG, s.gg()) } cs.forEach { s -> totalStates++ fun addNext(n: Long) { val g = n[2 * rc - 1] val gr = n[rc - 1] val gg = g + rem * gr val estG = gg + rem * (rem - 1) / 2 if (estG <= bestGG) return ns.add(n) } var canBuildCnt = 0 val isMax0 = s[0] >= max0 val i0 = if (isMax0) 1 else 0 build@for (i in i0 until rc) { val d = ds[i] for (j in 0 until rc) if (s[rc + j] < d[j]) continue@build canBuildCnt++ var n = s for (j in 0 until rc) n = n.minus(rc + j, d[j]) n = produce(n) n = n.plus(i, 1) addNext(n) } if (canBuildCnt < rc - i0) { addNext(produce(s)) } } println("$t -> ${ns.size}") cs = ns.also { ns = cs } ns.clear() } var best = 0 cs.forEach { s -> best = maxOf(best, s[2 * rc - 1]) } println("== $best") if (part == 1) { ans += (id0 + 1) * best } else { ans *= best if (id0 == 2) break } } println("---------------> part$part = $ans; " + "analyzed $totalStates states in ${start.elapsedNow().toString(DurationUnit.SECONDS, 3)} sec") } private const val SH = 6 private const val MASK = (1L shl SH) - 1 private operator fun Long.get(i: Int): Int = ((this shr (i * SH)) and MASK).toInt() private fun Long.plus(i: Int, d: Int): Long = this + (d.toLong() shl (i * SH)) private fun Long.minus(i: Int, d: Int): Long = this - (d.toLong() shl (i * SH)) private const val MAGIC = 0x9E3779B9.toInt() private const val TX = ((2/3.0) * (1L shl 32)).toLong().toInt() class LHS(var shift: Int = 29) { var a = LongArray(1 shl (32 - shift)) var size = 0 var tx = TX ushr shift fun clear() { a.fill(0L) size = 0 } fun add(k: Long) { require(k != 0L) if (size >= tx) rehash() val hc0 = k.toInt() * 31 + (k ushr 32).toInt() var i = (hc0 * MAGIC) ushr shift while (true) { if (a[i] == 0L) { a[i] = k size++ return } if (a[i] == k) return if (i == 0) i = a.size i-- } } inline fun forEach(op: (Long) -> Unit) { for (i in 0 until a.size) { if (a[i] != 0L) op(a[i]) } } private fun rehash() { val b = LHS(shift - 1) forEach { k -> b.add(k) } check(b.size == size) shift = b.shift a = b.a tx = b.tx } }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
4,720
aoc-2022
Apache License 2.0
src/main/kotlin/day08/Day08.kt
mdenburger
317,466,663
false
null
package day08 import java.io.File data class Operation(val name: String, val argument: Int) class Program(private val operations: List<Operation>) { private var instruction = 0 private var accumulator = 0 private val visited = BooleanArray(operations.size) fun run(): Int { while (instruction < operations.size && !visited[instruction]) { visited[instruction] = true val operation = operations[instruction] when (operation.name) { "nop" -> instruction += 1 "acc" -> { accumulator += operation.argument instruction += 1 } "jmp" -> instruction += operation.argument else -> error("unknown operation: ${operation.name}") } } return accumulator } fun terminated() = instruction >= operations.size } fun main() { val operations = File("src/main/kotlin/day08/day08-input.txt").readLines().map { val (operationName, argument) = it.split(" ") Operation(operationName, argument.toInt()) } println("Answer 1: " + operations.run()) println("Answer 2: " + operations.modifyAndRun()) } fun List<Operation>.run() = Program(this).run() fun List<Operation>.modifyAndRun(): Int? { forEachIndexed { index, operation -> when (operation.name) { "jmp", "nop" -> { val modifiedOperations = toMutableList() val modifiedOperationName = when (operation.name) { "jmp" -> "nop" "nop" -> "jmp" else -> operation.name } modifiedOperations[index] = Operation(modifiedOperationName, operation.argument) val program = Program(modifiedOperations) val result = program.run() if (program.terminated()) { return result } } } } return null }
0
Kotlin
0
0
b965f465cad30f949874aeeacd8631ca405d567e
2,024
aoc-2020
MIT License
Advent-of-Code-2023/src/Day23.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
private const val AOC_DAY = "Day23" private const val TEST_FILE = "${AOC_DAY}_test" private const val INPUT_FILE = AOC_DAY private fun part1(input: List<String>): Int { val start = Position(0, input.first().indexOf('.')) val end = Position(input.size - 1, input.last().indexOf('.')) val points = mutableListOf(start, end) for ((r, row) in input.withIndex()) { for ((c, char) in row.withIndex()) { if (char == '#') continue var neighbors = 0 for ((nextRow, nextCol) in listOf(Pair(r - 1, c), Pair(r + 1, c), Pair(r, c - 1), Pair(r, c + 1))) { if (nextRow in input.indices && nextCol in input[0].indices && input[nextRow][nextCol] != '#') neighbors++ } if (neighbors >= 3) points.add(Position(r, c)) } } val graph = mutableMapOf<Position, MutableMap<Position, Int>>().apply { points.forEach { this[it] = mutableMapOf() } } val dirs = mutableMapOf( '^' to listOf(Pair(-1, 0)), 'v' to listOf(Pair(1, 0)), '<' to listOf(Pair(0, -1)), '>' to listOf(Pair(0, 1)), '.' to listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) ) for (startingPos in points) { val stack = mutableListOf(Pair(0, Position(startingPos.row, startingPos.col))) val seen = mutableSetOf(Position(startingPos.row, startingPos.col)) while (stack.isNotEmpty()) { val (n, pos) = stack.removeFirst() if (n != 0 && pos in points) { graph[startingPos]!![pos] = n continue } for ((dr, dc) in dirs[input[pos.row][pos.col]]!!) { val nextRow = pos.row + dr val nextCol = pos.col + dc val nextPos = Position(nextRow, nextCol) if (nextRow in input.indices && nextCol in input[0].indices && input[nextRow][nextCol] != '#' && nextPos !in seen) { stack.add(Pair(n + 1, nextPos)) seen.add(nextPos) } } } } val seen = mutableSetOf<Position>() fun dfs(pos: Position): Int { if (pos == end) return 0 var m = 0 seen.add(pos) for (nx in graph[pos]!!) { if (nx.key !in seen) { m = maxOf(m, dfs(nx.key) + graph[pos]!![nx.key]!!) } } seen.remove(pos) return m } return dfs(start) } private fun part2(input: List<String>): Int { val start = Position(0, input.first().indexOf('.')) val end = Position(input.size - 1, input.last().indexOf('.')) val points = mutableListOf(start, end) for ((r, row) in input.withIndex()) { for ((c, char) in row.withIndex()) { if (char == '#') continue var neighbors = 0 for ((nextRow, nextCol) in listOf(Pair(r - 1, c), Pair(r + 1, c), Pair(r, c - 1), Pair(r, c + 1))) { if (nextRow in input.indices && nextCol in input[0].indices && input[nextRow][nextCol] != '#') neighbors++ } if (neighbors >= 3) points.add(Position(r, c)) } } val graph = mutableMapOf<Position, MutableMap<Position, Int>>().apply { points.forEach { this[it] = mutableMapOf() } } for (startingPos in points) { val stack = mutableListOf(Pair(0, Position(startingPos.row, startingPos.col))) val seen = mutableSetOf(Position(startingPos.row, startingPos.col)) while (stack.isNotEmpty()) { val (n, pos) = stack.removeFirst() if (n != 0 && pos in points) { graph[startingPos]!![pos] = n continue } for ((dr, dc) in listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1))) { val nextRow = pos.row + dr val nextCol = pos.col + dc val nextPos = Position(nextRow, nextCol) if (nextRow in input.indices && nextCol in input[0].indices && input[nextRow][nextCol] != '#' && nextPos !in seen) { stack.add(Pair(n + 1, nextPos)) seen.add(nextPos) } } } } val seen = mutableSetOf<Position>() fun dfs(pos: Position): Double { if (pos == end) return 0.0 var m = Double.NEGATIVE_INFINITY seen.add(pos) for (nx in graph[pos]!!) { if (nx.key !in seen) { m = maxOf(m, dfs(nx.key) + graph[pos]!![nx.key]!!) } } seen.remove(pos) return m } return dfs(start).toInt() } fun main() { createTestFiles(AOC_DAY) val testInput = readInputToList(TEST_FILE) val part1ExpectedRes = 94 println("---| TEST INPUT |---") println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes") val part2ExpectedRes = 154 println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = false println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t== 2106" else ""}") println("* PART 2: ${part2(input)}${if (improving) "\t== ???" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
5,215
Advent-of-Code-2023
Apache License 2.0
src/Day14.kt
mikrise2
573,939,318
false
{"Kotlin": 62406}
import java.lang.IndexOutOfBoundsException fun main() { fun createWalls( walls: List<List<Pair<Int, Int>>>, height: Int, width: Int, mapStartX: Int ): List<MutableList<Int>> { val map = List(height) { MutableList(width) { 0 } } walls.forEach { wall -> var current = wall[0] for (i in 1 until wall.size) { if (wall[i].first == current.first) { if (wall[i].second > current.second) { for (j in current.second..wall[i].second) { map[j][current.first - mapStartX] = 1 } } else { for (j in current.second downTo wall[i].second) { map[j][current.first - mapStartX] = 1 } } } else { if (wall[i].first > current.first) { for (j in (current.first - mapStartX)..(wall[i].first - mapStartX)) { map[current.second][j] = 1 } } else { for (j in (current.first - mapStartX) downTo (wall[i].first - mapStartX)) { map[current.second][j] = 1 } } } current = wall[i] } } return map } fun part1(input: List<String>): Int { val walls = input.map { it.split("->").map { coordinates -> val split = coordinates.split(",").map { coordinate -> coordinate.trim().toInt() } Pair(split[0], split[1]) } } val mapStartX = walls.minOf { it.minOf { coordinate -> coordinate.first } } val mapFinishX = walls.maxOf { it.maxOf { coordinate -> coordinate.first } } val mapStartY = 0 val mapFinishY = walls.maxOf { it.maxOf { coordinate -> coordinate.second } } val width = mapFinishX - mapStartX + 1 val height = mapFinishY - mapStartY + 1 val map = createWalls(walls, height, width, mapStartX) var counter = 0 var checker = true inner@ while (checker) { counter++ var position = Pair(500 - mapStartX, 0) while (position.first in 0..mapFinishX - mapStartX && position.second <= mapFinishY) { try { if (map[position.second + 1][position.first] == 0) { position = Pair(position.first, position.second + 1) } else if (map[position.second + 1][position.first - 1] == 0) { position = Pair(position.first - 1, position.second + 1) } else if (map[position.second + 1][position.first + 1] == 0) { position = Pair(position.first + 1, position.second + 1) } else { map[position.second][position.first] = 2 continue@inner } } catch (_: IndexOutOfBoundsException) { checker = false continue@inner } } break } return counter - 1 } fun part2(input: List<String>): Int { val walls = input.map { it.split("->").map { coordinates -> val split = coordinates.split(",").map { coordinate -> coordinate.trim().toInt() } Pair(split[0], split[1]) } } val mapStartX = 0 val mapFinishX = 1000 val mapStartY = 0 val mapFinishY = walls.maxOf { it.maxOf { coordinate -> coordinate.second } } + 2 val width = 1001 val height = mapFinishY - mapStartY + 1 val map = createWalls(walls, height, width, mapStartX) for (i in 0..1000) { map[map.lastIndex][i] = 1 } var counter = 0 var checker = true inner@ while (checker) { counter++ var position = Pair(500 - mapStartX, 0) while (position.first in 0..mapFinishX - mapStartX && position.second <= mapFinishY) { try { if (map[position.second + 1][position.first] == 0) { position = Pair(position.first, position.second + 1) } else if (map[position.second + 1][position.first - 1] == 0) { position = Pair(position.first - 1, position.second + 1) } else if (map[position.second + 1][position.first + 1] == 0) { position = Pair(position.first + 1, position.second + 1) } else { map[position.second][position.first] = 2 if (position.first == 500 && position.second == 0) { break@inner } continue@inner } } catch (_: IndexOutOfBoundsException) { checker = false continue@inner } } break } return counter } val input = readInput("Day14") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8
5,365
Advent-of-code
Apache License 2.0
src/main/kotlin/homework_5/Task1.kt
al-volkov
340,614,622
false
{"Kotlin": 124832}
package homework_5 import java.io.File fun String.isNumber() = this.toIntOrNull() != null enum class OperationType(val operation: String) { Addition("+"), Multiplication("*"), Subtraction("-"), Division("/") } interface ArithmeticTreeNode { fun getValue(): Int override fun toString(): String } class Operand(private val value: Int) : ArithmeticTreeNode { override fun getValue() = value override fun toString() = value.toString() } class Operation( private val type: OperationType, private val leftNode: ArithmeticTreeNode, private val rightNode: ArithmeticTreeNode ) : ArithmeticTreeNode { override fun getValue(): Int { return when (type) { OperationType.Addition -> leftNode.getValue() + rightNode.getValue() OperationType.Multiplication -> leftNode.getValue() * rightNode.getValue() OperationType.Subtraction -> leftNode.getValue() - rightNode.getValue() OperationType.Division -> leftNode.getValue() / rightNode.getValue() } } override fun toString(): String = "(${type.operation} $leftNode $rightNode)" } class ArithmeticTree(path: String) { private val root: ArithmeticTreeNode init { val input = File(path).readText().replace("(", "").replace(")", "").split(" ") root = parseRecursive(input).node } data class RecursiveResult(val node: ArithmeticTreeNode, val newList: List<String>) private fun parseRecursive(list: List<String>): RecursiveResult { if (list.first().isNumber()) { return RecursiveResult(Operand(list.first().toInt()), list.slice(1..list.lastIndex)) } else { val type = when (list.first()) { "+" -> OperationType.Addition "*" -> OperationType.Multiplication "-" -> OperationType.Subtraction "/" -> OperationType.Division else -> throw IllegalArgumentException("arithmetic expression is not correct") } var result = parseRecursive(list.slice(1..list.lastIndex)) val leftNode = result.node result = parseRecursive(result.newList) val rightNode = result.node return RecursiveResult(Operation(type, leftNode, rightNode), result.newList) } } override fun toString() = root.toString() fun getValue() = root.getValue() }
0
Kotlin
0
0
5049681dd2a57625309584a6e50b9a6e0b65948a
2,418
spbu_2020_kotlin_homeworks
Apache License 2.0
src/Day03.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
fun main() { fun priority(item: Char): Int = if (item.isUpperCase()) item.code - 38 else item.code - 96 fun part1(input: List<String>): Int { return input.sumOf { val compartments = it.chunked(it.length / 2) val common = compartments[0].toSet().intersect(compartments[1].toSet()) priority(common.single()) } } fun part2(input: List<String>): Int { val groups = input.chunked(3) return groups.sumOf { val badge = it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()) priority(badge.single()) } } //val input = readInput("Day03_test") //check(part2(input) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
794
aoc-2022
Apache License 2.0
day03/kotlin/RJPlog/day2303_1_2.kt
mr-kaffee
720,687,812
false
{"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314}
import java.io.File import kotlin.math.* fun gearRatio(): Int { var result = 0 val patternSymbol = """\W""".toRegex() val patternPartNumber = """(\d)+""".toRegex() var y = 0 File("day2303_puzzle_input.txt").forEachLine { var matchSymbol = patternSymbol.findAll(it.replace(".", "a")) matchSymbol.forEach { var x = it.range.first //println("${it.value}: $y $x") var yPartNumber = 0 File("day2303_puzzle_input.txt").forEachLine { var matchPartNumber = patternPartNumber.findAll(it) matchPartNumber.forEach { //println(" ${it.value.toInt()}: $yPartNumber, ${it.range}") var rangeCheck = IntRange(it.range.first-1, it.range.last + 1) if (abs(y - yPartNumber) < 2 && rangeCheck.contains(x)) { //println(" -> ok") // if there are more than one symbols adjacent to a number, this has to be reworked. // (swich order, look for partNumber and check for adjacent symbols, break after // first symbol is found.) result += it.value.toInt() } } yPartNumber += 1 } } y += 1 } return result } fun gearRatioPart2(): Int { var result = 0 val patternSymbol = """\*""".toRegex() val patternPartNumber = """(\d)+""".toRegex() var y = 0 File("day2303_puzzle_input.txt").forEachLine { var matchSymbol = patternSymbol.findAll(it) matchSymbol.forEach { var gearRatio = 1 var gearCount = 0 var x = it.range.first var yPartNumber = 0 File("day2303_puzzle_input.txt").forEachLine { var matchPartNumber = patternPartNumber.findAll(it) matchPartNumber.forEach { var rangeCheck = IntRange(it.range.first-1, it.range.last + 1) if (abs(y - yPartNumber) < 2 && rangeCheck.contains(x)) { gearRatio *= it.value.toInt() gearCount += 1 } } yPartNumber += 1 } if (gearCount == 2) result += gearRatio } y += 1 } return result } fun main() { var t1 = System.currentTimeMillis() var solution1 = gearRatio() var solution2 = gearRatioPart2() // print solution for part 1 println("*******************************") println("--- Day 3: Gear Ratios ---") println("*******************************") println("Solution for part1") println(" $solution1 is the sum of all of the part numbers in the engine schematic") println() // print solution for part 2 println("*******************************") println("Solution for part2") println(" $solution2 is the sum of all of the gear ratios in your engine schematic") println() t1 = System.currentTimeMillis() - t1 println("puzzle solved in ${t1} ms") }
0
Rust
2
0
5cbd13d6bdcb2c8439879818a33867a99d58b02f
2,555
aoc-2023
MIT License
src/main/kotlin/lesson2/CyclicRotation.kt
iafsilva
633,017,063
false
null
package lesson2 /** * An array A consisting of N integers is given. * * Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. * * For example, the rotation of array A = [[3, 8, 9, 7, 6]] is [[6, 3, 8, 9, 7]] (elements are shifted right by one index and 6 is moved to the first place). * * The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times. * Write a function: * * fun solution(A: IntArray, K: Int): IntArray * * that, given an array A consisting of N integers and an integer K, returns the array A rotated K times. * * For example, given: * A = [[3, 8, 9, 7, 6]] * K = 3 * the function should return [9, 7, 6, 3, 8]. * * Three rotations were made: * ``` * [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7] * [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9] * [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] * ``` * * For another example, given: * A = [[0, 0, 0]] * K = 1 * the function should return [[0, 0, 0]] * * Given: * A = [[1, 2, 3, 4]] * K = 4 * the function should return [[1, 2, 3, 4]] * * Assume that: * - N and K are integers within the range [[0..100]]; * - each element of array A is an integer within the range [[−1,000..1,000]]. * * In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment. */ class CyclicRotation { fun solution(a: IntArray, k: Int): IntArray { // If no rotation or rotation leaves the array as is, return immediately if (k == 0 || a.isEmpty() || k % a.size == 0) return a // Reduce to the minimum amount of rotations needed val minK = k - (a.size * (k / a.size)) val initialArray = a.toCollection(ArrayDeque()) for (i in 1..minK) initialArray.addFirst(initialArray.removeLast()) return initialArray.toIntArray() } }
0
Kotlin
0
0
5d86aefe70e9401d160c3d87c09a9bf98f6d7ab9
1,954
codility-lessons
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BuyTwoChocolates.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 kotlin.math.max import kotlin.math.min /** * 2706. Buy Two Chocolates * @see <a href="https://leetcode.com/problems/buy-two-chocolates">Source</a> */ sealed interface BuyTwoChocolates { operator fun invoke(prices: IntArray, money: Int): Int data object CheckEveryPairOfChocolate : BuyTwoChocolates { override fun invoke(prices: IntArray, money: Int): Int { // Assume Minimum Cost to be Infinity var minCost = Int.MAX_VALUE // Number of Chocolates val n = prices.size // Check Every Pair of Chocolates for (firstChoco in 0 until n) { for (secondChoco in firstChoco + 1 until n) { // Sum of Prices of the Two Chocolates val cost = prices[firstChoco] + prices[secondChoco] // If the Sum of Prices is Less than the Minimum Cost if (cost < minCost) { // Update the Minimum Cost minCost = cost } } } // We can buy chocolates only if we have enough money return if (minCost <= money) { // Return the Amount of Money Left money - minCost } else { // We cannot buy chocolates. Return the initial amount of money money } } } data object Greedy : BuyTwoChocolates { override fun invoke(prices: IntArray, money: Int): Int { require(prices.size > 1) { return money } prices.sort() val minCost = prices[0] + prices[1] if (minCost <= money) { return money - minCost } return money } } data object CountingSort : BuyTwoChocolates { private const val ARR_SIZE = 101 override fun invoke(prices: IntArray, money: Int): Int { val freq = calculateFrequency(prices) val (minimum, secondMinimum) = findMinimumAndSecondMinimum(freq) val minCost = calculateMinCost(minimum, secondMinimum) return if (minCost <= money) { money - minCost } else { money } } private fun calculateFrequency(prices: IntArray): IntArray { val freq = IntArray(ARR_SIZE) for (p in prices) { freq[p]++ } return freq } private fun findMinimumAndSecondMinimum(freq: IntArray): Pair<Int, Int> { var minimum = 0 var secondMinimum = 0 for (price in 1 until ARR_SIZE) { if (freq[price] > 1) { minimum = price secondMinimum = price break } else if (freq[price] == 1) { minimum = price break } } if (secondMinimum == 0) { secondMinimum = findSecondMinimum(freq, minimum) } return Pair(minimum, secondMinimum) } private fun findSecondMinimum(freq: IntArray, minimum: Int): Int { for (price in minimum + 1 until ARR_SIZE) { if (freq[price] > 0) { return price } } return 0 } private fun calculateMinCost(minimum: Int, secondMinimum: Int): Int { return minimum + secondMinimum } } data object TwoPasses : BuyTwoChocolates { override fun invoke(prices: IntArray, money: Int): Int { require(prices.size > 1) { return money } // Find the index of the minimum price val minIndex = indexMinimum(prices) // Remove the minimum price from the array. // Save the minimum price in a variable minCost var minCost = prices[minIndex] prices[minIndex] = Int.MAX_VALUE // Find the index of the second minimum price // which is the minimum of the remaining array val secondMinIndex = indexMinimum(prices) // Add the second minimum price to minCost minCost += prices[secondMinIndex] // We can buy chocolates only if we have enough money if (minCost <= money) { // Return the Amount of Money Left return money - minCost } // We cannot buy chocolates. Return the initial amount of money return money } private fun indexMinimum(arr: IntArray): Int { // Assume the First Element to be the Minimum var minIndex = 0 // Compare the Assumed Minimum with the Remaining Elements // and update assumed minimum if necessary for (i in 1 until arr.size) { if (arr[i] < arr[minIndex]) { minIndex = i } } // Return the Index of the Minimum Element return minIndex } } data object OnePass : BuyTwoChocolates { override fun invoke(prices: IntArray, money: Int): Int { require(prices.size > 1) { return money } // Assume minimum and second minimum var minimum = min(prices[0].toDouble(), prices[1].toDouble()).toInt() var secondMinimum = max(prices[0].toDouble(), prices[1].toDouble()).toInt() // Iterate over the remaining elements for (i in 2 until prices.size) { if (prices[i] < minimum) { secondMinimum = minimum minimum = prices[i] } else if (prices[i] < secondMinimum) { secondMinimum = prices[i] } } // Minimum Cost val minCost = minimum + secondMinimum // We can buy chocolates only if we have enough money if (minCost <= money) { // Return the Amount of Money Left return money - minCost } // We cannot buy chocolates. Return the initial amount of money return money } } data object Simple : BuyTwoChocolates { private const val ARR_SIZE = 101 override fun invoke(prices: IntArray, money: Int): Int { var min1 = ARR_SIZE var min2 = ARR_SIZE for (price in prices) { if (price < min1) { min2 = min1 min1 = price } else if (price < min2) { min2 = price } } return if ((min1 + min2 <= money)) { money - (min1 + min2) } else { money } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
7,656
kotlab
Apache License 2.0
src/main/kotlin/knn/KnnRegressor.kt
widi-nugroho
280,304,894
false
null
package knn class KnnRegressor (val k:Int,val inputweight:List<Double>){ fun getKNearestNeighbour(sorteddata:List<Pair<Double,DataRegressor>>):List<Pair<Double,DataRegressor>>{ var res= mutableListOf<Pair<Double,DataRegressor>>() for (i in 0..k-1){ res.add(sorteddata[i]) } return res } fun computeDistance(input:DataRegressor, data:List<DataRegressor>):List<Pair<Double,DataRegressor>>{ var res= mutableListOf<Pair<Double,DataRegressor>>() for (i in data){ var dist=Distance.weightedEuclidDistance(inputweight,input,i) res.add(Pair(dist,i)) } return res.sortedWith(compareBy({it.first})) } fun kNearestNeighbourMeanOutput(sorted:List<Pair<Double,DataRegressor>>):Double{ var res=0.0 for (i in sorted){ res+=i.second.output } return res/sorted.size.toDouble() } fun regress(input:List<Double>,data:List<DataRegressor>):Double{ var c=DataRegressor(input,0.0) var cd=computeDistance(c,data) var cd2=getKNearestNeighbour(cd) var md=kNearestNeighbourMeanOutput(cd2) return md } } fun main(){ var weight= listOf<Double>(0.001,1.0,10.0,0.1,1000.0) var test= listOf<Double>(1000.0,0.0,0.3048,71.3,0.00266337) var r=DataAccess.loadAirFoilNoise("/home/widi/projects/kotlin-machine-learning/src/main/resources/airfoil_self_noise.csv") var k2=KnnRegressor(3,weight) println(k2.regress(test,r)) }
0
Kotlin
0
0
139d768e4e02c76193443c06285d918b0fbbfc7f
1,521
kotlin-machine-learning
Apache License 2.0
src/Day10.kt
Donald-rdex
576,629,787
false
{"Kotlin": 3974}
fun main() { fun part1(instructionQueue: ArrayDeque<String>): Int { var registerX = 1 var cycle = 1 val interestingCyles = listOf<Int>(20, 60, 100, 140, 180, 220) var signalStrength: Int var totalSignalStr = 0 while (instructionQueue.isNotEmpty()) { val nextInstruction = instructionQueue.first() if (nextInstruction.matches("""-?\d+""".toRegex())) { registerX += nextInstruction.toInt() } // println("Instru: $cycle\t$nextInstruction\t$registerX\t $signalStrength\t$totalSignalStr") cycle++ if (cycle in interestingCyles) { signalStrength = cycle * registerX totalSignalStr += signalStrength println("Interesting: $cycle\t$registerX\t $signalStrength\t$totalSignalStr") if (cycle == interestingCyles.last()) { return totalSignalStr } } instructionQueue.removeFirst() } return totalSignalStr } fun part2(instructionQueue: ArrayDeque<String>) { var registerX = 1 var cycle = 0 val screenList = arrayListOf<String>("","","","","","") // ######################################## while (cycle <= 239) { val nextInstruction = instructionQueue.first() val pixelLoc = cycle % 40 val spriteLoc = registerX val pixelVal = if (spriteLoc - 1 == pixelLoc || spriteLoc == pixelLoc || spriteLoc + 1 == pixelLoc) { "#" } else { "." } screenList[cycle/40] += pixelVal if (nextInstruction.matches("""-?\d+""".toRegex())) { registerX += nextInstruction.toInt() } cycle++ instructionQueue.removeFirst() } for (line in screenList) { println(line) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day10_test") val inputQueue: ArrayDeque<String> = ArrayDeque() for (instruction in testInput) { instruction.split(" ").forEach { inputQueue.add(it) } } // part1(inputQueue) check(part1(inputQueue) == 13140) val input = readInput("day10_input") inputQueue.clear() for (instruction in input) { instruction.split(" ").forEach { inputQueue.add(it) } } part1(inputQueue) // begin part 2 inputQueue.clear() for (instruction in testInput) { instruction.split(" ").forEach { inputQueue.add(it) } } part2(inputQueue) inputQueue.clear() for (instruction in input) { instruction.split(" ").forEach { inputQueue.add(it) } } part2(inputQueue) }
0
Kotlin
0
0
6d9503a6be80691b9bcb5e2a31e0b483c192e2c1
2,836
kotlin-aoc2022
Apache License 2.0
src/day21/Jobs.kt
g0dzill3r
576,012,003
false
{"Kotlin": 172121}
package day21 import readInput data class Jobs (val map: MutableMap<String, Expression>) { fun evalInputs (symbol: String = ROOT, set: MutableSet<String> = mutableSetOf<String> ()): Set<String> { return evalInputs (map[symbol] as Expression, set) } fun evalInputs (expr: Expression, set: MutableSet<String>): Set<String> { when (expr) { is Expression.Number -> Unit is Expression.Symbol -> { set.add (expr.symbol) evalInputs (expr.symbol, set) } is Expression.Calculation -> { set.add ((expr.left as Expression.Symbol).symbol) set.add ((expr.right as Expression.Symbol).symbol) evalInputs (expr.left, set) evalInputs (expr.right, set) } } return set } val root: Expression.Calculation get () = map[ROOT] as Expression.Calculation fun set (symbol: String, value: Long) = map.put (symbol, Expression.Number (value)) fun eval (symbol: String = ROOT): Expression { val expr = map[symbol] return expr?.let { eval (it) } ?: Expression.Symbol (symbol) } fun eval (expr: Expression): Expression { return when (expr) { is Expression.Number -> { expr } is Expression.Symbol -> { eval (expr.symbol) } is Expression.Calculation -> { val left = eval (expr.left) val right = eval (expr.right) if (left is Expression.Number && right is Expression.Number) { Expression.Number (expr.invoke (left.value, right.value)) } else { Expression.Calculation (left, expr.operation, right) } } } } fun dump () = println (toString ()) override fun toString(): String { return StringBuffer ().apply { map.forEach { (key, value) -> append ("$key: $value\n") } }.toString () } companion object { val ROOT = "root" } } fun loadJobs (example: Boolean): Jobs { val input = readInput (21, example) val map = mutableMapOf<String, Expression> () input.trim ().split ("\n").map { Expression.parse (it, map) } return Jobs (map) } fun main (args: Array<String>) { val example = true val jobs = loadJobs (example) jobs.dump () val symbols = jobs.evalInputs("root") println (symbols) return } // EOF
0
Kotlin
0
0
6ec11a5120e4eb180ab6aff3463a2563400cc0c3
2,604
advent_of_code_2022
Apache License 2.0
src/main/kotlin/Day04.kt
margaret-lin
575,169,915
false
{"Kotlin": 9536}
package main.kotlin fun main() { println(part1(input)) } private val input = readInput("day04_input") private fun part1(input: List<String>): Pair<Int, Int> { val sectionPairs = input.map { line -> val sections = line.split(",") // [2-4, 6-8] val (sectionA, sectionB) = sections.map { rangeString -> val (from, to) = rangeString.split("-").map { it.toInt() } // [2, 4] (from..to).toSet() // [2, 3, 4] } sectionA to sectionB// create Pair [2, 3, 4] [6, 7, 8] } val fullyOverlapping = sectionPairs.count { (a, b) -> a.containsAll(b) || b.containsAll(a) } val overlapping = sectionPairs.count { (a, b) -> a.intersect(b).isNotEmpty() } return fullyOverlapping to overlapping }
0
Kotlin
0
0
7ef7606a04651ef88f7ca96f4407bae7e5de8a45
789
advent-of-code-kotlin-22
Apache License 2.0
kotlin/src/com/leetcode/46_Permutations.kt
programmerr47
248,502,040
false
null
package com.leetcode import kotlin.math.pow /** * We use straightforward approach with helping bit array. * Every time we go into the next level of recursion, * we mark the number as used. * * Tip: * This approach would not work in case of recurrent numbers! * * Time: O(n^n) - actually the total number of permutations is n! * which is less than n^n, but strictly in recursive * permute call we always going through the whole * array of nums independently of depth of recursive * call. Maybe that can be improved somehow to n!, * but I think this will cost taking more space * Space: O(n) */ private class Solution46 { fun permute(nums: IntArray): List<List<Int>> { val result = ArrayList<List<Int>>(nums.size.pow(nums.size)) val bitMask = BooleanArray(nums.size) val sample = ArrayList<Int>(nums.size) permute(result, bitMask, nums, sample) return result } private fun permute(permutations: MutableList<List<Int>>, bitMask: BooleanArray, nums: IntArray, sample: MutableList<Int>) { if (sample.size == nums.size) { permutations.add(ArrayList(sample)) return } nums.forEachIndexed { i, num -> if (!bitMask[i]) { bitMask[i] = true sample.add(num) permute(permutations, bitMask, nums, sample) sample.removeAt(sample.size - 1) bitMask[i] = false } } } private fun Int.pow(other: Int): Int = this.toDouble().pow(other).toInt() } fun main() { val solution = Solution46() println(solution.permute(intArrayOf(1, 2, 3))) println(solution.permute(intArrayOf(3, 2, 1))) println(solution.permute(intArrayOf(0, 1))) println(solution.permute(intArrayOf(666))) println(solution.permute(intArrayOf(1, 2, 4, 8))) println(solution.permute(intArrayOf(1, 2, 4, 8, 9))) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,997
problemsolving
Apache License 2.0
src/Day01.kt
Jenner-Zhl
576,294,907
false
{"Kotlin": 8369}
fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 input.forEach { if (it != "") { current += it.toInt() } else { max = maxOf(max, current) current = 0 } if (current != 0) { max = maxOf(max, current) } } return max } fun part2(input: List<String>): Int { val top3 = intArrayOf(0, 0, 0) fun submitTop3(n: Int) { var min = Int.MAX_VALUE var minIndex = 0 top3.forEachIndexed { index, num -> if (num < min) { min = num minIndex = index } } if (n > min) { top3[minIndex] = n } } var current = 0 input.forEach { if (it != "") { current += it.toInt() } else { submitTop3(current) current = 0 } } if (current != 0) { submitTop3(current) } return top3.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
5940b844155069e020d1859bb2d3fb06cb820981
1,472
aoc
Apache License 2.0
src/main/kotlin/dp/LIS.kt
yx-z
106,589,674
false
null
import util.OneArray import util.max import java.util.* // Longest Increasing Subsequence fun main(args: Array<String>) { // test array val arr = arrayOf(4, 2, 3, 5, 7) println(lenLISDP(arr)) println(lenLISDP2(arr)) println(lenLISDP3(arr)) println(lenLISDPOpt(arr)) } // DP with O(N^2) fun lenLISDP(arr: Array<Int>): Int { val len = arr.size var max = 1 val dp = Array(len) { 1 } for (i in 1 until len) { for (j in 0 until i) { if (arr[i] > arr[j]) { dp[i] = Math.max(dp[i], dp[j] + 1) } } max = Math.max(max, dp[i]) } return max } // another DP with O(N^2) fun lenLISDP2(arr: Array<Int>): Int { val len = arr.size // dp[i] = length of LIS that starts at arr[i] // dp[i] = 0, if i > n // 1 + max(dp[j]) where j > i && arr[j] > arr[i], o/w val dp = IntArray(len) var lenMax = 0 for (i in (len - 1) downTo 0) { dp[i] = 1 + (dp.filterIndexed { j, _ -> j > i && arr[j] > arr[i] }.max() ?: 0) lenMax = maxOf(dp[i], lenMax) } return lenMax } // succinct LIS implementation for OneArray // the algorithm is the same, but i just want to show how expressive Kotlin is! fun OneArray<Int>.lis(): Int { val dp = OneArray(size) { 0 } for (i in size downTo 1) dp[i] = 1 + ((i + 1..size) .filter { this[it] > this[i] } .map { dp[it] } .max() ?: 0) return dp.max() ?: 0 } // yet another DP with O(N^2) fun lenLISDP3(arr: Array<Int>): Int { val len = arr.size val copy = IntArray(len + 1) copy[0] = Int.MIN_VALUE arr.forEachIndexed { i, v -> copy[i + 1] = v } val hold = Array(len + 1) { IntArray(len + 1) } for (col in len downTo 0) { for (row in 0..col) { if (col < len) { hold[row][col] = if (copy[row] > copy[col]) { hold[row][col + 1] } else { maxOf(hold[row][col + 1], 1 + hold[col][col + 1]) } } } } return hold[0][0] } // Optimized DP with O(N log N) fun lenLISDPOpt(arr: Array<Int>): Int { val dp = ArrayList<Int>() arr.forEach { var idx = dp.binarySearch(it) if (idx < 0) { idx = -(idx + 1) } if (idx == dp.size) { dp.add(it) } else { dp[idx] = it } } return dp.size }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,110
AlgoKt
MIT License
src/day02.kt
skuhtic
572,645,300
false
{"Kotlin": 36109}
fun main() { day02.execute(forceBothParts = true) } val day02 = object : Day<Int>(2, 15, 12) { override val testInput: InputData = """ A Y B X C Z """.trimIndent().lines() override fun part1(input: InputData): Int = input .fold(0) { score, line -> line.parseRound().let { (theirHand, ourHand) -> when { theirHand == ourHand -> 3 (theirHand + 1).mod(3) == ourHand -> 6 theirHand == (ourHand + 1).mod(3) -> 0 else -> error("Invalid input") }.let { winScore -> score + winScore + ourHand + 1 } } } override fun part2(input: InputData): Int = input .fold(0) { score, line -> line.parseRound().let { (theirHand, outcome) -> when (outcome) { 0 -> (theirHand - 1).let { if (it < 0) it + 3 else it } 1 -> theirHand 2 -> (theirHand + 1).mod(3) else -> error("Invalid input") }.let { ourHand -> val winScore = outcome * 3 score + winScore + ourHand + 1 } } } fun String.parseRound() = split(' ').let { it.first()[0] - 'A' to it.last()[0] - 'X' } }
0
Kotlin
0
0
8de2933df90259cf53c9cb190624d1fb18566868
1,386
aoc-2022
Apache License 2.0
Advent-of-Code-2023/src/Day05.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
import kotlin.math.max import kotlin.math.min private const val AOC_DAY = "Day05" private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1" private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2" private const val INPUT_FILE = AOC_DAY // destination range start | source range start | range length private data class Range(val destStart: Long, val sourceRange: LongRange) /** * After parsing the input and having a range for each of its lines, check if each seed is contained in the range line. * If so, calculate the corresponding destination value, and add it to the seed list, so it can be evaluated in the * next range line, and so on. * In case the range does not contain a seed, we add it back to the list, since when there is no match, we should * continue with the initial/previous values. */ private fun part1(input: List<String>): Long { val (seeds, almanac) = parseInput(input) var seedsList = seeds for (list in almanac) { val auxList = mutableListOf<Long>() for ((i, seed) in seedsList.withIndex()) { for (range in list) { // If range does not contain seed, evaluate the next input line if (seed !in range.sourceRange) continue // Calculate the corresponding destination value auxList.add(seed - range.sourceRange.first + range.destStart) break } // If there is no mapping, add back the seed if (auxList.size == i) auxList.add(seed) } // Copy the resulting values to the seedsList to evaluate them through the next input lines seedsList = auxList } return seedsList.minOf { it } } /** * Parse the seeds in ranges, verify if they overlap with the next input line, if so calculate the destination value by * subtracting the source from the overlapping values and adding the destination values. Place the resulting ranges * inside the seedsList to evaluate the next line with these new ranges, and so on until reaching the location. If the * overlapped range is not the entire seed range, then we need to add the remaining back to the seedsList. * In case there is no overlapping in the current range lines, then add back the seed range to the seedsList, since * when there is no match, we should continue with the initial/previous values. */ private fun part2(input: List<String>): Long { val (seedsLine, almanac) = parseInput(input) val seeds = seedsLine.chunked(2).map { (start, len) -> start..<start + len } var seedsList = seeds.toMutableList() for (list in almanac) { val auxList = mutableListOf<LongRange>() while (seedsList.size > 0) { val seedRange = seedsList.removeFirst() for (range in list) { val overlapStart = max(seedRange.first, range.sourceRange.first) val overlapEnd = min(seedRange.last, range.sourceRange.last) // If there is no overlap, evaluate the next input line if (overlapStart >= overlapEnd) continue // Verify if there is a remaining in the [seedRange] before and after the overlap range if (overlapStart > seedRange.first) seedsList.add(seedRange.first..overlapStart) if (seedRange.last > overlapEnd) seedsList.add(overlapEnd..seedRange.last) // Calculate the corresponding destination values for the overlapping range: res - src + dst val destinationDiff = - range.sourceRange.first + range.destStart auxList.add(overlapStart + destinationDiff..overlapEnd + destinationDiff) break } // If there is no overlapping, add back the seedRange if (auxList.isEmpty()) auxList.add(seedRange) } // Copy the resulting ranges to the seedsList to evaluate them through the next input lines seedsList = auxList } return seedsList.minOf { it.first } } /** * Parses the input, resulting in a pair of the list of seeds and a list for each block which contains lists for each * line of the corresponding block. Each of these lines is represented as a [Range]. */ private fun parseInput(input: List<String>): Pair<List<Long>, List<List<Range>>> { val seedsLine = input[0].removePrefix("seeds: ").split(" ").map { it.toLong() } val almanac = input .drop(2) .joinToString("\n") .split("\n\n") .map { it .split("\n") .drop(1) .map { range -> val (dst, src, len) = range.split(" ") Range(dst.toLong(), src.toLong()..<src.toLong() + len.toLong()) } } return Pair(seedsLine, almanac) } fun main() { val part1ExpectedRes = 35 val part1TestInput = readInputToList(PART1_TEST_FILE) println("---| TEST INPUT |---") println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes") val part2ExpectedRes = 46 val part2TestInput = readInputToList(PART2_TEST_FILE) println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = true println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t== 51752125" else ""}") println("* PART 2: ${part2(input)}${if (improving) "\t== 12634632" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
5,409
Advent-of-Code-2023
Apache License 2.0
Problems/Algorithms/1202. Smallest String with Swaps/SmallestStringSwaps.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 smallestStringWithSwaps(s: String, pairs: List<List<Int>>): String { val numberOfVertices = s.length val res = CharArray(numberOfVertices) val uf = UnionFind(numberOfVertices) for (pair in pairs) { uf.union(pair.get(0), pair.get(1)) } val map: MutableMap<Int, MutableList<Int>> = mutableMapOf() for (i in 0..numberOfVertices-1) { val key = uf.find(i) val cc: MutableList<Int> if (map.containsKey(key)) { cc = map.get(key)!! } else { cc = mutableListOf() } cc.add(i) map.put(key, cc) } for (key in map.keys) { val componentIndices = map.get(key)!! val componentChars = CharArray(componentIndices.size) var i = 0 for (j in componentIndices) { componentChars[i] = s.get(j) i++ } componentChars.sort() i = 0 for (j in componentIndices) { res[j] = componentChars[i] i++ } } return res.joinToString("") } class UnionFind(numberOfVertices: Int) { val root = IntArray(numberOfVertices) val rank = IntArray(numberOfVertices) init { for (i in 0..numberOfVertices-1) { root[i] = i rank[i] = 1 } } fun find(x: Int): Int { if (x == root[x]) { return x } root[x] = find(root[x]) return root[x] } fun union(x: Int, y: Int): Unit { val rootX = find(x) val rootY = find(y) if (rootX != rootY) { if (rank[rootX] > rank[rootY]) { root[rootY] = rootX } else if (rank[rootX] < rank[rootY]) { root[rootX] = rootY } else { root[rootY] = rootX rank[rootX]++ } } } } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
2,266
leet-code
MIT License
src/main/kotlin/com/github/davio/aoc/y2022/Day4.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2022 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.getInputAsSequence import kotlin.system.measureTimeMillis fun main() { println(Day4.getResultPart1()) measureTimeMillis { println(Day4.getResultPart2()) }.also { println("Took $it ms") } } /** * See [Advent of Code 2022 Day 4](https://adventofcode.com/2022/day/4#part2]) */ object Day4 : Day() { private fun parseLine(line: String) = line.split(",").let { lineParts -> lineParts[0].toIntRange() to lineParts[1].toIntRange() } fun getResultPart1(): Int { fun IntRange.contains(other: IntRange) = this.first in other && this.last in other return getInputAsSequence() .map { line -> parseLine(line) } .count { ranges -> ranges.first.contains(ranges.second) || ranges.second.contains(ranges.first) } } fun getResultPart2(): Int { fun IntRange.overlaps(other: IntRange) = this.first in other || this.last in other || other.first in this return getInputAsSequence() .map { line -> parseLine(line) } .count { ranges -> ranges.first.overlaps(ranges.second) } } private fun String.toIntRange(): IntRange = this.split("-").let { it[0].toInt()..it[1].toInt() } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
1,322
advent-of-code
MIT License
src/main/kotlin/dev/wilerson/aoc/day3/Day03.kt
wilerson
572,902,668
false
{"Kotlin": 8272}
package dev.wilerson.aoc.day3 import dev.wilerson.aoc.utils.readInput fun main() { val input = readInput("day3input") val itemTypes = ('a'..'z') + ('A'..'Z') val priorities = (1 .. 52).toList() val priorityMap = itemTypes.mapIndexed { index, c -> c to priorities[index] }.toMap() // part1(input, priorityMap) val badgeSum = input.chunked(3).sumOf { (first, second, third) -> val badge = first.filter { it in second && it in third }.first() priorityMap[badge] ?: 0 } println(badgeSum) } private fun part1( input: List<String>, priorityMap: Map<Char, Int> ) { val prioritySum = input.sumOf { line -> val (first, second) = line.chunked(line.length / 2) first.filter { it in second }.toList().distinct().sumOf { priorityMap[it] ?: 0 } } println(prioritySum) }
0
Kotlin
0
0
d6121ef600783c18696211d43b62284f4700adeb
847
kotlin-aoc-2022
Apache License 2.0
src/Day01.kt
LesleySommerville-Ki
577,718,331
false
{"Kotlin": 9590}
fun main() { data class Elf ( var calories: Int? = 0 ) fun parseElves(input: List<String>): ArrayDeque<Elf> { val listOfElves = ArrayDeque<Elf>() var currentElf = Elf() input.forEach { if (it == "") { listOfElves.add(currentElf) currentElf = Elf(0) } else { currentElf.calories = currentElf.calories?.plus(it.toInt()) } } return listOfElves } fun part1(input: List<String>): Int { return parseElves(input).maxOf { it.calories!!.toInt() } } fun part2(input: List<String>): Int { val elves = parseElves(input) return elves.map { it.calories }.sortedByDescending { it }.take(3).sumOf { it!!.toInt() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ea657777d8f084077df9a324093af9892c962200
1,038
AoC
Apache License 2.0
atcoder/arc153/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package atcoder.arc153 private const val M = 1e12.toLong() private fun solve(s: IntArray): LongArray? { val n = s.size val sSum = s.sum() val a = LongArray(n) { it + 1L } fun aSum() = a.indices.sumOf { i -> a[i] * s[i] } if (sSum != 0) { val x = M / 4 val delta = (-x - aSum()) / sSum for (i in a.indices) a[i] += delta a[n - 1] -= aSum() return a } if (aSum() <= 0) { a[n - 1] -= aSum() return a } var sCum = 0 for (i in a.indices) { sCum += s[i] if (sCum > 0) { val x = aSum() + 1 for (j in i + 1 until n) a[j] += x a[n - 1] -= aSum() return a } } return null } fun main() { readLn() val s = readInts().toIntArray() val ans = (if (s.last() == 1) solve(s) else solve(s.map { -it }.toIntArray())) ?: return println("No") println("Yes") println(ans.joinToString(" ")) } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
966
competitions
The Unlicense
src/main/kotlin/SimplifySquareRootBigDecimal.kt
BjornvdLaan
459,274,171
false
{"Kotlin": 19109}
import java.math.BigInteger /** * Square root with its coefficient. * * Definitions: a square root is of form 'coefficient * sqrt(radicand)'. * In other words, the coefficient is outside the square root * and the radicand in inside the square root. * * @property coefficient number in front of the radical ('root') sign. * @property radicand number inside the radical ('root') sign. */ data class SquareRootBI(val coefficient: BigInteger, val radicand: BigInteger) /** * Simplifies the square root and makes radicand as small as possible. * * * @param squareRoot the square root to simplify. * @return the simplified square root. */ fun simplifySquareRoot(squareRoot: SquareRootBI): SquareRootBI = if (squareRoot.radicand < BigInteger.ZERO) throw IllegalArgumentException("Radicand cannot be negative") else if (squareRoot.radicand == BigInteger.ZERO) SquareRootBI(BigInteger.ZERO, BigInteger.ZERO) else if (squareRoot.radicand == BigInteger.ONE) SquareRootBI(squareRoot.coefficient, BigInteger.ONE) else { val decreasingSequence = sequence { // We can start at sqrt(radicand) because radicand is // never divisible without remainder by anything greater than i = sqrt(radicand) // This optimization is applied because tests are otherwise very very slow. var bi = squareRoot.radicand.sqrt() while (bi > BigInteger.ONE) { yield(bi) bi = bi.subtract(BigInteger.ONE) } } decreasingSequence .fold(squareRoot) { simplifiedSquareRoot, i -> run { if (simplifiedSquareRoot.radicand.mod(i.pow(2)) == BigInteger.ZERO) { SquareRootBI( simplifiedSquareRoot.coefficient.times(i), simplifiedSquareRoot.radicand.div(i.pow(2)) ) } else { simplifiedSquareRoot } } } }
0
Kotlin
0
0
c6d895d1c011628db4c7c5082e37dc32ac5f9a8a
2,060
KotlinTestApproachExamples
MIT License
src/main/kotlin/com/londogard/summarize/summarizers/EmbeddingClusterSummarizer.kt
londogard
222,868,849
false
null
package com.londogard.summarize.summarizers import com.londogard.embeddings.LightWordEmbeddings import com.londogard.summarize.extensions.* import com.londogard.summarize.extensions.mutableSumByCols import com.londogard.summarize.extensions.normalize import smile.nlp.* import kotlin.math.min import kotlin.math.roundToInt enum class ScoringConfig { Rosselio, Ghalandari } internal class EmbeddingClusterSummarizer( private val threshold: Double, private val simThreshold: Double, private val config: ScoringConfig, embeddingOverload: Pair<String, Int>? ) : Summarizer { private val embeddings = embeddingOverload ?.let { (path, dim) -> LightWordEmbeddings(dim, path) } ?: LightWordEmbeddings() private val zeroArray = Array(embeddings.dimensions) { 0f } private fun String.simplify(): String = normalize().toLowerCase().words().joinToString(" ") private fun getWordsAboveTfIdfThreshold(sentences: List<String>): Set<String> { val corpus = sentences.map { it.bag(stemmer = null) } val words = corpus.flatMap { bag -> bag.keys }.distinct() val bags = corpus.map { vectorize(words.toTypedArray(), it) } val vectors = tfidf(bags) val vector = vectors.mutableSumByCols() val vecMax = vector.max() ?: 1.0 return vector .map { it / vecMax } .mapIndexedNotNull { i, d -> if (d > threshold) words[i] else null } .toSet() } private fun getWordVector(words: Array<String>, allowedWords: Set<String>): Array<Float> = words .filter(allowedWords::contains) .fold(zeroArray) { acc, word -> (embeddings.vector(word) ?: zeroArray) `++` acc } .normalize() private fun getSentenceBaseScoring( cleanSentences: List<String>, rawSentences: List<String>, centroid: Array<Float>, allowedWords: Set<String> ): List<ScoreHolder> = cleanSentences .map { it.words() } .map { words -> getWordVector(words, allowedWords) } .mapIndexed { i, embedding -> val score = embeddings.cosine(embedding, centroid) // Here we can add further scoring params ScoreHolder(i, rawSentences[i], score, embedding) } .sortedByDescending { it.score } /** * This scoring compares using the following: * 1. Don't have a vector to similar to any vector in the current summary * 2. Otherwise just take max that we got by base scoring (comparing single sentence to centroid of document) */ private fun scoreRosellio( numSentences: Int, scoreHolders: List<ScoreHolder> ): List<ScoreHolder> { val selectedIndices = mutableSetOf(0) val selectedVectors = mutableSetOf(scoreHolders.first().vector) return listOf(scoreHolders.first()) + (2..min(numSentences, scoreHolders.size)) .mapNotNull { _ -> scoreHolders.asSequence() .filterNot { selectedIndices.contains(it.i) } .filterNot { score -> selectedVectors .any { selectedVector -> embeddings.cosine(score.vector, selectedVector) > simThreshold } } .firstOrNull() ?.let { maxScore -> selectedVectors.add(maxScore.vector) selectedIndices.add(maxScore.i) maxScore } } } /** * This scoring compares using the following: * 1. Don't have a vector to similar to any vector in the current summary * 2. Create centroid of currSummary + currSen and compare to centroid of whole doc */ private fun scoreGhalandari( numSentences: Int, centroid: Array<Float>, scoreHolders: List<ScoreHolder> ): List<ScoreHolder> { val selectedIndices = mutableSetOf(scoreHolders.first().i) val selectedVectors = mutableSetOf(scoreHolders.first().vector) var centroidSummary = scoreHolders.first().vector return listOf(scoreHolders.first()) + (2..min(numSentences, scoreHolders.size)) .mapNotNull { _ -> scoreHolders .filterNot { selectedIndices.contains(it.i) } .filterNot { score -> selectedVectors.any { selectedVector -> embeddings.cosine(score.vector, selectedVector) > simThreshold } } .maxBy { score -> embeddings.cosine(centroid, (score.vector `++` centroidSummary).normalize()) } ?.let { maxScore -> centroidSummary = (centroidSummary `++` maxScore.vector) selectedVectors.add(maxScore.vector) selectedIndices.add(maxScore.i) maxScore } } } override fun summarize(text: String, lines: Int): String { val sentences = text.sentences() val superCleanSentences = sentences.map { it.simplify() } val wordsOfInterest = getWordsAboveTfIdfThreshold(superCleanSentences) embeddings.addWords(wordsOfInterest) val words = superCleanSentences.flatMap { it.words().toList() } val centroidVector = getWordVector(words.toTypedArray(), wordsOfInterest) val scores = getSentenceBaseScoring(superCleanSentences, sentences.toList(), centroidVector, wordsOfInterest) val finalSentences = when (config) { ScoringConfig.Ghalandari -> scoreGhalandari(lines, centroidVector, scores) ScoringConfig.Rosselio -> scoreRosellio(lines, scores) } return finalSentences.sortedBy { it.i }.joinToString("\n") { it.rawSentence } } override fun summarize(text: String, ratio: Double): String { val lines = text.sentences().size return summarize(text, (lines * ratio).roundToInt().coerceAtLeast(1)) } }
3
Kotlin
0
2
521818ed9057e5ffb58a8ae7b3f0a6c3269e93cc
6,091
summarize-kt
Apache License 2.0
src/main/kotlin/RangeExtraction.kt
Flight552
408,072,383
false
{"Kotlin": 26115, "Assembly": 1320}
//A format for expressing an ordered list of //integers is to use a comma separated list of either // //individual integers //or a range of integers denoted by the //starting integer separated from the end integer in //the range by a dash, '-'. The range includes all //integers in the interval including both endpoints. //It is not considered a range unless it spans at least //3 numbers. For example "12,13,15-17" //Complete the solution so that it takes a //list of integers in increasing order and returns a //correctly formatted string in the range format. // //Example: // //solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]); // returns "-6,-3-1,3-5,7-11,14,15,17-20" object RangeExtraction { fun rangeExtraction(arr: IntArray): String { var listOfRangedNumbers = mutableListOf<Int>() var finalString = "" var rangeString = "" var isNext = false arr.forEachIndexed { index, i -> if (i <= 1) { val nextIndex: Int = try { arr[index + 1] } catch (e: Exception) { arr[index] } if (i == nextIndex - 1) { isNext = true listOfRangedNumbers.add(i) } else { if (isNext) listOfRangedNumbers.add(i) if (listOfRangedNumbers.size > 2) { rangeString = rangeString.plus("${listOfRangedNumbers[0]}-${listOfRangedNumbers[listOfRangedNumbers.size - 1]},") finalString = finalString.plus(rangeString) rangeString = "" listOfRangedNumbers = mutableListOf() } else { listOfRangedNumbers.forEach { finalString = finalString.plus("$it,") } listOfRangedNumbers = mutableListOf() } } } if (i > 1) { val nextIndex: Int = try { arr[index + 1] } catch (e: Exception) { 0 } if (i == nextIndex - 1) { isNext = true listOfRangedNumbers.add(i) } else { if (isNext) listOfRangedNumbers.add(i) if (listOfRangedNumbers.size > 2) { rangeString = rangeString.plus("${listOfRangedNumbers[0]}-${listOfRangedNumbers[listOfRangedNumbers.size - 1]},") finalString = finalString.plus(rangeString) rangeString = "" listOfRangedNumbers = mutableListOf() } else { listOfRangedNumbers.forEach { finalString = finalString.plus("$it,") } listOfRangedNumbers = mutableListOf() } } } if (!isNext) { finalString = finalString.plus("$i,") } } finalString = finalString.dropLast(1) println(finalString) return finalString } } fun main(args: Array<String>) { val array = intArrayOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20) RangeExtraction.rangeExtraction(array) } //best solution fun rangeExtraction( arr: IntArray ): String = arr.fold(emptyList<Pair<Int, Int>>()) { rs, x -> rs.lastOrNull().run { if (this != null && x - second == 1) rs.dropLast(1) + (first to x) else rs + (x to x) } }.joinToString(",") { (x, y) -> if (y - x > 1) "$x-$y" else (x..y).joinToString(",") }
0
Kotlin
0
0
b9fb9378120455c55a413ba2e5a95796612143bc
3,926
codewars
MIT License
src/algorithmdesignmanualbook/datastructures/LargestOccuringOrderedPair.kt
realpacific
234,499,820
false
null
package algorithmdesignmanualbook.datastructures import algorithmdesignmanualbook.print import kotlin.test.assertTrue private data class GenericNode<T>(val value: T?) { val nodes = mutableListOf<GenericNode<T>>() var count = 1 fun add(node: GenericNode<T>) { nodes.add(node) } fun find(str: String): GenericNode<T>? { return nodes.find { it.value == str } } fun print() { val nodeStr = nodes.map { "${it.value} ${it.count}" } println("$value $count $nodeStr") } } private class PairTrie(val rootNode: GenericNode<String> = GenericNode(null)) { var largestCount: Pair<String, Int>? = null private set fun add(on: String? = null, str: String) { // add it on root node if (on == null) { val existingNode = rootNode.find(str) if (existingNode == null) { rootNode.add(GenericNode(str)) } else { existingNode.count++ } } else { val previousNode = rootNode.find(on)!! val existingNode = previousNode.find(str) if (existingNode == null) { previousNode.add(GenericNode(str)) } else { existingNode.count++ if (largestCount == null || largestCount!!.second < existingNode.count) { largestCount = Pair("$on $str", existingNode.count) } } } } fun print() { println(rootNode.value) rootNode.nodes.map(GenericNode<String>::print) } } private fun findLargestOccurringOrderedPair(str: String): String { val trie = PairTrie() val split = str.split(" ") for (i in 0..split.lastIndex) { trie.add(on = null, str = split[i]) } for (i in 1..split.lastIndex) { trie.add(on = split[i - 1], str = split[i]) } trie.print() return trie.largestCount!!.first.print() } fun main() { assertTrue { findLargestOccurringOrderedPair("A new puppy in New York is happy with its New York life") == "New York" } assertTrue { findLargestOccurringOrderedPair("I am running from change change searching for change change") == "change change" } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,234
algorithms
MIT License
src/algorithmsinanutshell/FloydWarshallAlgorithm.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell import utils.PrintUtils import java.lang.Integer.min /** * # All pair shortest path algorithm * * While Dijkstra Shortest Path algorithm helps find shortest path between start and end vertex, [FloydWarshallAlgorithm] * finds the shortest path between all vertices in a [graph] * * [Source](https://www.youtube.com/watch?v=oNI0rf2P9gE) */ class FloydWarshallAlgorithm(val graph: Graph) { private var adjacencyMatrix = Array(graph.vertexCount) { row -> Array(graph.vertexCount) { col -> if (row == col) 0 else Integer.MAX_VALUE } } private fun buildAdjacencyMatrix() { graph.getAllNodes().forEach { startVertex -> startVertex.edges.forEach { val endVertex = it.endVertex adjacencyMatrix[startVertex.value - 1][endVertex.value - 1] = it.weight!! } } } init { buildAdjacencyMatrix() } fun execute() { println("Adjacency Matrix") PrintUtils.printIntArrWithCast(adjacencyMatrix.toList()) for (k in 0 until graph.vertexCount) { for (row in 0 until graph.vertexCount) { for (col in 0 until graph.vertexCount) { if (row == col) { continue } // This is necessary to prevent addition of number with Integer.MAX_VALUE i.e (Integer.MAX_VALUE + N) if (adjacencyMatrix[row][k] == Integer.MAX_VALUE || adjacencyMatrix[k][col] == Integer.MAX_VALUE) { continue } adjacencyMatrix[row][col] = min( adjacencyMatrix[row][col], adjacencyMatrix[row][k] + adjacencyMatrix[k][col] ) } } } println("Shortest Path Matrix") PrintUtils.printIntArrWithCast(adjacencyMatrix.toList()) } } fun main() { val graph = Graph.createWeightedDirectedGraph() val v1 = graph.add(1) val v2 = graph.add(2) val v3 = graph.add(3) val v4 = graph.add(4) v1.connectWith(v2, 3) v1.connectWith(v4, 7) v2.connectWith(v1, 8) v2.connectWith(v3, 2) v3.connectWith(v4, 1) v3.connectWith(v1, 5) v4.connectWith(v1, 2) FloydWarshallAlgorithm(graph).execute() }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,360
algorithms
MIT License
src/Day01.kt
andyludeveloper
573,249,939
false
{"Kotlin": 7818}
fun main() { fun part1(input: List<String>): Int { var sum = 0 var temp = 0 input.forEach { if (it.isEmpty()) { if (temp > sum) { sum = temp } temp = 0 } else { temp += it.toInt() } } return sum } fun part2(input: List<String>): Int { var firstFourItems = MutableList(4){0} val newInput = input + "" var temp = 0 newInput.forEach { if (it.isEmpty()) { firstFourItems[3] = temp firstFourItems = firstFourItems.sorted().reversed().toMutableList() println(firstFourItems) temp = 0 } else { temp += it.toInt() } } return firstFourItems.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
684cf9ff315f15bf29914ca25b44cca87ceeeedf
1,134
Kotlin-in-Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/d19/d19b.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d19 import readInput import java.util.* // > 1175 // > 1183 fun part1b(input: List<String>): Int { var sum = 0 for (line in input) { if (line.isBlank()) continue val (idx, bp) = readBluePrint(line) println(bp) val score = trailB(bp, 0, 0, 0, 1, 0, 0, 0, 24, 0) println("Blueprint $idx -> $score geodes : score = ${idx * score}") sum += idx * score } return sum } fun part2b(input: List<String>): Int { var prod = 1 for (line in input) { if (line.isBlank()) continue val (idx, bp) = readBluePrint(line) if (bp.idx > 3) break println(bp) val score = trailB(bp, 0, 0, 0, 1, 0, 0, 0, 32, 0) println("Blueprint $idx -> $score geodes : score = ${idx * score}") prod *= score } return prod } var orePrice = 1 var clayPrice = 1 var obsPrice = 1 var geodePrice = 1000 var oreRobotPrice = 1 var clayRobotPrice = 1 var obsRobotPrice = 1 var geoRobotPrice = 1 data class State( val ore: Int, val clay: Int, val obs: Int, val geodes: Int, val oreRobots: Int, val clayRobots: Int, val obsRobots: Int, val geoRobots: Int, val timeLeft: Int, ) : Comparable<State> { private val score = timeLeft + orePrice*ore + clayPrice*clay + obsPrice*obs + geodePrice*geodes + oreRobotPrice*oreRobots + clayRobotPrice*clayRobots + obsRobotPrice*obsRobots + geoRobotPrice*geoRobots override fun compareTo(other: State): Int = other.score.compareTo(score) } fun trailB( bp: Blueprint, ore: Int, clay: Int, obs: Int, oreRobots: Int, clayRobots: Int, obsRobots: Int, geoRobots: Int, timeLeft: Int, geodes: Int ): Int { oreRobotPrice = bp.oreCostOre * orePrice clayRobotPrice = bp.clayCostOre * orePrice clayPrice = clayRobotPrice obsRobotPrice = bp.obsCostOre * orePrice + bp.obsCostClay * clayPrice obsPrice = obsRobotPrice geoRobotPrice = bp.geoCostOre * orePrice + bp.geoCostObs * obsPrice val queue = PriorityQueue<State>() queue.add(State(ore, clay, obs, geodes, oreRobots, clayRobots, obsRobots, geoRobots, timeLeft)) var max = 0 val visited = mutableSetOf<State>() while (queue.isNotEmpty()) { val state = queue.poll() if (state in visited) continue else visited.add(state) if (state.timeLeft == 0) { if (state.geodes > max) { println("Max geodes = ${state.geodes}") max = state.geodes } continue } if (state.ore >= bp.geoCostOre && state.obs >= bp.geoCostObs) // if geodeRobot possible, go queue.add( State( state.ore + state.oreRobots - bp.geoCostOre, state.clay + state.clayRobots, state.obs + state.obsRobots - bp.geoCostObs, state.geodes + state.geoRobots, state.oreRobots, state.clayRobots, state.obsRobots, state.geoRobots + 1, state.timeLeft - 1, ) ) else if (state.ore >= bp.obsCostOre && state.clay >= bp.obsCostClay) // hypothesis : if obsidianRobot possible, go queue.add( State( state.ore + state.oreRobots - bp.obsCostOre, state.clay + state.clayRobots - bp.obsCostClay, state.obs + state.obsRobots, state.geodes + state.geoRobots, state.oreRobots, state.clayRobots, state.obsRobots + 1, state.geoRobots, state.timeLeft - 1, ) ) else { if (state.ore >= bp.oreCostOre) queue.add( State( state.ore + state.oreRobots - bp.oreCostOre, state.clay + state.clayRobots, state.obs + state.obsRobots, state.geodes + state.geoRobots, state.oreRobots + 1, state.clayRobots, state.obsRobots, state.geoRobots, state.timeLeft - 1, ) ) if (state.ore >= bp.clayCostOre) queue.add( State( state.ore + state.oreRobots - bp.clayCostOre, state.clay + state.clayRobots, state.obs + state.obsRobots, state.geodes + state.geoRobots, state.oreRobots, state.clayRobots + 1, state.obsRobots, state.geoRobots, state.timeLeft - 1, ) ) queue.add( State( state.ore + state.oreRobots, state.clay + state.clayRobots, state.obs + state.obsRobots, state.geodes + state.geoRobots, state.oreRobots, state.clayRobots, state.obsRobots, state.geoRobots, state.timeLeft - 1 ) ) } } return max } fun main() { //val input = readInput("d19/test") val input = readInput("d19/input1") //println(part1b(input)) println(part2b(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
5,668
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/aoc22/Day05.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc22 import readInput val startingStack = """ [T] [V] [W] [V] [C] [P] [D] [B] [J] [P] [R] [N] [B] [Z] [W] [Q] [D] [M] [T] [L] [T] [N] [J] [H] [B] [P] [T] [P] [L] [R] [D] [F] [P] [R] [P] [R] [S] [G] [M] [W] [J] [R] [V] [B] [J] [C] [S] [S] [B] [B] [F] [H] [C] [B] [N] [L] 1 2 3 4 5 6 7 8 9 """ fun main() { val startingCratePart1 = Crate( stacks = mutableListOf( ArrayDeque(listOf("S", "M", "R", "N", "W", "J", "V", "T")), ArrayDeque(listOf("B", "W", "D", "J", "Q", "P", "C", "V")), ArrayDeque(listOf("B", "J", "F", "H", "D", "R", "P")), ArrayDeque(listOf("F", "R", "P", "B", "M", "N", "D")), ArrayDeque(listOf("H", "V", "R", "P", "T", "B")), ArrayDeque(listOf("C", "B", "P", "T")), ArrayDeque(listOf("B", "J", "R", "P", "L")), ArrayDeque(listOf("N", "C", "S", "L", "T", "Z", "B", "W")), ArrayDeque(listOf("L", "S", "G")), ) ) fun part1(input: List<String>): String { val crate = Crate( stacks = startingCratePart1.stacks.map { it -> ArrayDeque(it.map { it }) }.toMutableList() ) input.forEach { ops -> val moveOperations = ops.toOperations() crate.moveOneAtATime(moveOperations[0], moveOperations[1], moveOperations[2]) } return crate.stacks.joinToString("") { it.last() } } fun part2(input: List<String>): String { val crate = Crate( stacks = startingCratePart1.stacks.map { it -> ArrayDeque(it.map { it }) }.toMutableList() ) input.forEach { ops -> val moveOperations = ops.toOperations() crate.moveMultiple(moveOperations[0], moveOperations[1], moveOperations[2]) } return crate.stacks.joinToString("") { it.last() } } val input = readInput("Day05") println(part1(input)) println(part2(input)) } fun String.toOperations() = filter { it.isDigit() || it.isWhitespace() } .split(" ") .map { it.replace(" ", "") } .map { it.toInt() } data class Crate( val stacks: MutableList<ArrayDeque<String>> ) { fun moveOneAtATime(amount: Int, fromPosition: Int, toPosition: Int) { val moveFrom = fromPosition - 1 val moveTo = toPosition - 1 repeat(amount) { val poppedValue = stacks[moveFrom].removeLast() stacks[moveTo].addLast(poppedValue) } } fun moveMultiple(amount: Int, fromPosition: Int, toPosition: Int) { val moveFrom = fromPosition - 1 val moveTo = toPosition - 1 val toMove = ArrayDeque<String>() repeat(amount) { toMove.addFirst(stacks[moveFrom].removeLast()) } stacks[moveTo].addAll(toMove) } }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
2,886
advent-of-code
Apache License 2.0
src/main/kotlin/io/permutation/PermutationGenerator.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.permutation import io.utils.runTests // Given a number n, generate all the permutations list of 1 to n // https://www.youtube.com/watch?v=V7hHupttzVk class PermutationGenerator { fun execute(input: Int): Array<IntArray> = Array(input.factorial()) { IntArray(input) }.apply { (1..input).forEach { first()[it - 1] = it } var index = 1 while (index < input.factorial()) { var decrease = input - 2 (0 until input).forEach { this[index][it] = this[index - 1][it] } val current = this[index] while (decrease in first().indices && current[decrease] > current[decrease + 1]) { if (decrease == 0) { break } decrease-- } var larger = input - 1 while (current[larger] < current[decrease]) larger-- current.swap(decrease, larger) var right = input - 1 var left = decrease + 1 while (left < right) { current.swap(left, right) left++ right-- } index++ } } private fun IntArray.swap(index0: Int, index1: Int) = this[index0].let { temp -> this[index0] = this[index1] this[index1] = temp } private fun Int.factorial(): Int = when (this) { in 2 until Int.MAX_VALUE -> this * (this - 1).factorial() else -> 1 } } fun main() { runTests(listOf( 2 to listOf(listOf(1, 2), listOf(2, 1)), 3 to listOf(listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1)) )) { (input, value) -> value to PermutationGenerator().execute(input).map { it.toList() }.toList() } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,597
coding
MIT License
kotlin/practice/src/main/kotlin/hackerrank/Arrays.kt
pradyotprksh
385,586,594
false
{"Kotlin": 1973871, "Dart": 1066884, "Python": 313491, "Swift": 147167, "C++": 113494, "CMake": 94132, "Go": 45704, "HTML": 21089, "Ruby": 12424, "Rust": 8550, "C": 7125, "Makefile": 1480, "Shell": 817, "JavaScript": 781, "CSS": 588, "Objective-C": 380, "Dockerfile": 32}
package hackerrank class Arrays { fun solveAllProblems() { println("Solution for hour glass sum problem") val hourglassSumArr = arrayOf( arrayOf(1, 1, 1, 0, 0, 0), arrayOf(0, 1, 0, 0, 0, 0), arrayOf(1, 1, 1, 0, 0, 0), arrayOf(0, 0, 2, 4, 4, 0), arrayOf(0, 0, 0, 2, 0, 0), arrayOf(0, 0, 1, 2, 4, 0), ) printHourGlass(hourglassSumArr) println("The max sum in the given array is ${hourglassSum(hourglassSumArr)}") println() println("Solution for rotate left problem") val leftRotationArr = arrayOf(1, 2, 3, 4, 5) println("Using array ${leftRotationArr.toList()}") val numberOfTurns = (1..10).random() println("After $numberOfTurns rotation new array is ${rotLeft(leftRotationArr, numberOfTurns).toList()}") println() println("Solution for minimum bribes") val minimumBribesArr = arrayOf(1, 2, 5, 3, 7, 8, 6, 4) println("Using array ${minimumBribesArr.toList()}") minimumBribes(minimumBribesArr) } private fun minimumBribes(q: Array<Int>) { var numberOfBribes = 0 for (i in q.indices) { var bribe = 0 if (i < q[i] - 1) bribe = q[i] - (i + 1) if (bribe > 2) { println("Too chaotic") break } else { numberOfBribes += bribe if (i == q.size - 1) { println(numberOfBribes) } } } } private fun rotLeft(a: Array<Int>, d: Int): Array<Int> { if (d % a.size != 0) { for (i in 1..d) { val first = a.first() for (index in 1 until a.size) { a[index - 1] = a[index] } a[a.size - 1] = first } } return a } private fun hourglassSum(arr: Array<Array<Int>>): Int { var maxSum = Int.MIN_VALUE for (row in arr.indices) { if (row + 2 >= arr.size) { continue } for (column in arr[row].indices) { if (column + 2 >= arr[row].size) { continue } var sum = 0 for (rF in 0..2) { for (cF in 0..2) { if (rF == 1) { if (cF == 0 || cF == 2) { continue } } sum += arr[row + rF][column + cF] } } maxSum = maxOf(sum, maxSum) } } return maxSum } private fun printHourGlass(arr: Array<Array<Int>>) { println("The array which we are going to use is") var message = "" for (item in arr) { var itemMessage = "" for (innerItem in item) { itemMessage = "$itemMessage $innerItem" } message = "$message\n$itemMessage" } println(message) println("Converting the array to hourglass images") for (row in arr.indices) { if (row + 2 >= arr.size) { continue } for (column in arr[row].indices) { if (column + 2 >= arr[row].size) { continue } var sum = 0 for (rF in 0..2) { for (cF in 0..2) { if (rF == 1) { if (cF == 0 || cF == 2) { continue } } sum += arr[row + rF][column + cF] } } val first = arr[row + 0][column + 0] val second = arr[row + 0][column + 1] val third = arr[row + 0][column + 2] val fourth = arr[row + 1][column + 1] val fifth = arr[row + 2][column + 0] val sixth = arr[row + 2][column + 1] val seventh = arr[row + 2][column + 2] println("$first $second $third $fourth $fifth $sixth $seventh : Sum=$sum") } } } }
0
Kotlin
10
17
2520dc56fc407f97564ed9f7c086292803d5d92d
4,370
development_learning
MIT License
src/main/kotlin/TrieNode.kt
bgraves-lo
134,632,043
false
{"Kotlin": 7092}
class TrieNode { private val children = mutableMapOf<Char, TrieNode>() private var isWord = false fun add(word: String) { add(word.toLowerCase().asIterable().iterator()) } fun isWord(word: String): Boolean { return isWord(word.toLowerCase().asIterable().iterator()) } fun findWords(letters: String): Set<String> { val sanitizedLetters = letters.toLowerCase().replace("[^a-z.]","") val words = mutableSetOf<String>() findWords(LetterBag(sanitizedLetters), words, "") return words } fun boggleWords(boggleBoard: Boggle): Set<String> { val words = mutableSetOf<String>() boggleBoard.tiles.forEach { tile -> boggleWords(tile, words, "") } return words } private fun add(letters: Iterator<Char>) { if (letters.hasNext()) { val letter = letters.next() val child = children.getOrPut(letter) { TrieNode() } child.add(letters) } else isWord = true } private fun isWord(letters: Iterator<Char>): Boolean { return if (letters.hasNext()) { val letter = letters.next() children[letter]?.isWord(letters) ?: false } else isWord } class LetterBag(letters: String) { private val letterMap = letters.groupingBy { it } .eachCount() .toMutableMap() fun add(letter: Char) { letterMap[letter] = letterMap[letter]?.inc() ?: 1 } fun remove(letter: Char) { letterMap[letter]?.let { if (it > 0) letterMap[letter] = it.dec() } } fun currentSet(): Set<Char> { return letterMap.filterValues { it > 0 }.keys } } private fun findWords(letters: LetterBag, words: MutableSet<String>, word: String) { if (isWord) words.add(word) val currentLetters = letters.currentSet() if (currentLetters.isNotEmpty() && children.isNotEmpty()) { if (currentLetters.contains('.')) { // Deal with blank tiles letters.remove('.') children.forEach { it.value.findWords(letters, words, word + it.key) } letters.add('.') } children.filterKeys { currentLetters.contains(it) } .forEach { letters.remove(it.key) it.value.findWords(letters, words, word + it.key) letters.add(it.key) } } } private fun boggleWords(tile: Boggle.Tile, words: MutableSet<String>, word: String) { if (isWord) words.add(word) val unvisitedNeighbors = tile.unvisitedNeighbors() if (unvisitedNeighbors.isNotEmpty() && children.isNotEmpty()) { tile.visit() unvisitedNeighbors.forEach { neighborTile -> val letter = neighborTile.letter children[letter]?.boggleWords(neighborTile, words, word + letter) } tile.reset() } } }
0
Kotlin
0
0
d1fece663d6936750b951cdbcabcbc5f05b93521
3,120
ktscrabble
Apache License 2.0
base/sdk-common/src/main/java/com/android/projectmodel/SubmodulePath.kt
qiangxu1996
255,410,085
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("SubmodulePathUtil") package com.android.projectmodel /** * Holds a path that uniquely identifies an [Artifact] or [Variant] within an [AndroidSubmodule]. * [SubmodulePath] instances must conform to the [ConfigTableSchema] for their [AndroidSubmodule]. * [Artifact] instances are always identified by the longest-possible paths in the schema. The * parent of an [Artifact] is always the path to its [Variant]. */ data class SubmodulePath internal constructor( val segments: List<String> = emptyList() ) { /** * Adds a segment to this [SubmodulePath]. */ operator fun plus(nextSegment: String): SubmodulePath { return submodulePathOf(segments + nextSegment) } /** * Returns the parent of this [SubmodulePath]. That is, it returns the prefix containing everything * except the last segment. Returns this if the path has no parent. */ fun parent(): SubmodulePath { return if (segments.isEmpty()) this else { submodulePathOf(segments.subList(0, segments.size - 1)) } } /** * The last segment of this path, or the empty string if the path is empty. */ val lastSegment get() = if (segments.isEmpty()) "" else segments.last() /** * Returns the simple name for this path, which is a string in the same format that Gradle * uses to name Variants. See [ConfigPath.simpleName] for details. */ val simpleName get() = toSimpleName(segments) override fun toString(): String { return segments.joinToString("/") } } val emptySubmodulePath = SubmodulePath(listOf()) /** * Returns a [SubmodulePath] given a string with segments separated by slashes. */ fun submodulePathForString(pathString: String) = if (pathString.isEmpty()) emptySubmodulePath else SubmodulePath(pathString.split('/')) /** * Returns a [SubmodulePath] given a list of segments. */ fun submodulePathOf(segments: List<String>) = if (segments.isEmpty()) emptySubmodulePath else SubmodulePath(segments) /** * Returns a [SubmodulePath] given a list of segments. */ fun submodulePathOf(vararg segments: String) = submodulePathOf(segments.toList()) internal fun toSimpleName(input: List<String>) = if (input.isEmpty()) { "main" } else toCamelCase(input) internal fun toCamelCase(input: List<String>) = input.mapIndexed { index, s -> if (index == 0) s.toLowerCase() else s.toLowerCase().capitalize() }.joinToString( "" )
0
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
3,095
vmtrace
Apache License 2.0
src/2022/Day17.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun printField(field: List<Int>) { println(field.reversed().joinToString(separator = "\n") { it.toString(2) .padStart(7, '0') .replace('0', '.') .replace('1', '#') }) } fun part1(input: List<String>): Int { val directions = input.first() var topY = -1 val field = mutableListOf<Int>() var time = 0 (0 until 2022).forEach { rockIndex -> val rock = Rock.values()[rockIndex % 5] while (field.size <= topY + 9) { field.add(0) } var left = 2 var bottom = topY + 4 var currentTop: Int do { val direction = directions[time % directions.length] left = rock.move(direction, field, left, bottom) time++ val canFall = rock.canFall(field, left, bottom - 1) currentTop = bottom + rock.height - 1 bottom-- } while (canFall) rock.settle(field, left, bottom + 1) if (currentTop > topY) topY = currentTop } return topY + 1 } fun part2(input: List<String>): Long { val directions = input.first() var topY = -1 val field = mutableListOf<Int>() var time = 0 val statToIndex = mutableMapOf<PossibleCycle, Int>() val indexToTop = mutableMapOf<Int, Int>() lateinit var cycle: Pair<Int, Int> for(rockIndex in 0 until 1000000000000) { val rock = Rock.values()[(rockIndex % 5).toInt()] while (field.size <= topY + 9) { field.add(0) } var left = 2 var bottom = topY + 4 var currentTop: Int do { val direction = directions[time % directions.length] left = rock.move(direction, field, left, bottom) time++ val canFall = rock.canFall(field, left, bottom - 1) currentTop = bottom + rock.height - 1 bottom-- } while (canFall) rock.settle(field, left, bottom + 1) if (currentTop > topY) topY = currentTop indexToTop[rockIndex.toInt()] = topY if (currentTop > directions.length) { val state = PossibleCycle(field.subList(currentTop - directions.length, currentTop).toList(), time % directions.length, rock) val prevIndex = statToIndex[state] if (prevIndex != null) { cycle = prevIndex to rockIndex.toInt() break } else { statToIndex[state] = rockIndex.toInt() } } } val inCycleRocks = 1000000000000 - cycle.first - 1 val cycleLength = cycle.second - cycle.first val cycleHeight = topY - indexToTop[cycle.first]!! val inCycleHeight = (inCycleRocks / cycleLength) * cycleHeight val restHeight = indexToTop[(inCycleRocks % cycleLength).toInt() + cycle.first]!! return inCycleHeight + restHeight + 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 3068) check(part2(testInput) == 1514285714288) val input = readInput("Day17") println(part1(input)) println(part2(input)) } @Suppress("EnumEntryName") enum class Rock(val width: Int, val height: Int) { first(4, 1), second(3, 3), third(3, 3), fourth(1, 4), fifth(2, 2), } fun Rock.canFall(field: List<Int>, left: Int, bottom: Int): Boolean { if (bottom < 0) return false return when(this) { Rock.first -> field[bottom][left] or field[bottom][left + 1] or field[bottom][left + 2] or field[bottom][left + 3] == 0 Rock.second -> field[bottom + 1][left] or field[bottom + 1][left + 1] or field[bottom + 1][left + 2] or field[bottom][left + 1] or field[bottom + 2][left + 1] == 0 Rock.third -> field[bottom][left] or field[bottom][left + 1] or field[bottom][left + 2] or field[bottom + 1][left + 2] or field[bottom + 2][left + 2] == 0 Rock.fourth -> field[bottom][left] or field[bottom + 1][left] or field[bottom + 2][left] or field[bottom + 3][left] == 0 Rock.fifth -> field[bottom][left] or field[bottom][left + 1] or field[bottom + 1][left] or field[bottom + 1][left + 1] == 0 } } fun Rock.move(direction: Char, field: List<Int>, left: Int, bottom: Int): Int { return when(direction) { '<' -> if (left >= 1 && canFall(field, left - 1, bottom)) left - 1 else left '>' -> if (left + width < 7 && canFall(field, left + 1, bottom)) left + 1 else left else -> error("Should be < or >") } } fun Rock.settle(field: MutableList<Int>, left: Int, bottom: Int) { when(this) { Rock.first -> { field[bottom] += 0b1111 shl (3 - left) } Rock.second -> { field[bottom + 2] += 0b010 shl (4 - left) field[bottom + 1] += 0b111 shl (4 - left) field[bottom] += 0b010 shl (4 - left) } Rock.third -> { field[bottom + 2] += 0b001 shl (4 - left) field[bottom + 1] += 0b001 shl (4 - left) field[bottom] += 0b111 shl (4 - left) } Rock.fourth -> { field[bottom + 3] += 1 shl (6 - left) field[bottom + 2] += 1 shl (6 - left) field[bottom + 1] += 1 shl (6 - left) field[bottom] += 1 shl (6 - left) } Rock.fifth -> { field[bottom + 1] += 0b11 shl (5 - left) field[bottom] += 0b11 shl (5 - left) } } } private operator fun Int.get(index: Int): Int { return if (((1 shl (6 - index)) and this) == 0) 0 else 1 } private data class PossibleCycle(val lastRocks: List<Int>, val position: Int, val rock: Rock)
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
6,089
aoc-2022-in-kotlin
Apache License 2.0
src/Day01.kt
meletios
573,316,028
false
{"Kotlin": 4032}
import java.util.InputMismatchException fun main() { fun part1(input: List<String>): Int { var maxCalories: Int = 0 var tempSum: Int = 0 input.forEach { line -> when (val test = line.toIntOrNull()) { null -> { if (tempSum > maxCalories) { maxCalories = tempSum } tempSum = 0 } else -> tempSum += test } } return maxCalories } fun part2(input: List<String>): Int { var firstMaxCalories = 0 var secondMaxCalories = 0 var thirdMaxCalories = 0 var tempSum: Int = 0 fun test() { if (tempSum > firstMaxCalories) { thirdMaxCalories = secondMaxCalories secondMaxCalories = firstMaxCalories firstMaxCalories = tempSum } else if (tempSum > secondMaxCalories) { thirdMaxCalories = secondMaxCalories secondMaxCalories = tempSum } else if (tempSum > thirdMaxCalories) { thirdMaxCalories = tempSum } } input.forEachIndexed { index, line -> when (val test = line.toIntOrNull()) { null -> { test() tempSum = 0 } else -> { tempSum += test if (index == input.size - 1) { test() } } } } return firstMaxCalories + secondMaxCalories + thirdMaxCalories } // test if implementation meets criteria from the description, like: val testInputPart1 = readInput("Day01_test") check(part1(testInputPart1) == 24000) val testInputPart2 = readInput("Day01_test") check(part2(testInputPart2) == 45000) val input = readInput("Day01") println(part2(input)) }
0
Kotlin
0
0
25549bde439b949f6dd091ccd69beb590d078787
2,001
advent-of-code-2022
Apache License 2.0
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Prims_Algorithm/Prims_Algorithm.kt
rajatenzyme
325,100,742
false
{"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189}
import java.util.* internal class Edge(var from: Int, var to: Int, var weight: Int) internal object Prims { /** * Function to compute MST * * @param graph * @return mst */ private fun prims(graph: ArrayList<ArrayList<Edge?>>): ArrayList<Edge?> { // ArrayList to store obtained MST val mst = ArrayList<Edge?>() // Priority Queue which gives minimum weight edge val pq = PriorityQueue(Comparator { edge1: Edge?, edge2: Edge? -> if (edge1!!.weight < edge2!!.weight) return@Comparator -1 else if (edge1.weight > edge2.weight) return@Comparator 1 else return@Comparator 0 }) // add the source vertex in Priority queue pq.addAll(graph[0]) var cost = 0.0 val size = graph.size val visited = BooleanArray(size) // mark source vertex as visited visited[0] = true // Keep extracting edges till priority is not empty while (!pq.isEmpty()) { // extract edge with minimum weight from priority queue val edge = pq.peek() // pop the edge from priority queue pq.poll() if (visited[edge!!.to] && visited[edge.from]) continue // mark the from vertex as visited visited[edge.from] = true // if the adjacent vertex to source is unvisited, add the edge to the priority queue for (edge1 in graph[edge.to]) { if (!visited[edge1!!.to]) pq.add(edge1) } // mark the adjacent vertex as visited visited[edge.to] = true // add the edge in minimum spanning tree cost += edge.weight mst.add(edge) } println("Total cost of MST: $cost") return mst } /** * Function to create adjacency list representation of graph * @param edges * @param nodes * @return graph */ private fun createGraph(edges: Array<Edge?>, nodes: Int): ArrayList<ArrayList<Edge?>> { // initialise graph as Adjacency List val graph = ArrayList<ArrayList<Edge?>>() // for adding Arraylist to Arraylist for (i in 0 until nodes) graph.add(ArrayList()) // Create adjacency list from the edge connectivity information for (source in edges) { val destination = Edge(source!!.from, source.to, source.weight) graph[source.from].add(source) graph[source.to].add(destination) } // Return constructed graph return graph } /** * Main Function * @param args */ @JvmStatic fun main(args: Array<String>) { // initialise number of nodes and edges val nodes = 7 val countEdges = 10 /* Input Graph is: 0 / \ / \ 1 ------ 2 / \ / \ 3 -- 4 -- 5 -- 6 */ val edges = arrayOfNulls<Edge>(countEdges) // initialising edges with from, to and weight value edges[0] = Edge(0, 1, 10) edges[1] = Edge(0, 2, 15) edges[2] = Edge(1, 2, 7) edges[3] = Edge(2, 5, 6) edges[4] = Edge(1, 3, 12) edges[5] = Edge(1, 4, 9) edges[6] = Edge(4, 5, 14) edges[7] = Edge(3, 4, 13) edges[8] = Edge(5, 6, 8) edges[9] = Edge(2, 6, 12) // Adjacency List representation of graph val graph = createGraph(edges, nodes) // ArrayList to store final MST obtained val mst = prims(graph) println("Minimum Spanning Tree:") for (edge in mst) println(edge!!.from.toString() + " - " + edge.to + " : " + edge.weight) } } /** * Input Graph is: * 0 * / \ * / \ * 1-----2 * / \ / \ * 3---4-5---6 * * Output: * Total cost: 52.0 * Minimum Spanning Tree: * 0 - 1 : 10.0 * 1 - 2 : 7.0 * 2 - 5 : 6.0 * 5 - 6 : 8.0 * 1 - 4 : 9.0 * 1 - 3 : 12.0 * */
0
C++
0
0
65a0570153b7e3393d78352e78fb2111223049f3
4,012
Coding-Journey
MIT License
AOC-2023/src/main/kotlin/Day02.kt
sagar-viradiya
117,343,471
false
{"Kotlin": 72737}
import utils.* const val RED_BALLS = 12 const val BLUE_BALLS = 14 const val GREEN_BALLS = 13 object Day02 { fun part01(input: String): Int { val games = input.splitAtNewLines() return games.mapIndexed { index, s -> Pair(index, s.splitAtColon()[1]) }.map { sets -> val isPossible = sets.first + 1 sets.second.splitAtSemiColon().forEach outer@{ set -> set.splitAtComma().forEach { balls -> val semiSet = balls.splitAtWhiteSpace() val number = semiSet[0].toInt() val requiredNumber = when (semiSet[1]) { "red" -> RED_BALLS "blue" -> BLUE_BALLS "green" -> GREEN_BALLS else -> throw IllegalStateException("Freak out!") } if (requiredNumber < number) { return@map 0 } } } isPossible }.sum() } fun part02(input: String): Int { val games = input.splitAtNewLines() return games.map { game -> game.splitAtColon()[1] }.sumOf { sets -> var reqRed = 0 var reqBlue = 0 var reqGreen = 0 sets.splitAtSemiColon().forEach outer@{ set -> set.splitAtComma().forEach { balls -> val semiSet = balls.splitAtWhiteSpace() val actualNumber = semiSet[0].toInt() when (semiSet[1]) { "red" -> if (reqRed < actualNumber) { reqRed = actualNumber } "blue" -> if (reqBlue < actualNumber) { reqBlue = actualNumber } "green" -> if (reqGreen < actualNumber) { reqGreen = actualNumber } else -> throw IllegalStateException("Freak out!") } } } reqRed * reqBlue * reqGreen } } }
0
Kotlin
0
0
7f88418f4eb5bb59a69333595dffa19bee270064
2,207
advent-of-code
MIT License
src/Day03.kt
dominik003
573,083,805
false
{"Kotlin": 9376}
fun main() { fun calcCharValue(char: Char): Int { if (char.isLowerCase()) { return (char.code - 97) + 1 } return (char.code - 65) + 27 } fun part1(input: List<String>): Int { var prioritySum = 0 input.forEach { val compartments: List<String> = it.chunked(it.length / 2) val wrongItems = compartments[0].toCharArray().toSet() intersect compartments[1].toCharArray().toSet() wrongItems.forEach { c -> prioritySum += calcCharValue(c) } } return prioritySum } fun part2(input: List<String>): Int { var prioritySum = 0 input.chunked(3).forEach { val groupBadge = it[0].toCharArray().toSet() intersect it[1].toCharArray().toSet() intersect it[2].toCharArray().toSet() prioritySum += calcCharValue(groupBadge.first()) } return prioritySum } // test if implementation meets criteria from the description, like: val testInput = readInput(3, true) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput(3) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b64d1d4c96c3dd95235f604807030970a3f52bfa
1,230
advent-of-code-2022
Apache License 2.0
src/main/kotlin/aoc2017/DigitalPlumber.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.commaSeparatedInts import komu.adventofcode.utils.nonEmptyLines fun pipesConnectedTo(startPipe: Int, input: String): Int { val pipesById = buildPipes(input) val start = pipesById[startPipe]!! val connected = mutableSetOf<Int>() collectConnected(start, connected) return connected.size } fun totalPipeGroups(input: String): Int { val pipes = buildPipes(input).values.toMutableSet() var count = 0 while (pipes.isNotEmpty()) { removeReachable(pipes.first(), pipes) count++ } return count } private fun removeReachable(pipe: Pipe, reachable: MutableSet<Pipe>) { if (reachable.remove(pipe)) for (neighbor in pipe.connections) removeReachable(neighbor, reachable) } private fun collectConnected(pipe: Pipe, visited: MutableSet<Int>) { if (visited.add(pipe.id)) for (neighbor in pipe.connections) collectConnected(neighbor, visited) } private fun buildPipes(input: String): Map<Int, Pipe> { val definitions = input.nonEmptyLines().map(PipeDefinition.Companion::parse) val pipesById = definitions.map { Pipe(it.id) }.associateBy { it.id } for (definition in definitions) { val pipe = pipesById[definition.id]!! for (connection in definition.connections) { val neighbor = pipesById[connection]!! pipe.connections += neighbor neighbor.connections += pipe } } return pipesById } private class Pipe(val id: Int) { val connections = mutableListOf<Pipe>() } private data class PipeDefinition(val id: Int, val connections: List<Int>) { companion object { private val regex = Regex("""(\d+) <-> (.+)""") fun parse(line: String): PipeDefinition { val m = regex.matchEntire(line) ?: error("no match for '$line'") return PipeDefinition( id = m.groupValues[1].toInt(), connections = m.groupValues[2].commaSeparatedInts()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,074
advent-of-code
MIT License
src/Day23.kt
kuangbin
575,873,763
false
{"Kotlin": 8252}
fun main() { fun part1(input: List<String>): Int { var positions = buildSet{ for (i in 0 until input.size) { for (j in 0 until input[i].length) { if (input[i][j] == '#') { add(i to j) } } } } for (i in 0 until 10) { positions = gao(positions, i) } val minX = positions.minBy { it.first }.first val maxX = positions.maxBy { it.first }.first val minY = positions.minBy { it.second }.second val maxY = positions.maxBy { it.second }.second return (maxX - minX + 1) * (maxY - minY + 1) - positions.size } fun part2(input: List<String>): Int { var positions = buildSet{ for (i in 0 until input.size) { for (j in 0 until input[i].length) { if (input[i][j] == '#') { add(i to j) } } } } var ii = 0 while (true) { var stable = true for (position in positions) { var num = 0 for (i in -1..1) { for (j in -1..1) { if (i == 0 && j == 0) { continue } if ((position.first+i to position.second+j) in positions) { num++ } } } if (num != 0) { stable = false break } } if (stable) { break } positions = gao(positions, ii) ii++ } return ii+1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day23_test") check(part1(testInput) == 110) println(part2(testInput)) val input = readInput("Day23") println(part1(input)) println(part2(input)) } val dir0 = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) val dir1 = listOf(-1 to -1, 1 to -1, -1 to -1, -1 to 1) val dir2 = listOf(-1 to 1, 1 to 1, 1 to -1, 1 to 1) fun gao(positions: Set<Pair<Int, Int>>, st: Int): Set<Pair<Int, Int>> { val mp = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() for (position in positions) { val x = position.first val y = position.second var numOfAround = 0 for (i in -1..1) { for (j in -1..1) { if (i == 0 && j == 0) { continue } if (positions.contains(x+i to y+j)) { numOfAround++ } } } if (numOfAround == 0) { mp[position] = position continue } for (i in 0 until 4) { val x1 = x + dir0[(i+st)%4].first val y1 = y + dir0[(i+st)%4].second val x2 = x + dir1[(i+st)%4].first val y2 = y + dir1[(i+st)%4].second val x3 = x + dir2[(i+st)%4].first val y3 = y + dir2[(i+st)%4].second if ((x1 to y1) !in positions && (x2 to y2) !in positions && (x3 to y3) !in positions) { mp[position] = x1 to y1 break } } if (!mp.contains(position)) { mp[position] = position } } val posNum = mutableMapOf<Pair<Int, Int>, Int>() for (position in positions) { posNum[mp[position]!!] = posNum.getOrDefault(mp[position], 0) + 1 } return buildSet { for (position in positions) { if (posNum[mp[position]] == 1) { add(mp[position]!!) } else { add(position) } } } }
0
Kotlin
0
0
ea0d89065b4d3cb4f6f78f768882d5b5473624d1
3,209
advent-of-code-2022
Apache License 2.0
aoc_2023/src/main/kotlin/problems/day2/CubeConundrum.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day2 class CubeConundrum(val games: List<CubeGame>) { companion object { fun fromLines(input: List<String>): CubeConundrum { val mutableListGames: MutableList<CubeGame> = mutableListOf() for (line in input) { val (gameStr, contentStr) = line.split(":") val gameId = gameStr.split(" ")[1].toInt() val gamesStr = contentStr.split(";") val rounds: MutableList<CubeRound> = mutableListOf() for (gameSplit in gamesStr) { val spaceSplit = gameSplit.replace(",", "").split(" ") val cubes = mutableMapOf( "red" to 0, "green" to 0, "blue" to 0 ) for (i in spaceSplit.indices) { val el = spaceSplit[i] if (cubes.containsKey(el)) { cubes[el] = spaceSplit[i - 1].toInt() } } val cubeRound = CubeRound(cubes["red"]!!, cubes["green"]!!, cubes["blue"]!!) rounds.add(cubeRound) } val game = CubeGame(gameId, rounds) mutableListGames.add(game) } return CubeConundrum(mutableListGames) } } fun sumIdPossibleGames(maxRound: CubeRound): Int { return this.games.fold(0) { acc, game -> val isPossible = game.isPossibleGame(maxRound) acc + if (isPossible) game.id else 0 } } fun sumPowersMinimumSets(): Int { return this.games.fold(0) { acc, it -> acc + it.minimumSet().powerSet() } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
1,787
advent-of-code-2023
MIT License
src/main/kotlin/year2023/Day02.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 class Day02 { companion object { @JvmStatic val maxColorNumbers = mapOf( "red" to 12, "green" to 13, "blue" to 14 ) } fun parseLine(line: String): Pair<Int, List<Pair<String, Int>>> { val (lineStart, lineEnd) = line.split(':') val gameNumber = lineStart.removePrefix("Game ").toInt() val colorList = lineEnd.split(';').flatMap { iteration -> val colors = iteration.split(',').map { it.trim() } colors.map { it.split(' ') }.map { it[1] to it[0].toInt() } } return gameNumber to colorList } fun part1(input: String): Int { return input.lines() .filter { it.isNotBlank() } .map { line -> val (gameNumber, colorList) = parseLine(line) if (colorList.all { pair -> maxColorNumbers[pair.first]!! >= pair.second }) { gameNumber } else { 0 } }.sum() } fun part2(input: String): Int { return input.lines() .filter { it.isNotBlank() } .map { line -> buildMap<String, Int> { parseLine(line).second.forEach { pair -> put(pair.first, maxOf(getOrDefault(pair.first, 0), pair.second)) } }.values.reduce(Int::times) }.sum() } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,481
aoc-2022
Apache License 2.0
src/Day10.kt
benwicks
572,726,620
false
{"Kotlin": 29712}
fun main() { // 20th, 60th, 100th, 140th, 180th, and 220th cycles val interestingPositions = generateSequence(20) { it + 40 }.take(6).toList() fun isInterestingCycle(cycleNumber: Int): Boolean { return cycleNumber in interestingPositions } fun part1(input: List<String>): Int { var sumOfCycleNumberAndSignalStrengthProducts = 0 // sum every 20th signal strength * its cycle # var cycleNumber = 0 var registerXValue = 1 for (operation in input) { if (operation == "noop") { cycleNumber++ if (isInterestingCycle(cycleNumber)) { sumOfCycleNumberAndSignalStrengthProducts += (cycleNumber * registerXValue) } } else { cycleNumber++ if (isInterestingCycle(cycleNumber)) { sumOfCycleNumberAndSignalStrengthProducts += (cycleNumber * registerXValue) } cycleNumber++ if (isInterestingCycle(cycleNumber)) { sumOfCycleNumberAndSignalStrengthProducts += (cycleNumber * registerXValue) } registerXValue += operation.split(" ")[1].toInt() } } // Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. // What is the sum of these six signal strengths? return sumOfCycleNumberAndSignalStrengthProducts } fun isSpriteInCurrentDrawPixel(cycleIndex: Int, registerXValue: Int) = cycleIndex % 40 in registerXValue - 1..registerXValue + 1 fun part2(input: List<String>) { // It seems like the X register controls the horizontal position of a sprite. Specifically, the sprite is 3 pixels wide, and the X register sets the horizontal position of the middle of that sprite. // (In this system, there is no such thing as "vertical position": if the sprite's horizontal position puts its pixels where the CRT is currently drawing, then those pixels will be drawn.) // If the sprite is positioned such that one of its three pixels is the pixel currently being drawn, the screen produces a lit pixel (#); otherwise, the screen leaves the pixel dark (.). var cycleIndex = 0 var registerXValue = 1 val imageOutputPixels = mutableListOf<Boolean>() for (operation in input) { if (operation == "noop") { imageOutputPixels += isSpriteInCurrentDrawPixel(cycleIndex, registerXValue) cycleIndex++ } else { imageOutputPixels += isSpriteInCurrentDrawPixel(cycleIndex, registerXValue) cycleIndex++ imageOutputPixels += isSpriteInCurrentDrawPixel(cycleIndex, registerXValue) cycleIndex++ registerXValue += operation.split(" ")[1].toInt() } } // Render the image given by your program. What eight capital letters appear on your CRT? imageOutputPixels.chunked(40).forEach { line -> println(line.map { if (it) '#' else '.' }.joinToString("")) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13_140) println(part2(testInput)) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
fbec04e056bc0933a906fd1383c191051a17c17b
3,437
aoc-2022-kotlin
Apache License 2.0
src/mathFunctions/FunctionEvaluator.kt
hopshackle
225,904,074
false
null
package mathFunctions import evodef.* import kotlin.AssertionError import kotlin.random.Random class FunctionEvaluator(val f: NTBEAFunction, val searchSpace: FunctionSearchSpace) : SolutionEvaluator { private val rnd = Random(System.currentTimeMillis()) override fun optimalFound() = false override fun optimalIfKnown() = null override fun logger() = EvolutionLogger() var nEvals = 0 override fun searchSpace() = searchSpace override fun reset() { nEvals = 0 } override fun nEvals() = nEvals override fun evaluate(settings: IntArray): Double { return evaluate(searchSpace.convertSettings(settings)) } override fun evaluate(settings: DoubleArray): Double { nEvals++ return if (rnd.nextDouble() < f.functionValue(settings)) 1.0 else -1.0 } } fun main(args: Array<String>) { val f = when (args[0]) { "Hartmann3" -> Hartmann3 "Hartmann6" -> Hartmann6 "Branin" -> Branin "GoldsteinPrice" -> GoldsteinPrice else -> throw AssertionError("Unknown function ${args[0]}") } FunctionExhaustiveResult(f, FunctionSearchSpace(f.dimension, args[1].toInt())).calculate() } class FunctionExhaustiveResult(val f: NTBEAFunction, val searchSpace: FunctionSearchSpace) { // We run through every possible setting in the searchSpace, and run maxGames, logging the average result val stateSpaceSize = (0 until searchSpace.nDims()).fold(1, { acc, i -> acc * searchSpace.nValues(i) }) val allRanges = (0 until searchSpace.nDims()).map { 0 until searchSpace.nValues(it) } fun addDimension(start: List<List<Int>>, next: IntRange): List<List<Int>> { return start.flatMap { list -> next.map { list + it } } } val allOptions = allRanges.fold(listOf(emptyList<Int>()), { acc, r -> addDimension(acc, r) }) fun calculate() { val optionScores = allOptions.map { val evaluator = FunctionEvaluator(f, searchSpace) val params = it.toIntArray() // StatsCollator.clear() val perfectScore = f.functionValue(searchSpace.convertSettings(params)) println("${params.joinToString()} has mean score ${String.format("%.3g", perfectScore)}") // println(StatsCollator.summaryString()) params to perfectScore } val numberPositive = optionScores.filter { it.second > 0.0 }.count().toDouble() val sortedScores = optionScores.sortedBy { it.second }.reversed().take(50) println("Best scores are : \n" + sortedScores.joinToString("\n") { String.format("\t%.3g at %s", it.second, it.first.joinToString()) }) println("A total of ${String.format("%.1f%% are above zero", 100.0 * numberPositive / optionScores.size)}") } } class FunctionSearchSpace(val dimensions: Int, val valuesPerDimension: Int) : SearchSpace { val increment = 1.0 / valuesPerDimension override fun nDims(): Int { return dimensions } override fun nValues(i: Int): Int { return valuesPerDimension } override fun name(i: Int): String { return "" } override fun value(i: Int, j: Int): Double { return j * increment } fun convertSettings(settings: IntArray): DoubleArray { return settings.withIndex().map { value(it.index, it.value) }.toDoubleArray() } }
0
Kotlin
0
0
e5992d6b535b3f4a6552bf6f2351865a33d56248
3,380
SmarterSims
MIT License
src/main/day25/day25.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day25 import kotlin.math.pow import kotlin.math.roundToLong import readInput val UNSNAFU = mapOf( "=" to -2.0, "-" to -1.0, "0" to 0.0, "1" to 1.0, "2" to 2.0, ) fun main() { val input = readInput("main/day25/Day25") println(part1(input)) } fun part1(input: List<String>): String { val numbers = input.associateBy { it.unsnafucate() } return numbers.keys.sum().snafucate() } fun Long.snafucate(): String { return generateSequence(this) { (it + 2) / 5 } .takeWhile { it != 0L }.toList() .map { "012=-"[(it % 5).toInt()] } .joinToString("").reversed() } fun String.unsnafucate(): Long { return indices.sumOf { (5.0.pow(it) * UNSNAFU[this[length - it - 1].toString()]!!.toLong()).roundToLong() } }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
793
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/searching/BinarySearch.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.searching fun main() { val items = listOf(5, 6, 4, 3, 10, 9, 5, 6, 7) print("items: $items \n") val sorted = items.sorted() print("items: $items \n") print("trying to find 10, index: ${binarySearch(sorted, 10)} - ${rank(sorted, 10)} \n") // 8 print("trying to find 10, index: ${binarySearch(sorted, 6)} - ${rank(sorted, 6)} \n") // 4 print("trying to find 10, index: ${binarySearch(sorted, 0)} - ${rank(sorted, 0)} \n") // -1 } // O(log(n)) time | O(1) space private fun binarySearch(items: List<Int>, target: Int): Int { var low = 0 var high = items.size - 1 while (low <= high) { val mid = low + (high - low) / 2 when { items[mid] < target -> low = mid + 1 items[mid] > target -> high = mid - 1 else -> return mid } } return -1 } // O(log(n)) time | O(log(n)) space cause of stack call private fun rank(items: List<Int>, item: Int): Int { return rank(items, item, 0, items.size) } private fun rank(items: List<Int>, item: Int, low: Int, high: Int): Int { if (low > high) return -1 val mid = (low + high) / 2 val guess = items[mid] return when { guess == item -> mid guess > item -> rank(items, item, low, mid - 1) else -> rank(items, item, mid + 1, high) } }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,376
algs4-leprosorium
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindLeaves.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 /** * Find Leaves of Binary Tree * @see <a href="https://leetcode.com/problems/find-leaves-of-binary-tree/">Source</a> */ fun interface FindLeaves { operator fun invoke(root: TreeNode?): List<List<Int>> } /** * Approach 1: DFS (Depth-First Search) with sorting */ class FindLeavesDFS : FindLeaves { private val pairs: MutableList<Pair<Int, Int>> = ArrayList() override operator fun invoke(root: TreeNode?): List<List<Int>> { getHeight(root) // sort all the (height, val) pairs pairs.sortBy { it.first } val n = pairs.size var height = 0 var i = 0 val solution: MutableList<List<Int>> = ArrayList() while (i < n) { val nums: MutableList<Int> = ArrayList() while (i < n && pairs[i].first == height) { nums.add(pairs[i].second) i++ } solution.add(nums) height++ } return solution } private fun getHeight(root: TreeNode?): Int { // return -1 for null nodes if (root == null) return -1 // first calculate the height of the left and right children val leftHeight = getHeight(root.left) val rightHeight = getHeight(root.right) // based on the height of the left and right children, obtain the height of the current (parent) node val currHeight = max(leftHeight, rightHeight) + 1 // collect the pair -> (height, val) this.pairs.add(currHeight to root.value) // return the height of the current node return currHeight } } /** * Approach 2: DFS (Depth-First Search) without sorting */ class FindLeavesDFS2 : FindLeaves { private val solution: MutableList<MutableList<Int>> = ArrayList() override operator fun invoke(root: TreeNode?): List<List<Int>> { getHeight(root) return this.solution } private fun getHeight(root: TreeNode?): Int { // return -1 for null nodes if (root == null) { return -1 } // first calculate the height of the left and right children val leftHeight = getHeight(root.left) val rightHeight = getHeight(root.right) val currHeight = max(leftHeight, rightHeight) + 1 if (solution.size == currHeight) { solution.add(ArrayList<Int>()) } solution[currHeight].add(root.value) return currHeight } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,145
kotlab
Apache License 2.0
src/main/kotlin/g2201_2300/s2290_minimum_obstacle_removal_to_reach_corner/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2201_2300.s2290_minimum_obstacle_removal_to_reach_corner // #Hard #Array #Breadth_First_Search #Matrix #Heap_Priority_Queue #Graph #Shortest_Path // #2023_06_28_Time_765_ms_(100.00%)_Space_66.1_MB_(100.00%) import java.util.PriorityQueue import java.util.Queue class Solution { fun minimumObstacles(grid: Array<IntArray>): Int { val n = grid.size val m = grid[0].size val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0)) val q: Queue<State> = PriorityQueue { a: State, b: State -> a.removed - b.removed } q.add(State(0, 0, 0)) val visited = Array(n) { BooleanArray(m) } visited[0][0] = true while (q.isNotEmpty()) { val state = q.poll() if (state.r == n - 1 && state.c == m - 1) { return state.removed } for (d in dirs) { val nr = state.r + d[0] val nc = state.c + d[1] if (nr < 0 || nc < 0 || nr == n || nc == m || visited[nr][nc]) { continue } visited[nr][nc] = true val next = State(nr, nc, state.removed) if (grid[nr][nc] == 1) { next.removed++ } q.add(next) } } return -1 } private class State(var r: Int, var c: Int, var removed: Int) }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,448
LeetCode-in-Kotlin
MIT License
src/Day16.kt
frungl
573,598,286
false
{"Kotlin": 86423}
import kotlin.math.max @OptIn(ExperimentalStdlibApi::class) fun main() { fun part1(input: List<String>): Int { val name = input.map { it.substringAfter("Valve ").substringBefore(' ') } val flow = input.map { it.substringAfter("rate=").substringBefore(';').toInt() } val leads = input.map { it.split(' ').drop(9).map { str -> when { str.last() == ',' -> str.dropLast(1) else -> str } }} val n = name.size val ind = mutableMapOf<String, Int>() name.forEachIndexed { i, s -> ind[s] = i } val can = mutableListOf<Int>() (0..<n).forEach { if (flow[it] != 0) can.add(it) } val mask = (1 shl can.size) val dp = MutableList(31) { MutableList(n) { MutableList(mask) { -1 } } } dp[0][ind["AA"]!!][0] = 0 var ans = 0 val go = leads.map { it.map { s -> ind[s]!! } } for (time in (0..<30)) { for (v in (0..<n)) { for (lmask in (0..<mask)) { if (dp[time][v][lmask] == -1) continue val nval = dp[time][v][lmask] + (0..<can.size).sumOf { when { ((lmask shr it) and 1) == 1 -> flow[can[it]] else -> 0 } } if (flow[v] != 0) { val pos = can.binarySearch(v) if (((lmask shr pos) and 1) == 0) { val nmask = lmask or (1 shl pos) if (dp[time + 1][v][nmask] < nval) { dp[time + 1][v][nmask] = nval ans = max(ans, nval) } } } go[v].forEach { if (dp[time + 1][it][lmask] < nval) { dp[time + 1][it][lmask] = nval ans = max(ans, nval) } } } } } return ans } fun part2(input: List<String>): Int { val name = input.map { it.substringAfter("Valve ").substringBefore(' ') } val flow = input.map { it.substringAfter("rate=").substringBefore(';').toInt() } val leads = input.map { it.split(' ').drop(9).map { str -> when { str.last() == ',' -> str.dropLast(1) else -> str } }} val n = name.size val ind = mutableMapOf<String, Int>() name.forEachIndexed { i, s -> ind[s] = i } val can = mutableListOf<Int>() (0..<n).forEach { if (flow[it] != 0) can.add(it) } val mask = (1 shl can.size) val dp = MutableList(27) { MutableList(n) { MutableList(n) { mutableMapOf<Int, Int>() } } } dp[0][ind["AA"]!!][ind["AA"]!!][0] = 0 var ans = 0 val go = leads.map { it.map { s -> ind[s]!! } } for (time in (0..<26)) { for (v in (0..<n)) { for (u in (0..<n)) { val tmp = dp[time][v][u].keys.sortedDescending() val was = mutableListOf<Int>() for (lmask in tmp) { var uniq = true for (w in was) { if (w and lmask == lmask) { uniq = false break; } } if (!uniq) continue was.add(lmask) val nval = dp[time][v][u][lmask]!! + (0..<can.size).sumOf { when { ((lmask shr it) and 1) == 1 -> flow[can[it]] else -> 0 } } var nmask = lmask if (flow[v] != 0) { val pos = can.binarySearch(v) nmask = nmask or (1 shl pos) val tmask = lmask or (1 shl pos) go[u].forEach { nu -> if ((dp[time + 1][v][nu][tmask] ?: -1) < nval) { dp[time + 1][v][nu][tmask] = nval ans = max(ans, nval) } } } if (flow[u] != 0) { val pos = can.binarySearch(u) nmask = nmask or (1 shl pos) val tmask = lmask or (1 shl pos) go[v].forEach { nv -> if ((dp[time + 1][nv][u][tmask] ?: -1) < nval) { dp[time + 1][nv][u][tmask] = nval ans = max(ans, nval) } } } if ((dp[time + 1][v][u][nmask] ?: -1) < nval) { dp[time + 1][v][u][nmask] = nval ans = max(ans, nval) } go[v].forEach { nv -> go[u].forEach { nu -> if ((dp[time + 1][nv][nu][lmask] ?: -1) < nval) { dp[time + 1][nv][nu][lmask] = nval ans = max(ans, nval) } } } } dp[time][v][u].clear() } } } return ans } val testInput = readInput("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
6,164
aoc2022
Apache License 2.0
src/Day06.kt
andyludeveloper
573,249,939
false
{"Kotlin": 7818}
fun main() { val test1 = "bvwbjplbgvbhsrlpgdmjqwftvncz" val test2 = "nppdvjthqldpwncqszvftbrmjlhg" val test3 = "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg" val test4 = "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" println(solution(test1, 1)) check(solution(test1, 1) == 5) check(solution(test2, 1) == 6) check(solution(test3, 1) == 10) check(solution(test4, 1) == 11) val input = readInputToText("Day06") println(solution(input, 1)) val test5 = "mjqjpqmgbljsphdztnvjfqwrcgsmlb" check(solution(test5, 2) == 19) println(solution(input, 2)) } fun solution(string: String, part: Int): Int { val windowSize = if (part == 1) 4 else 14 return string.toCharArray().toList().windowed(windowSize).map { it.toSet() }.map { it.size == windowSize } .indexOf(true) + windowSize }
0
Kotlin
0
1
684cf9ff315f15bf29914ca25b44cca87ceeeedf
822
Kotlin-in-Advent-of-Code-2022
Apache License 2.0
year2019/src/main/kotlin/net/olegg/aoc/year2019/day16/Day16.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2019.day16 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2019.DayOf2019 import kotlin.math.abs /** * See [Year 2019, Day 16](https://adventofcode.com/2019/day/16) */ object Day16 : DayOf2019(16) { override fun first(): Any? { val input = data.map { it - '0' } return (0..<100) .fold(input) { list, _ -> list.indices.map { index -> list.asSequence() .zip(makePhase(index + 1)) { a, b -> a * b } .sum() .let { abs(it % 10) } } } .take(8) .joinToString(separator = "") } override fun second(): Any? { val input = data.map { it - '0' } val position = data.substring(0, 7).toInt() val largeInput = sequence { repeat(10000) { yieldAll(input) } } val tail = largeInput.drop(position).toList().asReversed() return (0..<100) .fold(tail) { list, _ -> list.runningReduce { acc, item -> acc + item } .map { abs(it % 10) } } .takeLast(8) .reversed() .joinToString(separator = "") } private val BASE_PHASE = listOf(0, 1, 0, -1) private fun makePhase(index: Int): Sequence<Int> { return sequence { while (true) { BASE_PHASE.forEach { base -> repeat(index) { yield(base) } } } }.drop(1) } } fun main() = SomeDay.mainify(Day16)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,434
adventofcode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinMaxGasDist.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.math.BigDecimal import java.math.RoundingMode import java.util.PriorityQueue import kotlin.math.ceil import kotlin.math.max import kotlin.math.min /** * 774. Minimize Max Distance to Gas Station */ fun interface MinMaxGasDist { operator fun invoke(stations: IntArray, k: Int): Double companion object { const val LIMIT = 999999999.0 } } /** * Approach #1: Dynamic Programming [Memory Limit Exceeded] */ val minMaxGasDistDP = MinMaxGasDist { stations, station -> val n: Int = stations.size val deltas = DoubleArray(n - 1) for (i in 0 until n - 1) { deltas[i] = (stations[i + 1] - stations[i]).toDouble() } val dp = Array(n - 1) { DoubleArray( station + 1, ) } for (i in 0..station) { dp[0][i] = deltas[0] / (i + 1) } for (p in 1 until n - 1) for (k in 0..station) { var bns = MinMaxGasDist.LIMIT for (x in 0..k) bns = min(bns, max(deltas[p] / (x + 1), dp[p - 1][k - x])) dp[p][k] = bns } dp[n - 2][station] } /** * Approach #2: Brute Force [Time Limit Exceeded] */ val minMaxGasDistBruteForce = MinMaxGasDist { stations, station -> val n: Int = stations.size val deltas = DoubleArray(n - 1) for (i in 0 until n - 1) { deltas[i] = (stations[i + 1] - stations[i]).toDouble() } val count = IntArray(n - 1) { 1 } for (k in 0 until station) { var best = 0 for (i in 0 until n - 1) if (deltas[i] / count[i] > deltas[best] / count[best]) best = i count[best]++ } var ans = 0.0 for (i in 0 until n - 1) ans = max(ans, deltas[i] / count[i]) ans } /** * Approach #3: Heap [Time Limit Exceeded] */ val minMaxGasDistHeap = MinMaxGasDist { stations, station -> val n: Int = stations.size val pq: PriorityQueue<IntArray> = PriorityQueue<IntArray> { a, b -> if (b[0].toDouble() / b[1] < a[0].toDouble() / a[1] ) { -1 } else { 1 } } for (i in 0 until n - 1) pq.add(intArrayOf(stations[i + 1] - stations[i], 1)) for (k in 0 until station) { val node: IntArray = pq.poll() node[1]++ pq.add(node) } val node: IntArray = pq.poll() node[0].toDouble() / node[1] } /** * Approach #4: Binary Search */ class MinMaxGasDistBS : MinMaxGasDist { override operator fun invoke(stations: IntArray, k: Int): Double { if (stations.isEmpty() || k <= 0) return 0.0 val n: Int = stations.size var start = 0.0 var end = (stations[n - 1] - stations[0]).toDouble() while (start <= end) { val mid = start + (end - start) / 2 var count = 0 for (i in 0 until n - 1) count += (ceil((stations[i + 1] - stations[i]) / mid) - 1).toInt() if (count > k) { start = mid + DELTA } else { end = mid - DELTA } } val decimal = BigDecimal(start).setScale(5, RoundingMode.HALF_EVEN) return decimal.toDouble() } companion object { private const val DELTA = 1e-6 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,795
kotlab
Apache License 2.0
kotlin/1857-largest-color-value-in-a-directed-graph.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
class Solution { fun largestPathValue(colors: String, edges: Array<IntArray>): Int { val adj = HashMap<Int, ArrayList<Int>>() for ((from, to) in edges) adj[from] = adj.getOrDefault(from, ArrayList<Int>()).apply{this.add(to)} val visited = HashSet<Int>() val path = HashSet<Int>() val count = Array(colors.length){IntArray(26)} fun dfs(node: Int): Int { if (node in path) return Integer.MAX_VALUE if (node in visited) return 0 visited.add(node) path.add(node) val colorIndex = colors[node] - 'a' count[node][colorIndex] = 1 adj[node]?.forEach{ nei -> if (dfs(nei) == Integer.MAX_VALUE) return Integer.MAX_VALUE (0 until 26).forEach{ c -> count[node][c] = maxOf( count[node][c], count[nei][c] + if(c == colorIndex) 1 else 0 ) } } path.remove(node) return count[node].max()!! } var res = 0 for (i in 0 until colors.length) { res = maxOf(res, dfs(i)) } return if(res == Integer.MAX_VALUE) -1 else res } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,350
leetcode
MIT License
advent2022/src/main/kotlin/year2022/Day23.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import Point2D import findAllPositionsOf import year2022.Day23.Direction.* typealias PointComputation = Point2D.() -> Set<Point2D> class Day23 : AdventDay(2022, 23) { private val Point2D.allNeighbors: Set<Point2D> get() = entries.map { this + it.pointDiff }.toSet() private val northNeighbor: PointComputation get() = { listOf(N, NE, NW).map { it.pointDiff + this }.toSet() } private val southNeighbor: PointComputation get() = { listOf(S, SE, SW).map { it.pointDiff + this }.toSet() } private val westNeighbor: PointComputation get() = { listOf(W, SW, NW).map { it.pointDiff + this }.toSet() } private val eastNeighbor: PointComputation get() = { listOf(E, SE, NE).map { it.pointDiff + this }.toSet() } private fun checkInRound(round: Int): List<Pair<PointComputation, Direction>> = when (round % 4) { 0 -> listOf(northNeighbor to N, southNeighbor to S, westNeighbor to W, eastNeighbor to E) 1 -> listOf(southNeighbor to S, westNeighbor to W, eastNeighbor to E, northNeighbor to N) 2 -> listOf(westNeighbor to W, eastNeighbor to E, northNeighbor to N, southNeighbor to S) 3 -> listOf(eastNeighbor to E, northNeighbor to N, southNeighbor to S, westNeighbor to W) else -> error("only 0..3 can be computed mod 4") } private fun Point2D.proposeMove(allElfs: Set<Point2D>, round: Int): Point2D? = when { (allNeighbors intersect allElfs).isEmpty() -> null else -> checkInRound(round) .firstOrNull { (check, _) -> (this.check() intersect allElfs).isEmpty() } ?.let { (_, dir) -> this + dir.pointDiff } } enum class Direction(val pointDiff: Point2D) { N(Point2D(0, -1)), NE(Point2D(1, -1)), NW(Point2D(-1, -1)), S(Point2D(0, 1)), SE(Point2D(1, 1)), SW(Point2D(-1, 1)), W(Point2D(-1, 0)), E(Point2D(1, 0)) } private fun Set<Point2D>.simulateForXRounds(x: Int, startRoundNumber: Int = 0): Set<Point2D> { var current = this repeat(x) { round -> val proposed = current.map { it.proposeMove(current, round + startRoundNumber) } val moves = current.zip(proposed) current = buildSet { moves.forEach { (orig, next) -> add(when { next == null -> orig proposed.count { it == next } == 1 -> next else -> orig }) } } } return current } override fun part1(input: List<String>): Long { val elfsAfter10Rounds = input.findAllPositionsOf().simulateForXRounds(10) val minX = elfsAfter10Rounds.minOf { it.x } val minY = elfsAfter10Rounds.minOf { it.y } val maxX = elfsAfter10Rounds.maxOf { it.x } val maxY = elfsAfter10Rounds.maxOf { it.y } val lengthX = maxX - minX + 1 val lengthY = maxY - minY + 1 return (lengthX * lengthY) - elfsAfter10Rounds.size } override fun part2(input: List<String>): Int { var curRound = 1 var prev = input.findAllPositionsOf() var curr = prev.simulateForXRounds(1, 0) while (prev != curr) { prev = curr curr = prev.simulateForXRounds(1, curRound) curRound += 1 } return curRound } } fun main() = Day23().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
3,481
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindAndReplacePattern.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT /** * Find and Replace Pattern * @see <a href="https://leetcode.com/problems/find-and-replace-pattern/">Source</a> */ fun interface FindAndReplacePattern { operator fun invoke(words: Array<String>, pattern: String): List<String> } class FRPTwoMaps : FindAndReplacePattern { override operator fun invoke(words: Array<String>, pattern: String): List<String> { val ans: MutableList<String> = ArrayList() for (word in words) if (match(word, pattern)) ans.add(word) return ans } private fun match(word: String, pattern: String): Boolean { val m1: MutableMap<Char?, Char?> = HashMap() val m2: MutableMap<Char?, Char?> = HashMap() for (i in word.indices) { val w = word[i] val p = pattern[i] if (!m1.containsKey(w)) m1[w] = p if (!m2.containsKey(p)) m2[p] = w if (m1[w] != p || m2[p] != w) return false } return true } } class FRPOneMap : FindAndReplacePattern { override operator fun invoke(words: Array<String>, pattern: String): List<String> { val ans: MutableList<String> = ArrayList() for (word in words) if (match(word, pattern)) ans.add(word) return ans } private fun match(word: String, pattern: String): Boolean { val m: MutableMap<Char?, Char?> = HashMap() for (i in word.indices) { val w = word[i] val p = pattern[i] if (!m.containsKey(w)) m[w] = p if (m[w] != p) return false } val seen = BooleanArray(ALPHABET_LETTERS_COUNT) for (p in m.values) { if (seen[p?.minus('a')!!]) return false seen[p - 'a'] = true } return true } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,447
kotlab
Apache License 2.0
src/Day24.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import java.util.PriorityQueue import kotlin.math.abs fun main() { val windUp = 0b0001 val windRight = 0b0010 val windDown = 0b0100 val windLeft = 0b1000 class Map(val width: Int = 120, val height: Int = 25) { private val winds = Array(width * height) { 0 } fun addWind(x: Int, y: Int, direction: Int) { winds[y * width + x] += direction } fun nextMap(): Map { val map = Map(width, height) forEach { x, y, wind -> if (wind and windUp > 0) map.addWind(x, (y + height - 1) % height, windUp) if (wind and windRight > 0) map.addWind((x + 1) % width, y, windRight) if (wind and windDown > 0) map.addWind(x, (y + 1) % height, windDown) if (wind and windLeft > 0) map.addWind((x + width - 1) % width, y, windLeft) } return map } fun forEach(f: (x: Int, y: Int, wind: Int) -> Unit) { (0 until height).forEach { y -> (0 until width).forEach { x -> f(x, y, winds[y * width + x]) } } } fun isFree(x: Int, y: Int): Boolean { return x == 0 && y == -1 || x == 119 && y == 25 || x in 0..119 && y in 0..24 && winds[y * width + x] == 0 } override fun toString(): String { val buffer = StringBuffer() forEach {x, y, wind -> if (x == 0 && y > 0) buffer.appendLine() when (wind) { windUp -> buffer.append("^") windRight -> buffer.append(">") windDown -> buffer.append("v") windLeft -> buffer.append("<") 0 -> buffer.append(".") else -> buffer.append( (if (wind and windUp > 0) 1 else 0) + (if (wind and windRight > 0) 1 else 0) + (if (wind and windDown > 0) 1 else 0) + (if (wind and windLeft > 0) 1 else 0) ) } } return buffer.toString() } } class Position(val x: Int = 0, val y: Int = -1, val time: Int = 0) { fun nextPositions(nextMap: Map): List<Position> { return listOfNotNull( Position(x, y, time + 1).takeIf { nextMap.isFree(x, y) }, Position(x + 1, y, time + 1).takeIf { nextMap.isFree(x + 1, y) }, Position(x - 1, y, time + 1).takeIf { nextMap.isFree(x - 1, y) }, Position(x, y - 1, time + 1).takeIf { nextMap.isFree(x, y - 1) }, Position(x, y + 1, time + 1).takeIf { nextMap.isFree(x, y + 1) }, ) } // override fun compareTo(other: Position): Int { // return 2 * (other.y - y) + 10 * (other.x - x) + time - other.time // } // override fun toString(): String { return "($x, $y, $time)" } override fun equals(other: Any?): Boolean { other as Position return other.x == x && other.y == y && other.time == time } override fun hashCode(): Int { return 120 * y + x + 3000 * time } } fun parseInput(input: List<String>): Map { val map = Map() input.drop(1).dropLast(1).forEachIndexed { y, line -> line.drop(1).dropLast(1).forEachIndexed { x, char -> map.addWind(x, y, when (char) { '^' -> windUp; '>' -> windRight; 'v' -> windDown; '<' -> windLeft; else -> 0 }) } } return map } fun generateMaps(map: Map): List<Map> { val list = mutableListOf(map) repeat(599) { list.add(list.last().nextMap()) } return list } class ForwardComparator: Comparator<Position> { override fun compare(o1: Position, o2: Position): Int { return 2 * (o2.y - o1.y) + 10 * (o2.x - o1.x) + o2.time - o1.time } } class BackwardComparator: Comparator<Position> { override fun compare(o1: Position, o2: Position): Int { return 2 * (o1.y - o2.y) + 10 * (o1.x - o2.x) + o2.time - o1.time } } fun findBest(maps: List<Map>, initialPosition: Position, goalX: Int, goalY: Int, comparator: Comparator<Position>): Int { val toExplore = PriorityQueue(comparator) toExplore.add(initialPosition) val explored = mutableListOf<Position>() var bestTiming = initialPosition.time + 1000 while (toExplore.isNotEmpty()) { val position = toExplore.poll() if (position.x == goalX && position.y == goalY) { if (position.time < bestTiming) { bestTiming = position.time println("New best : $bestTiming") } continue } if (position.time + abs(goalX - position.x) + abs(goalY - position.y) >= bestTiming) { continue } if (position in explored) { continue } explored.add(position) position.nextPositions(maps[(position.time + 1) % 600]).forEach { if (it !in toExplore) toExplore.add(it) } } return bestTiming } fun part1(maps: List<Map>): Int { return findBest(maps, Position(), 119, 25, ForwardComparator()) } fun part2(maps: List<Map>): Int { val position1 = Position() val position2 = Position(119, 25, findBest(maps, position1, 119, 25, ForwardComparator())) val position3 = Position(0, -1, findBest(maps, position2, 0, -1, BackwardComparator())) return findBest(maps, position3, 119, 25, ForwardComparator()) } val input = readInput("Day24") val maps = generateMaps(parseInput(input)) println(part1(maps)) println(part2(maps)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
6,005
aoc2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/PrimePalindrome.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 dev.shtanko.algorithms.DECIMAL import dev.shtanko.algorithms.extensions.isPrime import kotlin.math.pow /** * Prime Palindrome * @see <a href="https://leetcode.com/problems/prime-palindrome/">Source</a> */ fun interface PrimePalindrome { operator fun invoke(n: Int): Int } /** * Approach 1: Iterate Palindromes * Time Complexity: O(N). * Space Complexity: O(logN). */ class IteratePalindromes : PrimePalindrome { override operator fun invoke(n: Int): Int { for (L in 1..MAX) { // Check for odd-length palindromes val local = DECIMAL.toDouble().pow((L - 1).toDouble()).toInt() for (root in local until DECIMAL.toDouble().pow(L.toDouble()).toInt()) { val sb = StringBuilder(root.toString()) for (k in L - 2 downTo 0) sb.append(sb[k]) val x = Integer.valueOf(sb.toString()) if (x >= n && x.isPrime()) return x } // Check for even-length palindromes val start = DECIMAL.toDouble().pow((L - 1).toDouble()).toInt() for (root in start until DECIMAL.toDouble().pow(L.toDouble()).toInt()) { val sb = StringBuilder(root.toString()) for (k in L - 1 downTo 0) sb.append(sb[k]) val x = Integer.valueOf(sb.toString()) if (x >= n && x.isPrime()) return x } } return 0 } companion object { private const val MAX = 5 } } /** * Approach 2: Brute Force with Mathematical Shortcut * Time Complexity: O(N). * Space Complexity: O(1). */ class PrimePalindromeBruteForce : PrimePalindrome { override operator fun invoke(n: Int): Int { var x = n while (true) { if (x == reverse(x) && x.isPrime()) { return x } x++ if (x in RANGE_START..RANGE_END) { x = MAX } } } private fun reverse(n: Int): Int { var x = n var ans = 0 while (x > 0) { ans = DECIMAL * ans + x % DECIMAL x /= DECIMAL } return ans } companion object { private const val RANGE_START = 10_000_001 private const val RANGE_END = 99_999_999 private const val MAX = 100_000_000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,986
kotlab
Apache License 2.0
src/main/kotlin/io/rbrincke/dice/core/Combination.kt
rbrincke
167,712,634
false
{"Kotlin": 13146}
package io.rbrincke.dice.core class Combination<T : Element<T>>(private val elements: List<T>) { init { check(elements.isNotEmpty()) { "Elements may not be empty." } } /** * Matches element 1 to 2, ..., N - 1 to N, N to 1. */ private val elementPairs = elements.mapIndexed { currentIdx, current -> val other = elements[(currentIdx + 1) % elements.size] current to other } /** * For the N elements in this set, compute the probability that die 1 beats die 2, * ..., N - 1 beats N, N beats 1. */ private val dominanceProbabilities = elementPairs.map { (current, other) -> current.beats(other) } val elementPairDominanceProbabilities = elementPairs.zip(dominanceProbabilities) /** * True if element 1 beats element 2, ..., N - 1 beats N, N beats 1, false otherwise. */ fun isNonTransitive() = dominanceProbabilities.all { v -> v > 0.5 } /** * Least of the probabilities that element 1 beats element 2, ..., N - 1 beats N, N beats 1. */ fun leastDominance() = dominanceProbabilities.minOrNull() ?: throw IllegalStateException("Empty set.") /** * Probability that element 1 beats element 2, ..., N - 1 beats N, N beats 1. */ fun dominance() = dominanceProbabilities.toList() /** * Pretty prints this combination. */ fun prettyPrint() = elementPairDominanceProbabilities.joinToString { (elements, probability) -> val (current, other) = elements "$current beats $other with probability $probability" } } interface Element<in E> { /** * Probability that this element beats the other element [E]. If draws are possible, * they are assumed to be resolved by a coin toss. */ fun beats(other: E): Double }
0
Kotlin
0
0
fc5aa0365d91ce360bf6e9c7589e3f5fc6bc8a82
1,811
nontransitive-dice
MIT License
src/main/kotlin/adventofcode/year2021/Day02Dive.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2021 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.year2021.Day02Dive.Companion.Direction.DOWN import adventofcode.year2021.Day02Dive.Companion.Direction.FORWARD import adventofcode.year2021.Day02Dive.Companion.Direction.UP class Day02Dive(customInput: PuzzleInput? = null) : Puzzle(customInput) { override val name = "Dive!" private val commands by lazy { input.lines().map(::Command) } override fun partOne() = commands.fold(Position()) { acc, command -> when (command.direction) { FORWARD -> acc.copy(horizontal = acc.horizontal + command.value) DOWN -> acc.copy(depth = acc.depth + command.value) UP -> acc.copy(depth = acc.depth - command.value) } }.multiply() override fun partTwo() = commands.fold(Position()) { acc, command -> when (command.direction) { FORWARD -> acc.copy(horizontal = acc.horizontal + command.value, depth = acc.depth + acc.aim * command.value) DOWN -> acc.copy(aim = acc.aim + command.value) UP -> acc.copy(aim = acc.aim - command.value) } }.multiply() companion object { private data class Position( val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0 ) { fun multiply() = horizontal * depth } private data class Command( val direction: Direction, val value: Int ) { constructor(input: String) : this(Direction(input.split(" ").first()), input.split(" ").last().toInt()) } private enum class Direction(val direction: String) { FORWARD("forward"), DOWN("down"), UP("up"); companion object { operator fun invoke(direction: String) = entries.associateBy(Direction::direction)[direction]!! } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
1,960
AdventOfCode
MIT License
src/Day02.kt
xiaofeiMophsic
575,326,884
false
null
// A 石头(1) B 布(2) C 剪刀(3) // X 石头 Y 布 Z 剪刀 // 0(L), 3(D), 6(W) val part1ScoreList = mapOf( "A X" to 4, "A Y" to 8, "A Z" to 3, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 7, "C Y" to 2, "C Z" to 6 ) val part2ScoreList = mapOf( "A X" to 3, "A Y" to 4, "A Z" to 8, "B X" to 1, "B Y" to 5, "B Z" to 9, "C X" to 2, "C Y" to 6, "C Z" to 7 ) fun main() { fun part1(input: List<String>): Int { return input.sumOf { part1ScoreList[it] ?: 0 } } fun part2(input: List<String>): Int { return input.sumOf { part2ScoreList[it] ?: 0 } } val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
13e5063928c0eb6416ce266e2083816ca78b8240
781
aoc-kotlin
Apache License 2.0
src/Day20.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
fun main() { fun day20(input: List<String>, decryptionKey: Long, repeat: Int): Long { val encryptedFile = input.map { it.toInt() * decryptionKey }.withIndex().toMutableList() repeat(repeat) { input.indices.forEach { initialIndex -> val currentIndex = encryptedFile.indexOfFirst { it.index == initialIndex } val indexedValue = encryptedFile.removeAt(currentIndex) encryptedFile.add( index = (currentIndex + indexedValue.value).mod(encryptedFile.size), element = indexedValue, ) } } val decryptedFile = encryptedFile.map { it.value } val indexOfZero = decryptedFile.indexOf(0) return decryptedFile[(indexOfZero + 1000).mod(decryptedFile.size)] + decryptedFile[(indexOfZero + 2000).mod(decryptedFile.size)] + decryptedFile[(indexOfZero + 3000).mod(decryptedFile.size)] } fun part1(input: List<String>): Long { return day20(input, decryptionKey = 1, repeat = 1) } fun part2(input: List<String>): Long { return day20(input, decryptionKey = 811589153, repeat = 10) } // test if implementation meets criteria from the description, like: val testInput = readLines("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readLines("Day20") with(part1(input)) { check(this == 23321L) println(this) } with(part2(input)) { check(this == 1428396909280) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
1,620
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/dp/LCS.kt
yx-z
106,589,674
false
null
package dp import util.* // Longest Common Subsequence fun main(args: Array<String>) { val a1 = intArrayOf(1, 5, 0, 12, 9) val a2 = intArrayOf(5, 12, 9, 1) // println(a1 lcs a2) // [5, 12, 9] -> 3 // how about three arrays? val A = oneArrayOf(1, 1, 1, 2, 2, 2, 2, 2) val B = oneArrayOf(2, 2, 2, 2, 1, 1, 1, 1) val C = oneArrayOf(1, 1, 1, 3, 3, 3, 3, 3) println(lcs3(A, B, C)) } infix fun IntArray.lcs(that: IntArray): Int { // dp[i, j]: length of lcs for this[0 until i] & that[0 until j] // dp[i, j] = 0, if (i == 0 || j == 0) // = if (this[i] == that[j]) { // max(1 + dp[i - 1, j - 1], dp[i - 1, j], dp[i, j - 1]) // } else { // max(dp[i - 1, j], dp[i, j - 1], dp[i - 1, j - 1]) // } // we want dp[size, that.size] val dp = Array(size + 1) { IntArray(that.size + 1) } for (i in 1..size) { for (j in 1..that.size) { dp[i, j] = if (this[i - 1] == that[j - 1]) { max(1 + dp[i - 1, j - 1], dp[i - 1, j], dp[i, j - 1]) } else { max(dp[i - 1, j], dp[i, j - 1], dp[i - 1, j - 1]) } } } return dp[size, that.size] } // A[1..n], B[1..n], C[1..n] fun lcs3(A: OneArray<Int>, B: OneArray<Int>, C: OneArray<Int>): Int { val n = A.size // == B.size == C.size val dp = Array(n + 1) { Array(n + 1) { Array(n + 1) { 0 } } } for (i in 1..n) { for (j in 1..n) { for (k in 1..n) { dp[i, j, k] = if (A[i] == B[j] && B[j] == C[k]) { 1 + dp[i - 1, j - 1, k - 1] } else { max(dp[i - 1, j, k], dp[i, j - 1, k], dp[i, j, k - 1]) } } } } return dp[n, n, n] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
1,582
AlgoKt
MIT License
src/Day08.kt
Kvest
573,621,595
false
{"Kotlin": 87988}
fun main() { val testInput = readInput("Day08_test").toMatrix() check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08").toMatrix() println(part1(input)) println(part2(input)) } private fun part1(input: Matrix): Int { val width = input[0].size val height = input.size var result = height * 2 + width * 2 - 4 val used = Array(height) { BooleanArray(width) { false } } val row = IntArray(width) { input[0][it] } val column = IntArray(height) { input[it][0] } fun updateResult(i: Int, j: Int) { if (!used[i][j]) { ++result used[i][j] = true } } fun checkItem(i: Int, j: Int) { if (input[i][j] > column[i]) { updateResult(i, j) column[i] = input[i][j] } if (input[i][j] > row[j]) { updateResult(i, j) row[j] = input[i][j] } } //top-to-bottom, left-to-right pass for (i in 1..(height - 2)) { for (j in 1..(width - 2)) { checkItem(i, j) } } for (i in 1..(height - 2)) { column[i] = input[i][width - 1] } for (j in 1..(width - 2)) { row[j] = input[height - 1][j] } //bottom-to-top, right-to-left pass for (i in (height - 2) downTo 1) { for (j in (width - 2) downTo 1) { checkItem(i, j) } } return result } private fun part2(input: Matrix): Int { var result = 0 val width = input[0].size val height = input.size for (i in 1..(height - 2)) { for (j in 1..(width - 2)) { val digit = input[i][j] var top = i - 1 while (top > 0 && digit > input[top][j]) { --top } var left = j - 1 while (left > 0 && digit > input[i][left]) { --left } var right = j + 1 while (right < width - 1 && digit > input[i][right]) { ++right } var bottom = i + 1 while (bottom < height - 1 && digit > input[bottom][j]) { ++bottom } val mul = (i - top) * (j - left) * (right - j) * (bottom - i) if (mul > result) { result = mul } } } return result } private fun List<String>.toMatrix(): Matrix { return Array(this.size) { i -> IntArray(this[i].length) { j -> this[i][j].digitToInt() } } }
0
Kotlin
0
0
6409e65c452edd9dd20145766d1e0ea6f07b569a
2,549
AOC2022
Apache License 2.0
src/day15/Day15.kt
daniilsjb
726,047,752
false
{"Kotlin": 66638, "Python": 1161}
package day15 import java.io.File fun main() { val data = parse("src/day15/Day15.txt") println("🎄 Day 15 🎄") println() println("[Part 1]") println("Answer: ${part1(data)}") println() println("[Part 2]") println("Answer: ${part2(data)}") } private fun parse(path: String): List<String> = File(path) .readText() .split(",") private fun String.hash(): Int = fold(0) { acc, it -> (acc + it.code) * 17 and 0xFF } private fun part1(data: List<String>): Int = data.sumOf(String::hash) private data class Lens( val label: String, val focalLength: Int, ) private fun part2(data: List<String>): Int { val boxes = Array(256) { mutableListOf<Lens>() } for (step in data) { val (label) = step.split('=', '-') val location = label.hash() if (step.contains('=')) { val focalLength = step.last().digitToInt() val index = boxes[location].indexOfFirst { it.label == label } if (index >= 0) { boxes[location][index] = Lens(label, focalLength) } else { boxes[location] += Lens(label, focalLength) } } else { boxes[location].removeIf { it.label == label } } } return boxes.withIndex().sumOf { (boxNumber, box) -> box.withIndex().sumOf { (lensNumber, lens) -> (boxNumber + 1) * (lensNumber + 1) * lens.focalLength } } }
0
Kotlin
0
0
46a837603e739b8646a1f2e7966543e552eb0e20
1,540
advent-of-code-2023
MIT License
kotlin/905.Length of Longest Fibonacci 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 <code>X_1, X_2, ..., X_n</code>&nbsp;is <em>fibonacci-like</em> if:</p> <ul> <li><code>n &gt;= 3</code></li> <li><code>X_i + X_{i+1} = X_{i+2}</code>&nbsp;for all&nbsp;<code>i + 2 &lt;= n</code></li> </ul> <p>Given a <b>strictly increasing</b>&nbsp;array&nbsp;<code>A</code> of positive integers forming a sequence, find the <strong>length</strong> of the longest fibonacci-like subsequence of <code>A</code>.&nbsp; If one does not exist, return 0.</p> <p>(<em>Recall that a subsequence is derived from another sequence <code>A</code> by&nbsp;deleting any number of&nbsp;elements (including none)&nbsp;from <code>A</code>, without changing the order of the remaining elements.&nbsp; For example, <code>[3, 5, 8]</code> is a subsequence of <code>[3, 4, 5, 6, 7, 8]</code>.</em>)</p> <p>&nbsp;</p> <ul> </ul> <p><strong>Example 1:</strong></p> <pre> <strong>Input: </strong>[1,2,3,4,5,6,7,8] <strong>Output: </strong>5 <strong>Explanation: </strong>The longest subsequence that is fibonacci-like: [1,2,3,5,8]. </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input: </strong>[1,3,7,11,12,14,18] <strong>Output: </strong>3 <strong>Explanation</strong>: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18]. </pre> <p>&nbsp;</p> <p><strong>Note:</strong></p> <ul> <li><code>3 &lt;= A.length &lt;= 1000</code></li> <li><code>1 &lt;= A[0] &lt; A[1] &lt; ... &lt; A[A.length - 1] &lt;= 10^9</code></li> <li><em>(The time limit has been reduced by 50% for submissions in Java, C, C++, and C#.)</em></li> </ul> <p>如果序列&nbsp;<code>X_1, X_2, ..., X_n</code>&nbsp;满足下列条件,就说它是&nbsp;<em>斐波那契式&nbsp;</em>的:</p> <ul> <li><code>n &gt;= 3</code></li> <li>对于所有&nbsp;<code>i + 2 &lt;= n</code>,都有&nbsp;<code>X_i + X_{i+1} = X_{i+2}</code></li> </ul> <p>给定一个<strong>严格递增</strong>的正整数数组形成序列,找到 <code>A</code> 中最长的斐波那契式的子序列的长度。如果一个不存在,返回&nbsp;&nbsp;0 。</p> <p><em>(回想一下,子序列是从原序列 <code>A</code>&nbsp;中派生出来的,它从 <code>A</code>&nbsp;中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如,&nbsp;<code>[3, 5, 8]</code>&nbsp;是&nbsp;<code>[3, 4, 5, 6, 7, 8]</code>&nbsp;的一个子序列)</em></p> <p>&nbsp;</p> <ul> </ul> <p><strong>示例 1:</strong></p> <pre><strong>输入: </strong>[1,2,3,4,5,6,7,8] <strong>输出: </strong>5 <strong>解释: </strong>最长的斐波那契式子序列为:[1,2,3,5,8] 。 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入: </strong>[1,3,7,11,12,14,18] <strong>输出: </strong>3 <strong>解释</strong>: 最长的斐波那契式子序列有: [1,11,12],[3,11,14] 以及 [7,11,18] 。 </pre> <p>&nbsp;</p> <p><strong>提示:</strong></p> <ul> <li><code>3 &lt;= A.length &lt;= 1000</code></li> <li><code>1 &lt;= A[0] &lt; A[1] &lt; ... &lt; A[A.length - 1] &lt;= 10^9</code></li> <li><em>(对于以 Java,C,C++,以及&nbsp;C# 的提交,时间限制被减少了 50%)</em></li> </ul> <p>如果序列&nbsp;<code>X_1, X_2, ..., X_n</code>&nbsp;满足下列条件,就说它是&nbsp;<em>斐波那契式&nbsp;</em>的:</p> <ul> <li><code>n &gt;= 3</code></li> <li>对于所有&nbsp;<code>i + 2 &lt;= n</code>,都有&nbsp;<code>X_i + X_{i+1} = X_{i+2}</code></li> </ul> <p>给定一个<strong>严格递增</strong>的正整数数组形成序列,找到 <code>A</code> 中最长的斐波那契式的子序列的长度。如果一个不存在,返回&nbsp;&nbsp;0 。</p> <p><em>(回想一下,子序列是从原序列 <code>A</code>&nbsp;中派生出来的,它从 <code>A</code>&nbsp;中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如,&nbsp;<code>[3, 5, 8]</code>&nbsp;是&nbsp;<code>[3, 4, 5, 6, 7, 8]</code>&nbsp;的一个子序列)</em></p> <p>&nbsp;</p> <ul> </ul> <p><strong>示例 1:</strong></p> <pre><strong>输入: </strong>[1,2,3,4,5,6,7,8] <strong>输出: </strong>5 <strong>解释: </strong>最长的斐波那契式子序列为:[1,2,3,5,8] 。 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入: </strong>[1,3,7,11,12,14,18] <strong>输出: </strong>3 <strong>解释</strong>: 最长的斐波那契式子序列有: [1,11,12],[3,11,14] 以及 [7,11,18] 。 </pre> <p>&nbsp;</p> <p><strong>提示:</strong></p> <ul> <li><code>3 &lt;= A.length &lt;= 1000</code></li> <li><code>1 &lt;= A[0] &lt; A[1] &lt; ... &lt; A[A.length - 1] &lt;= 10^9</code></li> <li><em>(对于以 Java,C,C++,以及&nbsp;C# 的提交,时间限制被减少了 50%)</em></li> </ul> **/ class Solution { fun lenLongestFibSubseq(A: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
4,842
leetcode
MIT License
2015/src/main/kotlin/day8_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day8Func.run() } object Day8Func : Solution<List<String>>() { override val name = "day8" override val parser = Parser.lines private fun unescape(input: String): String { val slash = input.indexOf('\\') if (slash == -1) return input val second = input[slash + 1] if (second == '\\') { return input.substring(0, slash) + "\\" + unescape(input.substring(slash + 2)) } if (second == '"') { return input.substring(0, slash) + "\"" + unescape(input.substring(slash + 2)) } if (second == 'x') { val hex = input.substring(slash + 2, slash + 4) return input.substring(0, slash) + hex.toInt(16).toChar() + unescape(input.substring(slash + 4)) } throw IllegalArgumentException("Illegal escape sequence \\${second} at $slash") } private fun escape(input: String): String { val slash = input.indexOf('\\') val quote = input.indexOf('"') val escapeIndex = minOf(slash, quote).takeIf { it != -1 } ?: maxOf(slash, quote) if (escapeIndex == -1) return input return input.substring(0, escapeIndex) + "\\" + input[escapeIndex] + escape(input.substring(escapeIndex + 1)) } override fun part1(input: List<String>): Int { return input.sumOf { it.length } - input.sumOf { unescape(it.removeSurrounding("\"")).length } } override fun part2(input: List<String>): Int { return input.sumOf { "\"${escape(it)}\"".length } - input.sumOf { it.length } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,507
aoc_kotlin
MIT License
src/main/kotlin/days/Day17.kt
nuudles
316,314,995
false
null
package days class Day17 : Day(17) { private fun findNeighbors( target: Triple<Int, Int, Int>, candidates: Set<Triple<Int, Int, Int>> ): Set<Triple<Int, Int, Int>> { val neighbors = mutableSetOf<Triple<Int, Int, Int>>() for (candidate in candidates.minus(target)) { if ( candidate.first in (target.first - 1)..(target.first + 1) && candidate.second in (target.second - 1)..(target.second + 1) && candidate.third in (target.third - 1)..(target.third + 1) ) { neighbors.add(candidate) } } return neighbors } override fun partOne(): Any { var activeCubes = mutableSetOf<Triple<Int, Int, Int>>() inputList .forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') { activeCubes.add(Triple(x, y, 0)) } } } (0 until 6).forEach { _ -> val nextCubes = mutableSetOf<Triple<Int, Int, Int>>() for (cube in activeCubes) { val neighbors = findNeighbors(cube, activeCubes) if (neighbors.count() == 2 || neighbors.count() == 3) { nextCubes.add(cube) } } for (x in IntRange( (activeCubes .map { it.first } .minOrNull() ?: 0) - 1, (activeCubes .map { it.first } .maxOrNull() ?: 0) + 1 )) { for (y in IntRange( (activeCubes .map { it.second } .minOrNull() ?: 0) - 1, (activeCubes .map { it.second } .maxOrNull() ?: 0) + 1 )) { for (z in IntRange( (activeCubes .map { it.third } .minOrNull() ?: 0) - 1, (activeCubes .map { it.third } .maxOrNull() ?: 0) + 1 )) { Triple(x, y, z).let { cube -> if (activeCubes.contains(cube)) { return@let } if (findNeighbors(cube, activeCubes).count() == 3) { nextCubes.add(cube) } } } } } activeCubes = nextCubes } return activeCubes.count() } private data class Point4D( val x: Int, val y: Int, val z: Int, val w: Int ) private fun findNeighbors( target: Point4D, candidates: Set<Point4D> ): Set<Point4D> { val neighbors = mutableSetOf<Point4D>() for (candidate in candidates.minus(target)) { if ( candidate.x in (target.x - 1)..(target.x + 1) && candidate.y in (target.y - 1)..(target.y + 1) && candidate.z in (target.z - 1)..(target.z + 1) && candidate.w in (target.w - 1)..(target.w + 1) ) { neighbors.add(candidate) } } return neighbors } override fun partTwo(): Any { var activeCubes = mutableSetOf<Point4D>() inputList .forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') { activeCubes.add(Point4D(x, y, 0, 0)) } } } (0 until 6).forEach { _ -> val nextCubes = mutableSetOf<Point4D>() for (cube in activeCubes) { val neighbors = findNeighbors(cube, activeCubes) if (neighbors.count() == 2 || neighbors.count() == 3) { nextCubes.add(cube) } } for (x in IntRange( (activeCubes .map { it.x } .minOrNull() ?: 0) - 1, (activeCubes .map { it.x } .maxOrNull() ?: 0) + 1 )) { for (y in IntRange( (activeCubes .map { it.y } .minOrNull() ?: 0) - 1, (activeCubes .map { it.y } .maxOrNull() ?: 0) + 1 )) { for (z in IntRange( (activeCubes .map { it.z } .minOrNull() ?: 0) - 1, (activeCubes .map { it.z } .maxOrNull() ?: 0) + 1 )) { for (w in IntRange( (activeCubes .map { it.w } .minOrNull() ?: 0) - 1, (activeCubes .map { it.w } .maxOrNull() ?: 0) + 1 )) { Point4D(x, y, z, w).let { cube -> if (activeCubes.contains(cube)) { return@let } if (findNeighbors(cube, activeCubes).count() == 3) { nextCubes.add(cube) } } } } } } activeCubes = nextCubes } return activeCubes.count() } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
6,014
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day19.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
import kotlin.math.* import kotlin.time.* data class P3D(val x: Int, val y: Int, val z: Int) @ExperimentalStdlibApi @ExperimentalTime fun main() { val start = TimeSource.Monotonic.markNow() val input = readInputFile("day19") val a = ArrayList<HashSet<P3D>>() for (s in input) { if (s == "--- scanner ${a.size} ---") { a.add(HashSet()) continue } if (s.isEmpty()) continue a.last().add(s.split(",").map { it.toInt() }.let { (x, y, z) -> P3D(x, y, z) }) } val n = a.size fun check(ui: Int, vi: Int): T3D? { val u = a[ui] for (dir in 0 until 24) { val v = a[vi].map { it.rotate(dir) } val sh = sequence { for (pu in u) for (pv in v) yield(diff(pu, pv)) } .groupingBy { it } .eachCount() .filterValues { it >= 12 } .keys.firstOrNull() ?: continue return T3D(dir, sh) } return null } val t = arrayOfNulls<List<T3D>>(n) val b = a[0].toMutableSet() val s = arrayOfNulls<P3D>(n) t[0] = emptyList() s[0] = P3D(0, 0, 0) val found = ArrayDeque<Int>().apply { add(0) } val rem = (1 until a.size).toHashSet() while (rem.isNotEmpty()) { val ui = found.removeFirst() for (vi in rem.toList()) { val o = check(ui, vi) ?: continue val f = listOf(o) + t[ui]!! t[vi] = f s[vi] = P3D(0, 0, 0).apply(f) b += a[vi].map { it.apply(f) } found += vi rem -= vi } } println("Done in ${start.elapsedNow()}") println("part1 = ${b.size}") val part2 = buildList { for (s1 in s) for (s2 in s) add(diff(s1!!, s2!!).dist()) }.maxOrNull()!! println("part2 = $part2") } class T3D(val dir: Int, val sh: P3D) fun P3D.apply(t: T3D): P3D = rotate(t.dir).shift(t.sh) fun P3D.apply(t: List<T3D>): P3D = t.fold(this, P3D::apply) fun diff(a: P3D, b: P3D): P3D = P3D(a.x - b.x, a.y - b.y, a.z - b.z) fun P3D.shift(b: P3D): P3D = P3D(this.x + b.x, this.y + b.y, this.z + b.z) fun P3D.dist() = x.absoluteValue + y.absoluteValue + z.absoluteValue fun P3D.get(i: Int) = when(i) { 0 -> x 1 -> y 2 -> z else -> error("$i") } fun P3D.rotate(d: Int): P3D { val c0 = d % 3 val c0s = 1 - ((d / 3) % 2) * 2 val c1 = (c0 + 1 + (d / 6) % 2) % 3 val c1s = 1 - (d / 12) * 2 val c2 = 3 - c0 - c1 val c2s = c0s * c1s * (if (c1 == (c0 + 1) % 3) 1 else -1) return P3D(get(c0) * c0s, get(c1) * c1s, get(c2) * c2s) }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
2,607
AOC2021
Apache License 2.0
src/Day01.kt
lampenlampen
573,064,227
false
{"Kotlin": 1907}
import kotlin.time.ExperimentalTime @OptIn(ExperimentalTime::class) fun main() { fun parseInput(input: String): List<Int> = input .split("\n\n") .map { elv -> elv.lines().sumOf { it.toInt() } } fun topNElves(elves: List<Int>, n: Int): Int { fun findTopN(n: Int, element: List<Int>): List<Int> { if (element.size == n) return element val small = mutableListOf<Int>() val equal = mutableListOf<Int>() val big = mutableListOf<Int>() val x = element.random() element.forEach { if (it < x) small.add(it) if (it == x) equal.add(it) if (it > x) big.add(it) } if (big.size >= n) return findTopN(n, big) if (equal.size + big.size >= n) return (equal + big).takeLast(n) return findTopN(n - equal.size - big.size, small) + equal + big } return findTopN(n, elves).sum() } fun part1(input: String): Int = topNElves(parseInput(input), 1) fun part2(input: String): Int = topNElves(parseInput(input), 3) // test if implementation meets criteria from the description, like: // val testInput = readInputByLines("Day01_test") // check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f63812280aaacb9e4af7995d2ee7b0b6d1ffecac
1,188
AdventOfCode2022
Apache License 2.0
src/Day10.kt
SebastianHelzer
573,026,636
false
{"Kotlin": 27111}
fun main() { fun processOps(ops: List<Int?>, cycle: (Int, Int) -> Unit) { var cycleNumber = 1 var x = 1 ops.forEach { if(it == null) { cycle(cycleNumber++, x) } else { cycle(cycleNumber++, x) cycle(cycleNumber++, x) x += it } } } fun part1(input: List<String>): Int { val ops = input.map { ("$it noop").split(" ")[1].toIntOrNull()} var accumulatedSignalStrength = 0 fun checkAndAccumulate(cycleNumber: Int, x: Int) { if ((cycleNumber + 20) % 40 == 0) { accumulatedSignalStrength += cycleNumber * x } } processOps(ops, ::checkAndAccumulate) return accumulatedSignalStrength } fun part2(input: List<String>) { val ops = input.map { it.split(" ").getOrNull(1)?.toIntOrNull()} fun printPixel(cycleNumber: Int, x: Int) { val pixelNumber = ((cycleNumber - 1) % 40) print(if(pixelNumber in (x-1)..(x+1)) '#' else '.') if (pixelNumber == 39) { println() } } processOps(ops, ::printPixel) } val testInput = readInput("Day10_test") checkEquals(13140, part1(testInput)) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
e48757626eb2fb5286fa1c59960acd4582432700
1,393
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dynamicprogramming/LongestPalindromicSubstring.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package dynamicprogramming private var memo: Array<Array<Boolean?>>? = null fun isPalindrome(s: String, i: Int, j: Int): Boolean { if (memo!![i][j] != null) { return memo!![i][j]!! } if (i == j) { memo!![i][j] = true return true } if (i == j - 1) { memo!![i][j] = s[i] == s[j] return s[i] == s[j] } val res = s[i] == s[j] && isPalindrome(s, i + 1, j - 1) memo!![i][j] = res return res } // O(N^2) fun longestPalindrome(s: String): String { memo = Array(s.length) {Array<Boolean?>(s.length) {null} } var ti = s.lastIndex var tj = 0 for (i in s.indices) { for (j in i..s.lastIndex) { if (isPalindrome(s, i, j) && j - i > tj - ti) { ti = i tj = j } } } return s.substring(ti, tj + 1) } fun main() { println(longestPalindrome("ac")) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
915
LeetcodeGoogleInterview
Apache License 2.0
src/Day01.kt
mythicaleinhorn
572,689,424
false
{"Kotlin": 11494}
fun main() { fun part1(input: List<String>): Int { var highest = 0 var temp = 0 for (line in input) { if (line == "") { highest = highest.coerceAtLeast(temp) temp = 0 continue } temp += line.toInt() } return highest } fun part2(input: List<String>): Int { val elves: MutableList<Int> = mutableListOf() var temp = 0 for (i in input.indices) { if (input[i] != "") { temp += input[i].toInt() } if (input[i] == "" || i == input.indices.last) { elves.add(temp) temp = 0 continue } } elves.sortDescending() return elves[0] + elves[1] + elves[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
959dc9f82c14f59d8e3f182043c59aa35e059381
1,131
advent-of-code-2022
Apache License 2.0
src/Day10.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { fun part1(input: List<String>): Int { var x = 1 var cycle = 1 var total = 0 for(line in input) { val command = line.trim().split(" ") if(command.first() == "addx") { for(i in 1..2) { if (i == 2) x += command.last().toInt() cycle++ if(cycle in listOf(20, 60, 100, 140,180, 220)) total += cycle * x } } else { cycle++ if(cycle in listOf(20, 60, 100, 140,180, 220)) total += cycle * x } } return total } fun printSprite(cycle: Int, x: Int) { val position = cycle.mod(40) - 1 if(position.mod(40) == 0) println() if(position in x-1..x+1) print("# ") else print(". ") } fun part2(input: List<String>){ var x = 1 var cycle = 1 for(line in input) { val command = line.trim().split(" ") if(command.first() == "addx") { for(i in 1..2) { printSprite(cycle, x) if (i == 2) x += command.last().toInt() cycle++ } } else { printSprite(cycle, x) cycle++ } } } val testInput = readInput("Day10_test") val input = readInput("Day10") println(part1(testInput)) check(part1(testInput) == 13140) println(part1(input)) part2(testInput) println() part2(input) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
1,567
AoC-2022
Apache License 2.0