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/Day11.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { data class Monkey( var items: MutableList<Long>, val operation: String, val opValue: String, val div: Long, val ifTrue: Int, val ifFalse: Int, var itemsRevised: Long ) fun buildMonkeys(input: List<String>): List<Monkey> = buildList { for (info in input) { val monkeyInfo = info.split("\n").drop(1) val items = "(\\d+),?".toRegex().findAll(monkeyInfo[0]).map { it.groupValues[1].toLong() }.toList() val operation = "([*+]) (\\d+|old)".toRegex().find(monkeyInfo[1])!!.groupValues.toList() val divisible = "(\\d+),?".toRegex().findAll(monkeyInfo[2]).map { it.value }.first().toLong() val trueToMonkey = "(\\d+)".toRegex().findAll(monkeyInfo[3]).map { it.value }.first().toInt() val falseToMonkey = "(\\d+)".toRegex().findAll(monkeyInfo[4]).map { it.value }.first().toInt() add( Monkey( mutableListOf(*items.toTypedArray()), operation[1], operation[2], divisible, trueToMonkey, falseToMonkey, 0 ) ) } } fun countItems(monkeys: List<Monkey>, iterations: Int, reduce: Int): List<Long> { val base = monkeys.map { it.div }.reduce { acc, i -> acc * i } repeat(iterations) { for (monkey in monkeys) { for (item in monkey.items) { monkey.itemsRevised++ val value = when (monkey.opValue) { "old" -> item else -> monkey.opValue.toLong() } val total = when (monkey.operation) { "*" -> (item * value) / reduce "+" -> (item + value) / reduce else -> item } if (total % monkey.div == 0L) { monkeys[monkey.ifTrue].items.add(total % base) } else { monkeys[monkey.ifFalse].items.add(total % base) } } monkey.items = mutableListOf() } } return monkeys.map { it.itemsRevised } } fun part1(monkeys: List<Monkey>): Long { val counter = countItems(monkeys, 20, 3) return counter.sortedDescending().take(2).reduce{acc, elem -> acc * elem } } fun part2(monkeys: List<Monkey>): Long { val counter = countItems(monkeys, 10000, 1) return counter.sortedDescending().take(2).reduce{acc, elem -> acc * elem } } val testInput = readInputByGroups("Day11_test") val input = readInputByGroups("Day11") check(part1(buildMonkeys(testInput)) == 10605L) println(part1(buildMonkeys(input))) check(part2(buildMonkeys(testInput)) == 2713310158L) println(part2(buildMonkeys(input))) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
3,036
AoC-2022
Apache License 2.0
src/main/kotlin/day3.kt
sviams
726,160,356
false
{"Kotlin": 9233}
import kotlin.math.max import kotlin.math.min object day3 { data class Number(val chars: String, val startIndex: Int, val row: Int) { fun toInt() = chars.toInt() val range by lazy { IntRange(startIndex, startIndex+chars.length-1) } fun isAdjacentToSymbol(world: List<Line>): Boolean = (-1 .. 1).fold(emptyList<Symbol>()) { acc, offset -> acc + getSymbolsInRange(world, row+offset, range) }.any() } data class Symbol(val char: Char, val col: Int, val row: Int) { fun isGearSymbol() = char == '*' val range by lazy { IntRange(col-1, col+1) } fun adjacentNumbers(world: List<Line>): List<Number> = (-1 .. 1).fold(emptyList()) { acc, offset -> acc + getNumbersInRange(world, row+offset, range) } fun gearRatio(world: List<Line>): Int { val nums = adjacentNumbers(world).map { it.toInt() } return nums.first() * nums.last() } } fun getNumbersInRange(world: List<Line>, row: Int, range: IntRange) = if (row < 0 || row >= world.size) emptyList() else world[row].numbers.filter { range.intersect(it.range).any() } fun getSymbolsInRange(world: List<Line>, row: Int, range: IntRange) = if (row < 0 || row >= world.size) emptyList() else world[row].symbols.filter { range.intersect(it.range).any() } data class Line(val numbers: List<Number>, val symbols: List<Symbol>) tailrec fun numbersFromLine(line: String, row: Int, res: List<Number> = emptyList(), currentNum: String = "", currentStart: Int = -1, index: Int = 0): List<Number> { if (index == line.length) return if (!currentNum.isEmpty()) res + Number(currentNum, currentStart, row) else res val atIndex = line[index] val newCurrentNum = if (atIndex.isDigit()) currentNum + atIndex else "" val newStart = if (currentNum == "" && atIndex.isDigit()) index else currentStart val newRes = if (!atIndex.isDigit() && !currentNum.isEmpty()) res + Number(currentNum, currentStart, row) else res return numbersFromLine(line, row, newRes, newCurrentNum, newStart, index+1) } fun parseInput(input: List<String>) = input.foldIndexed(emptyList<Line>()) { row, linesRes, line -> val nums = numbersFromLine(line, row) val symbols = line.foldIndexed(emptyList<Symbol>()) { col, acc, c -> if (!c.isDigit() && c != '.') acc + Symbol(c, col, row) else acc } linesRes + Line(nums, symbols) } fun pt1(input: List<String>): Int { val world = parseInput(input) return world.fold(0) { acc, line -> val hasAdjacent = line.numbers.filter { it.isAdjacentToSymbol(world) } acc + hasAdjacent.sumOf { it.toInt() } } } fun pt2(input: List<String>): Int { val world = parseInput(input) return world.fold(0) { acc, line -> val actualGears = line.symbols.filter {it.isGearSymbol() && it.adjacentNumbers(world).size == 2 } acc + actualGears.sumOf { it.gearRatio(world) } } } }
0
Kotlin
0
0
4914a54b21e8aac77ce7bbea3abc88ac04037d50
3,055
aoc23
Apache License 2.0
src/year2023/day03/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day03 import arrow.core.nonEmptyListOf import utils.Point import utils.ProblemPart import utils.neighbors import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 3, transform = ::parse) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(4361), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(467835), algorithm = ::part2, ), ) } private fun parse(input: List<String>): Input { return input.asSequence() .map(parsingRegex::findAll) .flatMapIndexed { row, elements -> elements.map { match -> match.value.toLongOrNull() ?.let { Number(row, match.range, it) } ?: Symbol(match.value.first(), Point(row, match.range.first)) } } .partition { it is Number } .let { (numbers, symbols) -> Input( numbers = numbers as List<Number>, symbols = symbols as List<Symbol>, ) } } private val parsingRegex = "(\\d+|[^\\d.])".toRegex() private fun part1(input: Input): Long { return input.symbols.asSequence() .flatMap { symbol -> symbol.position.adjacentNumbers(input.numbers) } .distinct() .sumOf { it.value } } private fun Point.adjacentNumbers(numbers: List<Number>): Sequence<Number> { return neighbors(includeDiagonal = true) .mapNotNull { coordinates -> numbers.find { it.row == coordinates.x && coordinates.y in it.columns } } .distinct() } private fun part2(input: Input): Long { return input.symbols.asSequence() .filter { it.value == '*' } .map { symbol -> symbol.position .adjacentNumbers(input.numbers) .map { it.value } .toList() } .filter { it.size == 2 } .map { it.reduce(Long::times) } .sum() } private data class Input( val numbers: List<Number>, val symbols: List<Symbol>, ) private data class Number( val row: Int, val columns: IntRange, val value: Long, ) private data class Symbol( val value: Char, val position: Point, )
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,441
Advent-of-Code
Apache License 2.0
src/year_2021/day_09/Day09.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2021.day_09 import readInput import util.neighbors import util.product object Day09 { /** * @return */ fun solutionOne(text: List<String>): Int { val heightmap = parseText(text) val lowPoints = heightmap.flatMapIndexed { rowIndex, row -> row.filterIndexed { colIndex, _ -> isLowPoint(rowIndex, colIndex, heightmap) } } return lowPoints.sumOf { it + 1 } } /** * @return */ fun solutionTwo(text: List<String>): Int { val positions = text.indices.product(text[0].indices) val depths = positions.associateWith { (row, col) -> text[row][col] }.withDefault { '@' } val positionsWithBasinLabels = mutableMapOf<Pair<Int, Int>, Int>() var label = 0 positions.forEach { position -> searchBasin(position, depths, positionsWithBasinLabels, label++) } val basins = positionsWithBasinLabels.entries.groupBy({ it.value }) { it.key }.values return basins .map { it.size } .sortedBy { it } .takeLast(3) .reduce { a, b -> a * b } } private fun parseText(text: List<String>): List<List<Int>> { return text.map { line -> line.map { height -> Integer.parseInt("$height") } } } private fun isLowPoint(row: Int, column: Int, heightmap: List<List<Int>>): Boolean { val height = heightmap[row][column] var top = Integer.MAX_VALUE var bottom = Integer.MAX_VALUE var left = Integer.MAX_VALUE var right = Integer.MAX_VALUE if (row > 0) { top = heightmap[row - 1][column] } if (row < heightmap.size - 1) { bottom = heightmap[row + 1][column] } if (column > 0) { left = heightmap[row][column - 1] } if (column < heightmap[row].size - 1) { right = heightmap[row][column + 1] } return height < top && height < bottom && height < left && height < right } private fun searchBasin( position: Pair<Int, Int>, depths: Map<Pair<Int, Int>, Char>, positionsWithBasinLabels: MutableMap<Pair<Int, Int>, Int>, label: Int ) { if (position !in positionsWithBasinLabels && depths.getValue(position) < '9') { positionsWithBasinLabels[position] = label position.neighbors().forEach { searchBasin(it, depths, positionsWithBasinLabels, label) } } } } fun main() { val inputText = readInput("year_2021/day_09/Day10.txt") val solutionOne = Day09.solutionOne(inputText) println("Solution 1: $solutionOne") val solutionTwo = Day09.solutionTwo(inputText) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,826
advent_of_code
Apache License 2.0
src/main/kotlin/aoc2023/Day02.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2023 import utils.InputUtils enum class Colours { red, blue, green } typealias BallCount = Map<Colours, Int> fun BallCount.fitsIn(limits: BallCount) = limits.all { (col, limit) -> (this[col] ?: 0) <= limit } data class Game(val id: Int, val contents: List<BallCount>) { fun fitsIn(limits: BallCount): Boolean = contents.all { it.fitsIn(limits) } fun minimums(): BallCount { return Colours.entries.associateWith { colour -> contents.maxOf { it[colour] ?: 0 } } } } fun String.parseSample(): BallCount { return this.split(", ").parsedBy("^(\\d+) (\\w+)".toRegex()) { val (count, col) = it.destructured Colours.valueOf(col) to count.toInt() }.toMap() } fun main() { val testInput = """Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green""".split("\n") val parseSample = "((\\d+) (red|green|blue)(, )?)+".toRegex() val parseSensor = "Game ([\\d]+): (($parseSample(; )?)+)".toRegex() fun List<String>.toGames() = parsedBy(parseSensor) { match -> val (id, sample) = match.destructured Game(id.toInt(), sample.split("; ").map { it.parseSample() }) } fun part1(input: List<String>): Int { return input.toGames() .filter { it.fitsIn(mapOf( Colours.red to 12, Colours.green to 13, Colours.blue to 14 )) } .sumOf { it.id } } fun part2(input: List<String>): Int { return input.toGames() .map { it.minimums() } .map { it.values.product() } .sum() } // test if implementation meets criteria from the description, like: val testValue = part1(testInput) println(testValue) check(testValue == 8) println(part2(testInput)) val puzzleInput = InputUtils.downloadAndGetLines(2023, 2) val input = puzzleInput.toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
2,204
aoc-2022-kotlin
Apache License 2.0
src/y2023/Day08.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.product import util.readInput import util.timingStatistics import y2015.Day20 import y2022.Day15.toPair object Day08 { private fun parse(input: List<String>): Pair<List<(Pair<String, String>) -> String>, Map<String, Pair<String, String>>> { val leftRight: List<(Pair<String, String>) -> String> = input.first().map { if (it == 'L') { { pair: Pair<String, String> -> pair.first } } else { { pair: Pair<String, String> -> pair.second } } } val map = input.drop(2).map { line -> val (left, right) = line.split(" = ") left to right.replace("(", "").replace(")", "").split(", ").toPair() }.toMap() return leftRight to map } fun part1(input: List<String>): Int { val (moves, map) = parse(input) var steps = 0 var current = "AAA" while (current != "ZZZ") { current = moves[steps % moves.size](map[current]!!) steps++ } return steps } fun part2x(input: List<String>): Long { val (moves, map) = parse(input) val starts = map.keys.filter { it.endsWith('A') } var steps = 0L var currents = starts while (currents.any { !it.endsWith('Z') }) { currents = currents.map { moves[(steps % moves.size).toInt()](map[it]!!) } steps++ } return steps } fun part2(input: List<String>): Long { val (moves, map) = parse(input) val starts = map.keys.filter { it.endsWith('A') } val cycles = starts.map { getCycle(moves, map, it) } val cycleLengths = cycles.map { it.last().stepsSinceLast } val factors = cycleLengths.map { Day20.factors(it.toInt()) } val uncommonFactors = factors.map { it[2] } val common = factors.first().last() val lcm = uncommonFactors.map { it.toLong() }.product() * common return lcm } fun getCycle(moves: List<(Pair<String, String>) -> String>, map: Map<String, Pair<String, String>>, start: String): MutableList<CycleStep> { var steps = 0L var current = start val cycle = mutableListOf<CycleStep>() while (true) { current = moves[(steps % moves.size).toInt()](map[current]!!) if (current.endsWith('Z')) { cycle.add( CycleStep( steps + 1, steps + 1 - (cycle.lastOrNull()?.totalSteps ?: 0), (steps + 1) % moves.size, current ) ) } if (cycle.distinctBy { it.instructionPosition to it.position }.size < cycle.size) { break } steps++ } return cycle } data class CycleStep( val totalSteps: Long, val stepsSinceLast: Long, val instructionPosition: Long, val position: String ) } fun main() { val testInput = """ RL AAA = (BBB, CCC) BBB = (DDD, EEE) CCC = (ZZZ, GGG) DDD = (DDD, DDD) EEE = (EEE, EEE) GGG = (GGG, GGG) ZZZ = (ZZZ, ZZZ) """.trimIndent().split("\n") val testInput2 = """ LR 11A = (11B, XXX) 11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX) """.trimIndent().split("\n") println("------Tests------") println(Day08.part1(testInput)) //println(Day08.part2(testInput2)) println("------Real------") val input = readInput(2023, 8) println("Part 1 result: ${Day08.part1(input)}") println("Part 2 result: ${Day08.part2(input)}") timingStatistics { Day08.part1(input) } timingStatistics { Day08.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
3,970
advent-of-code
Apache License 2.0
src/main/day19/Part1.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day19 import day19.Resource.* import groupUntil import readInput import java.util.* typealias Materials = Map<Resource, Int> fun main() { val blueprints = parseTestInput() val robots = Robots(mapOf(Robot(ORE) to 1, Robot(CLAY) to 1)) val materials = mapOf(ORE to 2, CLAY to 1) val qualityLevel = solve(blueprints.first(), 24) // .sumOf { solve(it, 24) } println("Day 19 part 1. Quality level: $qualityLevel ") } fun solve(blueprint: Blueprint, timelimit: Int): Int { println("New blueprint: $blueprint") val queue = PriorityQueue<HarvestState> { a, b -> a.elapsedTime.compareTo(b.elapsedTime) } // val queue = LinkedList<HarvestState>() val startingState = HarvestState(Robots(mapOf(Robot(ORE) to 1)), startingMaterials(), 0) queue.add(startingState) var max = 0; val seen = mutableSetOf<HarvestState>() var iterations = 0 while (queue.isNotEmpty()) { val current = queue.poll()!! seen.add(current) // println(current) val possibleBuilds = blueprint.possibleBuilds(current.materials) val harvestedMaterials = current.robots.work() possibleBuilds .map { (robot, materialsLeft) -> HarvestState(current.robots.add(robot), materialsLeft + harvestedMaterials, current.elapsedTime + 1) } .forEach { queue.add(it) } queue.add(HarvestState(current.robots, current.materials + harvestedMaterials, current.elapsedTime + 1)) val possiblemax = queue .filter { it.elapsedTime == timelimit } .maxOfOrNull { it.geodes() } ?: 0 max = maxOf(possiblemax, max) queue.removeIf { it.elapsedTime == timelimit } queue.removeIf { seen.contains(it) } } return max * blueprint.id } data class HarvestState(val robots: Robots, val materials: Materials, val elapsedTime: Int) { fun score(): Int { return robots.instances .map { (robot, quantity) -> when(robot.resource) { ORE -> 1 * quantity CLAY -> 10 * quantity OBSIDIAN -> 100 * quantity GEODE -> 100000 * quantity } } .sum() / (elapsedTime + 1) } fun geodes(): Int { return materials.getOrDefault(GEODE, 0) } } data class Blueprint(val id: Int, private val constructions: List<Construction>) { fun possibleBuilds(availableMaterials: Materials): List<Pair<Robot, Materials>> { return constructions .filter { it.buildable(availableMaterials) } .map { it.build(availableMaterials) } } companion object { fun parse(input: List<String>): Blueprint { val blueprintId = input.first().substringAfter("Blueprint ").substringBefore(":").toInt() val constructions = input .drop(1) .map { Construction.parse(it) } return Blueprint(blueprintId, constructions) } } } data class Construction(val resource: Resource, val requiredMaterials: Materials) { fun buildable(availableMaterials: Materials): Boolean { return requiredMaterials.all { (resource, requiredQuantity) -> availableMaterials.getOrDefault( resource, 0 ) >= requiredQuantity } } fun build(availableMaterials: Materials): Pair<Robot, Materials> { return Robot(resource) to availableMaterials - requiredMaterials } companion object { fun parse(input: String): Construction { val resource = input.substringAfter("Each ").substringBefore(" robot").let { valueOf(it.uppercase()) } if (input.contains("and")) { val firstMaterial = input.substringAfter("costs ").substringBefore(" and") .split(" ") .let { (quantity, resourceName) -> valueOf(resourceName.uppercase()) to quantity.toInt() } val secondMaterial = input.substringAfter("and ").substringBefore(".") .split(" ") .let { (quantity, resourceName) -> valueOf(resourceName.uppercase()) to quantity.toInt() } return Construction(resource, mapOf(firstMaterial, secondMaterial)) } else { val firstMaterial = input.substringAfter("costs ").substringBefore(".") .split(" ") .let { (quantity, resourceName) -> valueOf(resourceName.uppercase()) to quantity.toInt() } return Construction(resource, mapOf(firstMaterial)) } } } } data class Robots(val instances: Map<Robot, Int>) { fun work(): Materials { return instances .map { (robot, quantity) -> robot.resource to quantity } .toMap() } fun add(robot: Robot): Robots { return if(!instances.containsKey(robot)) { Robots(instances + (robot to 1)) } else { instances .map { (key, quantity) -> if (key == robot) { key to quantity + 1 } else { key to quantity } } .toMap().let { robotMap -> Robots(robotMap) } } } } data class Robot(val resource: Resource) { } enum class Resource { ORE, CLAY, OBSIDIAN, GEODE; } operator fun Materials.minus(other: Materials): Materials { return this .map { (resource, quantity) -> resource to (quantity - other.getOrDefault(resource, 0)) } .toMap() } operator fun Materials.plus(other: Materials): Materials { return this .map { (resource, quantity) -> resource to (quantity + other.getOrDefault(resource, 0)) } .toMap() } fun parseTestInput(): List<Blueprint> { return readInput("day19/testinput.txt") .groupUntil { line -> line.isBlank() } .map { Blueprint.parse(it.filter { line -> !line.isBlank() }) } } fun startingMaterials(): Materials { return mapOf(ORE to 0, CLAY to 0, OBSIDIAN to 0, GEODE to 0) }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
6,174
aoc2022
Apache License 2.0
2021/src/day20/Day20.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day20 import readInput typealias Table = Array<CharArray> fun Table.print() { for (line in this) { println(line) } } fun List<String>.toTable() : Table { val ret = Array(size) { CharArray(0) } for (idx in indices) ret[idx] = this[idx].toCharArray() return ret } fun Table.getValue(y: Int, x: Int, default: Char) : Int { if (x < 0 || y < 0 || y >= size || x >= this[y].size) return if (default == '#') 1 else 0 return if (this[y][x] == '#') 1 else 0 } // return a binary number of the 9 squares values around Y and X fun Table.getSquareValue(y: Int, x: Int, default: Char) : Int { var number = 0 for (yOffset in -1..1) { for (xOffset in -1..1) { number = number.shl(1) or getValue(y + yOffset, x + xOffset, default) } } return number } fun enhanceImage(table: Table, ref: String, numberOfSteps: Int = 1) : Table { var ret = table for (i in 1..numberOfSteps) { val nextIteration = Array(ret.size + 2) { CharArray(ret[0].size + 2) } // In case we're OOB, our default is either '.' (initial) or the first char in the reference // meaning all the chars were previously surrounded by '.' and got 0 as a total of 9 cells around val default = if (i % 2 == 0) { ref.first() } else { '.' } for (y in nextIteration.indices) { for (x in nextIteration[y].indices) { val number = ret.getSquareValue(y - 1, x - 1, default) nextIteration[y][x] = ref[number] } } ret = nextIteration } return ret } fun part1(lines: List<String>): Int { val ref = lines.first() val table = lines.drop(1).toTable() return enhanceImage(table, ref, 2).let{ it.print() it.sumOf { it.fold<Int>(0) { acc, c -> if (c == '#') acc + 1 else acc } } } } fun part2(lines: List<String>): Int { val ref = lines.first() val table = lines.drop(1).toTable() return enhanceImage(table, ref, 50).let{ it.print() it.sumOf { it.fold<Int>(0) { acc, c -> if (c == '#') acc + 1 else acc } } } } fun main() { val testInput = readInput("day20/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day20/input") println("part1(input) => " + part1(input)) println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,437
advent-of-code
Apache License 2.0
src/2021/Day8_2.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
import java.io.File fun String.matchAnyOrder(values: String) = this.toList().containsAll(values.toList()) fun map(pattern: List<String>, nine: String, six: String, five: String, three: String, two: String, zero: String): Map<String, String> = mapOf<String, String>( Pair(pattern.filter { it.length == nine.length && it.matchAnyOrder(nine) }.first(), "9"), Pair(pattern.filter { it.length == 7 }.first(), "8"), Pair(pattern.filter { it.length == 3 }.first(), "7"), Pair(pattern.filter { it.length == six.length && it.matchAnyOrder(six) }.first(), "6"), Pair(pattern.filter { it.length == five.length && it.matchAnyOrder(five) }.first(), "5"), Pair(pattern.filter { it.length == 4 }.first(), "4"), Pair(pattern.filter { it.length == three.length && it.matchAnyOrder(three) }.first(), "3"), Pair(pattern.filter { it.length == two.length && it.matchAnyOrder(two) }.first(), "2"), Pair(pattern.filter { it.length == 2 }.first(), "1"), Pair(pattern.filter { it.length == zero.length && it.matchAnyOrder(zero) }.first(), "0") ) fun extrapolate(pattern: List<String>): Map<Int, String> { val four = pattern.filter { it.length == 4 }[0] val one = pattern.filter { it.length == 2 }[0] val three = pattern.filter { it.length == 5 && it.matchAnyOrder(one) }[0] val top = pattern.filter { it.length == 3 } .flatMap { it.toList() } .filter { !one.contains(it) }[0] val bottom = pattern.filter { it.length == 6 } .filter { it.matchAnyOrder(four) && it.contains(top) } .flatMap { it.toList() } .filter { !four.contains(it) && it != top }[0] val middle = three.filter { !one.contains(it) && it != top && it != bottom }[0] val topLeft = four.filter { !one.contains(it) && it != middle }[0] val five = pattern.filter { it.length == 5 && it.contains(topLeft) }[0] val topRight = one.filter { !five.contains(it) }[0] val bottomRight = one.filter { five.contains(it) }[0] val two = pattern.filter { it.length == 5 && it.contains(topRight) && !it.contains(bottomRight) }[0] val bottomLeft = two.filter { !three.contains(it) }[0] val nine = "$top$middle$bottom$topLeft$topRight$bottomRight" val six = "$top$middle$bottom$topLeft$bottomRight$bottomLeft" val zero = "$top$bottom$topLeft$topRight$bottomLeft$bottomRight" return mapOf<Int, String>(Pair(9,nine),Pair(6,six),Pair(5,five),Pair(3,three),Pair(2,two),Pair(0,zero)) } val signals = ArrayList<Pair<String, String>>() File("input/2021/day8").forEachLine { line -> val (pattern, output) = line.split("|").map { it.trim() } signals.add(Pair(pattern, output)) } println(signals.map { val pattern = it.first.split(" ") val patterns: Map<Int, String> = extrapolate(pattern) val mapping = map(pattern, patterns[9]!!, patterns[6]!!, patterns[5]!!, patterns[3]!!, patterns[2]!!, patterns[0]!!) it.second.split(" ").map { digit -> mapping.filter { it.key.length == digit.length }.filter { it.key.matchAnyOrder(digit) }.map { it.value }[0] }.joinToString("").toLong() }.sum())
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
3,127
adventofcode
MIT License
src/day13/Day13.kt
palpfiction
572,688,778
false
{"Kotlin": 38770}
package day13 import readInput sealed interface Item : Comparable<Item> class ListItem(val items: List<Item> = listOf()) : Item { override fun toString(): String { return "$items" } override infix fun compareTo(other: Item): Int = when (other) { is IntItem -> this compareTo ListItem(listOf(other)) is ListItem -> items.zip(other.items) .map { it.first compareTo it.second } .filterNot { it == 0 } .firstOrNull() ?: (this.items.size compareTo other.items.size) } } class IntItem(val value: Int) : Item { override fun toString(): String { return "$value" } override infix fun compareTo(other: Item) = when (other) { is IntItem -> this.value compareTo other.value is ListItem -> ListItem(listOf(this)) compareTo other } } fun main() { fun parseItem(input: String): ListItem { input.toIntOrNull()?.let { return ListItem(listOf(IntItem(it))) } val inside = input.removeSurrounding("[", "]") if (inside.isEmpty()) return ListItem() return ListItem( buildList { var current = "" var brackets = 0 for (char in inside) { if (char == '[') brackets++ if (char == ']') brackets-- if (char == ',' && brackets == 0) { add(parseItem(current)) current = "" continue } current += char } add(parseItem(current)) } ) } fun parsePairs(input: List<String>): List<Pair<ListItem, ListItem>> = input .filter { it != "" } .map { parseItem(it) } .chunked(2) .map { (first, second) -> first to second } fun part1(input: List<String>): Int = parsePairs(input) .mapIndexed { index, (first, second) -> if (first < second) index + 1 else 0 } .sum() fun part2(input: List<String>): Int { val firstDivider = ListItem(listOf(IntItem(2))) val secondDivider = ListItem(listOf(IntItem(6))) val sortedPackets = (parsePairs(input) .flatMap { it.toList() } + listOf(firstDivider, secondDivider)) .sortedWith(ListItem::compareTo) return (sortedPackets.indexOf(firstDivider) + 1) * (sortedPackets.indexOf(secondDivider) + 1) } val testInput = readInput("/day13/Day13_test") println(part1(testInput)) println(part2(testInput)) //check(part1(testInput) == 2) //check(part2(testInput) == 4) val input = readInput("/day13/Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7
2,849
advent-of-code
Apache License 2.0
src/main/kotlin/days/Day8.kt
teunw
573,164,590
false
{"Kotlin": 20073}
package days import java.util.* data class Point2D(val x: Int, val y: Int) : Comparable<Point2D> { fun copy(newX: Int? = null, newY: Int? = null): Point2D { return Point2D(newX ?: this.x, newY ?: this.y) } override fun compareTo(other: Point2D): Int { return ((this.x - other.x)) - ((other.y - this.y) * 999) } } fun <T>List<T>.takeUntil(predicate: (T) -> Boolean): List<T> { val newList = mutableListOf<T>() for (it in this) { if (predicate(it)) { newList.add(it) } else { newList.add(it) break; } } return newList.toList() } class Day8 : Day(8) { override fun partOne(): Int { val trees = inputList.flatMapIndexed { x: Int, line: String -> line.mapIndexed { y, char -> Point2D(x, y) to char.digitToInt() } }.toHashSet() val rightEdge = trees.maxOf { it.first.x } val bottomEdge = trees.maxOf { it.first.y } val visibleTrees = trees.filter { (point, height) -> point.x == 0 || point.y == 0 || point.x == rightEdge || point.y == bottomEdge || isTallerThanNeighbors(trees, point, height) }.sortedBy { it.first } return visibleTrees.size } private fun isTallerThanNeighbors(trees: HashSet<Pair<Point2D, Int>>, point: Point2D, height: Int): Boolean { val tallerTrees = trees.filter { it.second >= height } val row = tallerTrees.filter { it.first.x == point.x && point.y != it.first.y } val column = tallerTrees.filter { it.first.y == point.y && point.x != it.first.x } val top = row.filter { it.first.y < point.y } val bottom = row.filter { it.first.y > point.y } val left = column.filter { it.first.x < point.x } val right = column.filter { it.first.x > point.x } return listOf(left, right, top, bottom).any { it.isEmpty() } } private fun getScore(trees: SortedSet<Pair<Point2D, Int>>, point: Point2D, height: Int): Int { val column = trees.filter { it.first.x == point.x && point != it.first } val row = trees.filter { it.first.y == point.y && point != it.first } val top = column.filter { it.first.y < point.y }.reversed() .takeUntil { it.second < height }.count() val bottom = column.filter { it.first.y > point.y } .takeUntil { it.second < height }.count() val left = row.filter { it.first.x < point.x }.reversed() .takeUntil { it.second < height }.count() val right = row.filter { it.first.x > point.x } .takeUntil { it.second < height }.count() return listOf(top, bottom, left, right).filter { it > 0 } .fold(1) { acc, int -> acc.times(int) } } override fun partTwo(): Int { val trees = inputList.flatMapIndexed { y: Int, line: String -> line.mapIndexed { x, char -> Point2D(x, y) to char.digitToInt() } }.toSortedSet { o1, o2 -> o1.first.compareTo(o2.first) } val visibleTrees = trees.map { (point, height) -> point to getScore(trees, point, height) }.sortedBy { it.first } return visibleTrees.maxBy { it.second }.second } }
0
Kotlin
0
0
149219285efdb1a4d2edc306cc449cce19250e85
3,331
advent-of-code-22
Creative Commons Zero v1.0 Universal
src/year2022/day08/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2022.day08 import readInput fun main() { val day = "08" val expectedTest1 = 21 val expectedTest2 = 8 fun checkIt(trees: CharSequence, index: Int, sz: Char) = trees.subSequence(0, index).any { t -> t >= sz } && trees.subSequence(index+1, trees.length).any { t -> t >= sz } fun indexVisibility(trees: CharSequence, index: Int, sz: Char) = (trees.subSequence(1, index).takeLastWhile { t -> t < sz }.length + 1) * (trees.subSequence(index + 1, trees.length - 1).takeWhile { t -> t < sz }.length + 1) fun part1(input: List<String>): Int { val map = input.mapIndexed{ rowNumber, row -> row.mapIndexed { columnNumber, c -> rowNumber != 0 && rowNumber < input.size - 1 && columnNumber != 0 && columnNumber < row.length-1 && checkIt(row, columnNumber, c) && checkIt(input.map { it[columnNumber] }.joinToString(""), rowNumber , c) } } return map.flatten().count { !it } } fun part2(input: List<String>): Int { val map = input.mapIndexed { rowNumber, row -> row.mapIndexed { columnNumber, c -> when { rowNumber == 0 -> 0 rowNumber == input.size-1 -> 0 columnNumber == 0 -> 0 columnNumber == row.length-1 -> 0 else -> indexVisibility(row, columnNumber, c) * indexVisibility(input.map { it[columnNumber] }.joinToString(""), rowNumber, c) } } } return map.flatten().max() } // test if implementation meets criteria from the description, like: val testInput = readInput("year2022/day$day/test") val part1Test = part1(testInput) check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" } val input = readInput("year2022/day$day/input") println(part1(input)) val part2Test = part2(testInput) check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" } println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
2,189
adventOfCode
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/descreasing_subsequences/DecreasingSubsequences.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.descreasing_subsequences import nonstdlib.printed import datsok.shouldEqual import org.junit.Test /** * https://leetcode.com/discuss/interview-question/350233/Google-or-Summer-Intern-OA-2019-or-Decreasing-Subsequences */ class DecreasingSubsequencesTests { @Test fun `split array into strictly decreasing subsequences`() { split(arrayOf(5, 2, 4, 3, 1, 6)).printed() shouldEqual listOf(listOf(5, 2, 1), listOf(4, 3), listOf(6)) split(arrayOf(2, 9, 12, 13, 4, 7, 6, 5, 10)).printed() shouldEqual listOf( listOf(2), listOf(9, 4), listOf(12, 7, 6, 5), listOf(13, 10) ) split(arrayOf(1, 1, 1)).printed() shouldEqual listOf(listOf(1), listOf(1), listOf(1)) leastSubsequences(5, 2, 4, 3, 1, 6) shouldEqual 3 leastSubsequences(2, 9, 12, 13, 4, 7, 6, 5, 10) shouldEqual 4 leastSubsequences(1, 1, 1) shouldEqual 3 } } private fun leastSubsequences(vararg nums: Int): Int { val piles = IntArray(nums.size) var size = 0 for (n in nums) { val pile = binarySearch(piles, size, n) piles[pile] = n if (pile == size) size++ } return size } private fun binarySearch(nums: IntArray, size: Int, target: Int): Int { var from = 0 var to = size while (from < to) { val mid = (from + to) / 2 if (target < nums[mid]) to = mid else from = mid + 1 } return from } private fun split(array: Array<Int>): List<List<Int>> { return allSubsequences(Solution(array.toList())).minByOrNull { it: Solution -> it.seqs.size }!!.seqs } private fun allSubsequences(solution: Solution): List<Solution> { if (solution.isComplete()) return listOf(solution) return solution.nextValidSteps() .flatMap { subSolution -> allSubsequences(subSolution) } } private data class Solution(private val list: List<Int>, val seqs: List<List<Int>> = emptyList()) { fun isComplete() = list.isEmpty() fun nextValidSteps(): List<Solution> { val head = list.first() val tail = list.drop(1) return seqs.mapIndexedNotNull { i, seq -> if (seq.last() <= head) null else { val updatedValue = ArrayList(seqs).also { it[i] = seq + head } Solution(tail, updatedValue) } } + Solution(tail, seqs + listOf(listOf(head))) } override fun toString() = "Solution=$seqs" }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,436
katas
The Unlicense
src/aoc2021/Day09.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2021 import readInput fun main() { val (year, day) = "2021" to "Day09" data class Point(val x: Int, val y: Int, val number: Int, var visited: Boolean = false) { val directions = arrayOf(1 to 0, -1 to 0, 0 to 1, 0 to -1) fun adjacent(mx: Int, my: Int) = directions.mapNotNull { (dx, dy) -> if (x + dx < 0 || x + dx >= mx || y + dy < 0 || y + dy >= my) null else (x + dx) to (y + dy) } } fun List<String>.toPoints() = flatMapIndexed { x, row -> row.mapIndexed { y, col -> Point(x, y, col - '0') } } fun part1(input: List<String>): Int { val mx = input.size val my = input.first().length val points = input.toPoints() return points.sumOf { point -> val low = point.adjacent(mx, my).all { (ax, ay) -> points[ax * my + ay].number > point.number } if (low) point.number + 1 else 0 } } fun part2(input: List<String>): Int { val mx = input.size val my = input.first().length val points = input.toPoints() fun dfsSum(x: Int, y: Int): Int = when { x < 0 || x >= mx || y < 0 || y >= my || points[x * my + y].visited || points[x * my + y].number == 9 -> 0 else -> { points[x * my + y].visited = true 1 + dfsSum(x + 1, y) + dfsSum(x - 1, y) + dfsSum(x, y + 1) + dfsSum(x, y - 1) } } val basinSums = points.mapNotNull { (x, y, number, visited) -> if (visited || number == 9) null else dfsSum(x, y) } return basinSums.sortedDescending().take(3).reduce { acc, i -> acc * i } } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) check(part1(testInput) == 15) println(part1(input)) check(part2(testInput) == 1134) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
1,977
aoc-kotlin
Apache License 2.0
src/main/kotlin/adventofcode2023/day6/day6.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day6 import adventofcode2023.readInput import kotlin.math.sqrt import kotlin.time.measureTime fun main() { val input = readInput("day6") println("Day 6") val duration1 = measureTime { println("Puzzle 1: ${puzzle1(input)}") } println("Puzzle 1 took $duration1") val duration1Optimized = measureTime { println("Puzzle Optimized 1: ${puzzle1Optimized(input)}") } println("Puzzle 1 Solved took $duration1Optimized") val duration1Solved = measureTime { println("Puzzle Solved 1: ${puzzle1Solved(input)}") } println("Puzzle 1 Solved took $duration1Solved") val duration2Optimized = measureTime { println("Puzzle 2 Optimized: ${puzzle2Optimized(input)}") } println("Puzzle 2 Optimized took $duration2Optimized") val duration2Dummy = measureTime { println("Puzzle 2 Dummy: ${puzzle2Dummy(input)}") } println("Puzzle 2 Dummy took $duration2Dummy") } data class Race(val time: Long, val distance: Long) fun parseInput(lines:List<String>): List<Race> { val (timeLine, distanceLine) = lines val time = timeLine.substring("Time:".length).trim().split(' ').filter { it.isNotEmpty() }.map { it.toLong() } val distance = distanceLine.substring("Distance:".length).trim().split(' ').filter { it.isNotEmpty() }.map { it.toLong() } assert(time.size == distance.size) return time.indices.map { index -> Race(time[index], distance[index]) } } fun findWinningStrategiesDummy(race: Race): List<Long> { val combinations = mutableListOf<Long>() for (x in 1 until race.time) { val y = race.time - x if (x * y > race.distance) { combinations.add(x) } } return combinations } fun findWinningStrategiesDummyOptimized(race: Race) = (1 until race.time).count { x -> x * (race.time - x) > race.distance } fun findWinningStrategiesSolves(race: Race): Int { val b = -race.time val c = race.distance val discriminant = b * b - 4 * 1.0 * c return if (discriminant <= 0.0) { throw IllegalStateException("Could not find solution") } else { val root1 = ((-b + sqrt(discriminant)) / (2 * 1.0)) val root2 = ((-b - sqrt(discriminant)) / (2 * 1.0)) val correctedEnd = if (root1 % 1 > 0) { root1.toInt() } else { root1.toInt() -1 } correctedEnd - root2.toInt() // IntRange(start.toInt() + 1, correctedEnd) } } fun puzzle1(input: List<String>): Int { return parseInput(input).map { race -> findWinningStrategiesDummy(race).size }.reduce { acc, i -> acc * i } } fun puzzle1Optimized(input: List<String>): Int { return parseInput(input).map { race -> findWinningStrategiesDummyOptimized(race) }.reduce { acc, i -> acc * i } } fun puzzle1Solved(input: List<String>): Int { return parseInput(input).map { race -> findWinningStrategiesSolves(race) }.reduce { acc, i -> acc * i } } fun parseInput2(lines:List<String>): Race { val (timeLine, distanceLine) = lines val time = timeLine.substring("Time:".length).trim().split(' ').filter { it.isNotEmpty() }.joinToString(separator = "").toLong() val distance = distanceLine.substring("Distance:".length).trim().split(' ').filter { it.isNotEmpty() }.joinToString(separator = "").toLong() return Race(time, distance) } fun puzzle2Dummy(input: List<String>): Int { return parseInput2(input).let { race -> findWinningStrategiesDummy(race).size } } fun puzzle2Optimized(input: List<String>): Int { return findWinningStrategiesDummyOptimized(parseInput2(input)) } fun puzzle2Solved(input: List<String>): Int { return findWinningStrategiesSolves(parseInput2(input)) }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
3,819
adventofcode2023
MIT License
src/Day02.kt
emersonf
572,870,317
false
{"Kotlin": 17689}
typealias Round = Pair<Char, Char> fun toRound(line: String): Round { val segments = line.split(" ") return segments[0].first() to segments[1].first() } fun Round.scoreWithSecondColumnAsHand(): Int { // A == X == Rock // B == Y == Paper // C == Z == Scissors return when { first == 'A' && second == 'X' -> 1 + 3 first == 'A' && second == 'Y' -> 2 + 6 first == 'A' && second == 'Z' -> 3 first == 'B' && second == 'X' -> 1 first == 'B' && second == 'Y' -> 2 + 3 first == 'B' && second == 'Z' -> 3 + 6 first == 'C' && second == 'X' -> 1 + 6 first == 'C' && second == 'Y' -> 2 first == 'C' && second == 'Z' -> 3 + 3 else -> 0 } } fun Round.scoreWithSecondColumnAsResult(): Int { // A == Rock == 1 points if played // B == Paper == 2 points if played // C == Scissors == 3 points if played // X == Lose // Y == Draw // Z == Win return when { first == 'A' && second == 'X' -> 3 first == 'B' && second == 'X' -> 1 first == 'C' && second == 'X' -> 2 first == 'A' && second == 'Y' -> 1 + 3 first == 'B' && second == 'Y' -> 2 + 3 first == 'C' && second == 'Y' -> 3 + 3 first == 'A' && second == 'Z' -> 2 + 6 first == 'B' && second == 'Z' -> 3 + 6 first == 'C' && second == 'Z' -> 1 + 6 else -> 0 } } fun main() { fun part1(input: List<String>): Int = input .map { line -> toRound(line) } .sumOf { it.scoreWithSecondColumnAsHand() } fun part2(input: List<String>): Int = input .map { line -> toRound(line) } .sumOf { it.scoreWithSecondColumnAsResult() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0e97351ec1954364648ec74c557e18ccce058ae6
2,076
advent-of-code-2022-kotlin
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day23/day23.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day23 import eu.janvdb.aocutil.kotlin.point2d.Point2D import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input23-test.txt" const val FILENAME = "input23.txt" fun main() { val map = Puzzle.parse(readLines(2023, FILENAME)) val nodes = map.getNodes() println(nodes.longestPath()) val map2 = map.removeSlopes() val nodes2 = map2.getNodes() println(nodes2.longestPath()) // < 6400 } enum class Tile(val ch: Char) { PATH('.'), FOREST('#'), UP_SLOPE('^'), DOWN_SLOPE('v'), LEFT_SLOPE('<'), RIGHT_SLOPE('>'); companion object { fun fromChar(ch: Char) = entries.first { it.ch == ch } } } data class Nodes(val start: Point2D, val end: Point2D, val distances: Map<Point2D, Map<Point2D, Int>>) { fun longestPath(): Int { return shortestPathFrom(start, mutableSetOf(), 0) } private fun shortestPathFrom(current: Point2D, currentPath: MutableSet<Point2D>, currentDistance: Int): Int { if (current == end) return currentDistance currentPath.add(current) val result = distances.getOrDefault(current, emptyMap()) .filter { it.key !in currentPath } .maxOfOrNull { shortestPathFrom(it.key, currentPath, currentDistance + it.value) } currentPath.remove(current) return result ?: -1 } } data class Puzzle(val width: Int, val height: Int, val tiles: List<Tile>) { fun getNodes(): Nodes { val nodeSet = (0..<height).flatMap { y -> (0..<width).map { x -> Point2D(x, y) } } .filter { getTile(it) != Tile.FOREST } .filter { it.y == 0 || it.y == height - 1 || getNeighbours(it).count() > 2 } .toSet() fun longestPath(node1: Point2D, node2: Point2D): Int { fun visitRestOfPath2(visited: MutableSet<Point2D>, current: Point2D): Int { if (current == node2) return visited.size if (current != node1 && current in nodeSet) return -1 visited.add(current) val result = getNeighbours(current) .filter { it !in visited } .maxOfOrNull { visitRestOfPath2(visited, it) } ?: -1 visited.remove(current) return result } return visitRestOfPath2(mutableSetOf(), node1) } val distances = nodeSet.associateWith { node1 -> nodeSet.asSequence() .filter { it != node1 } .associateWith { node2 -> longestPath(node1, node2) } .filter { it.value != -1 } } return Nodes(nodeSet.first(), nodeSet.last(), distances) } private fun getNeighbours(point: Point2D): Sequence<Point2D> { return when (getTile(point)) { Tile.PATH -> sequenceOf(point.left(), point.right(), point.up(), point.down()) Tile.FOREST -> sequenceOf() Tile.UP_SLOPE -> sequenceOf(point.up()) Tile.DOWN_SLOPE -> sequenceOf(point.down()) Tile.LEFT_SLOPE -> sequenceOf(point.left()) Tile.RIGHT_SLOPE -> sequenceOf(point.right()) }.filter { getTile(it) != Tile.FOREST } } private fun getTile(point: Point2D) = if (point.y < 0 || point.y >= height || point.x < 0 || point.x >= width) Tile.FOREST else tiles[point.y * width + point.x] fun removeSlopes(): Puzzle { val newTiles = tiles.map { if (it == Tile.FOREST) Tile.FOREST else Tile.PATH } return Puzzle(width, height, newTiles) } companion object { fun parse(lines: List<String>): Puzzle { val width = lines[0].length val height = lines.size val tiles = lines.flatMap { line -> line.map { Tile.fromChar(it) } } return Puzzle(width, height, tiles) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
3,359
advent-of-code
Apache License 2.0
src/main/day18/day18.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day18 import readInput fun main() { val input = readInput("main/day18/Day18") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int = input.toCubes().surfaceArea() fun part2(input: List<String>): Int = exteriorSurfaceArea(input.toCubes()) private fun List<String>.toCubes() = map { line -> val (x, y, z) = line.split(",") Cube(x.toInt(), y.toInt(), z.toInt()) } private fun List<Cube>.surfaceArea(): Int = sumOf { it.neighbours().filter { c -> c !in this }.size } private fun exteriorSurfaceArea(cubes: List<Cube>): Int { val minX = cubes.minOf { it.x } - 1 val maxX = cubes.maxOf { it.x } + 1 val minY = cubes.minOf { it.y } - 1 val maxY = cubes.maxOf { it.y } + 1 val minZ = cubes.minOf { it.z } - 1 val maxZ = cubes.maxOf { it.z } + 1 val surface = mutableSetOf<Cube>() val queue = mutableListOf(Cube(minX, minY, minZ)) while (queue.isNotEmpty()) { val current = queue.removeLast() if (current in cubes) continue val (x, y, z) = current if (x !in minX..maxX || y !in minY..maxY || z !in minZ..maxZ) continue if (surface.add(current)) queue.addAll(current.neighbours()) } return cubes.sumOf { it.neighbours().filter { c -> c in surface }.size } } data class Cube(val x: Int, val y: Int, val z: Int) { fun neighbours() = listOf( Cube(x + 1, y, z), Cube(x - 1, y, z), Cube(x, y + 1, z), Cube(x, y - 1, z), Cube(x, y, z + 1), Cube(x, y, z - 1) ) }
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
1,528
aoc-2022
Apache License 2.0
src/year2023/Day4.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import powerOfTwo import readLines fun main() { val input = parseInput(readLines("2023", "day4")) val testInput = parseInput(readLines("2023", "day4_test")) check(part1(testInput) == 13) println("Part 1:" + part1(input)) check(part2(testInput) == 30) println("Part 2:" + part2(input)) } private fun parseInput(input: List<String>): List<Card> { return input .map { it.split(Regex("[:|]")) } .map { Card( it[1].split(" ").filter { it != "" }.map(String::toInt), it[2].split(" ").filter { it != "" }.map(String::toInt), ) } } private fun part1(input: List<Card>): Int { return input .map { card -> card.numbers.filter { number -> card.winningNumbers.contains(number) }.size } .filter { it >= 1 } .sumOf { powerOfTwo(it - 1) } } private fun part2(input: List<Card>): Int { val instances = input.indices.map { Pair(it, 1) }.toMap().toMutableMap() for (i in input.indices) { val card = input[i] val count = instances[i]!! val numberOfWonCards = card.numbers.filter { number -> card.winningNumbers.contains(number) }.size for (j in (1..numberOfWonCards)) { val k = i + j val oldValue = instances.getOrDefault(k, 1) instances[k] = oldValue + count } } return instances.values.sum() } private data class Card(val winningNumbers: List<Int>, val numbers: List<Int>)
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,511
advent_of_code
MIT License
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day22/Day22.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day22 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines object Day22 : Day { override val input = readInputLines(22).map { Step.from(it) } override fun part1(): Number { return input .filter { it.cuboid.inRange(-50..50) } .fold(emptySet<Triple<Int, Int, Int>>()) { a, c -> when (c.state) { State.OFF -> a.minus(c.cuboid.combinations()) State.ON -> a.plus(c.cuboid.combinations()) } }.count() } override fun part2(): Number { val cubes = mutableListOf<Step>() input.forEach { cubes.addAll(buildList { cubes.forEach { step -> it.cuboid.overlap(step.cuboid)?.apply { add(Step(!step.state, this)) } } }) if (it.state == State.ON) cubes.add(it) } return cubes.sumOf { it.state.sign * it.cuboid.size() } } enum class State(val sign: Int) { ON(1), OFF(-1); operator fun not() = when (this) { ON -> OFF OFF -> ON } } data class Cuboid(val x: IntRange, val y: IntRange, val z: IntRange) { fun combinations() = buildSet { for (x in x) for (y in y) for (z in z) add(Triple(x, y, z)) } fun inRange(range: IntRange) = listOf(x, y, z).all { range.contains(it.first) && range.contains(it.last) } fun size() = x.size() * y.size() * z.size() fun overlap(other: Cuboid): Cuboid? { return listOf<Cuboid.() -> IntRange>({ x }, { y }, { z }) .map { it(this).overlap(it(other)) } .takeIf { r -> r.all { it.first <= it.second } } ?.map { it.first..it.second } ?.let { (x, y, z) -> Cuboid(x, y, z) } } private fun IntRange.overlap(other: IntRange) = maxOf(first, other.first) to minOf(last, other.last) private fun IntRange.size(): Long = (last - first + 1).toLong() } data class Step(val state: State, val cuboid: Cuboid) { companion object { fun from(line: String): Step { val state = State.valueOf(line.substringBefore(" ").uppercase()) val (x, y, z) = line.substringAfter(" ").split(",") .map { s -> s.substringAfter("=").split("..").map { it.toInt() }.let { it.first()..it.last() } } return Step(state, Cuboid(x, y, z)) } } } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
2,528
aoc2021
MIT License
src/main/kotlin/advent/y2018/day3.kt
IgorPerikov
134,053,571
false
{"Kotlin": 29606}
package advent.y2018 import misc.readAdventInput /** * https://adventofcode.com/2018/day/3 */ const val notVisited = 0 const val visited = 1 const val collision = 2 fun main(args: Array<String>) { val claims = readClaims() val collisionsMap = buildCollisionsMap(claims) calculateCollisions(collisionsMap).also { println(it) } findIntactClaim(claims, collisionsMap).also { println(it) } } private fun calculateCollisions(collisionsMap: Array<Array<Int>>): Int { return collisionsMap.sumBy { ints -> ints.filter { it == collision }.sumBy { 1 } } } private fun findIntactClaim(claims: List<Claim>, collisionsMap: Array<Array<Int>>): Int { for (claim in claims) { var collisionsFound = 0 outer@ for (i in claim.row until claim.row + claim.rows) { for (j in claim.column until claim.column + claim.columns) { if (collisionsMap[i][j] == collision) { collisionsFound++ break@outer } } } if (collisionsFound == 0) { return claim.id } } throw IllegalArgumentException("No intact claims found") } private fun buildCollisionsMap(claims: List<Claim>): Array<Array<Int>> { val fabric = Array(1000) { Array(1000) { notVisited } } for (claim in claims) { for (i in claim.row until claim.row + claim.rows) { for (j in claim.column until claim.column + claim.columns) { when (fabric[i][j]) { notVisited -> fabric[i][j] = visited visited -> { fabric[i][j] = collision } } } } } return fabric } private fun readClaims() = readAdventInput(3, 2018).map(::parseClaim) private fun parseClaim(claim: String): Claim { val (id, claimWithoutId) = claim.substringAfter("#").split(" @ ") val (column, row) = claimWithoutId.substringBefore(": ").split(",") val (columns, rows) = claimWithoutId.substringAfter(": ").split("x") return Claim(id.toInt(), column.toInt(), row.toInt(), columns.toInt(), rows.toInt()) } private data class Claim( val id: Int, val column: Int, val row: Int, val columns: Int, val rows: Int )
0
Kotlin
0
0
b30cf179f7b7ae534ee55d432b13859b77bbc4b7
2,286
kotlin-solutions
MIT License
src/main/kotlin/Day08.kt
joostbaas
573,096,671
false
{"Kotlin": 45397}
fun List<String>.parse(): Forest = Forest(map { line -> line.map { it.digitToInt() } }) data class Tree(val x: Int, val y: Int) { fun treesBetween(other: Tree): List<Tree> { require(other.x == x || other.y == y) require(other != this) return when { other.x < x -> (other.x until x).map { Tree(it, y) }.filterNot { it == this || it == other }.reversed() other.y < y -> (other.y until y).map { Tree(x, it) }.filterNot { it == this || it == other }.reversed() other.x > x -> (x until other.x).map { Tree(it, y) }.filterNot { it == this || it == other } other.y > y -> (y until other.y).map { Tree(x, it) }.filterNot { it == this || it == other } else -> throw IllegalArgumentException() } } } class Forest(private val grid: List<List<Int>>) { private val horizontalSize = grid[0].size private val verticalSize = grid.size private val allTrees = (0 until horizontalSize).flatMap { xc -> (0 until verticalSize).map { yc -> Tree(xc, yc) } } fun countVisibleFromOutside(): Int { return allTrees.count { it.isVisibleFromOutside() } } fun List<List<Int>>.get(tree: Tree) = this[tree.y][tree.x] private fun Tree.seesOther(other: Tree): Boolean = grid.get(this).let { thisTreeSize -> treesBetween(other).all { val treeInBetweenSize = grid.get(it) treeInBetweenSize < thisTreeSize } } private fun Tree.neighboursBottom() = (y + 1 until verticalSize).map { Tree(x, it) } private fun Tree.neighboursTop() = (0 until y).map { Tree(x, it) } private fun Tree.neighboursRight() = (x + 1 until horizontalSize).map { Tree(it, y) } private fun Tree.neighboursLeft() = (0 until x).map { Tree(it, y) } private fun Tree.scenicScore(): Int = listOf( neighboursTop(), neighboursLeft(), neighboursRight(), neighboursBottom(), ).map { neighbours -> neighbours.count { otherTree -> seesOther(otherTree) } } .fold(1) { acc, count -> count * acc } fun highestScenicScore() = allTrees.maxOf { it.scenicScore() } private fun Tree.isVisibleFromOutside(): Boolean { if (x == 0 || y == 0 || x == horizontalSize - 1 || y == verticalSize - 1) return true val sizeOfTree = grid.get(this) return listOf( neighboursLeft(), neighboursRight(), neighboursTop(), neighboursBottom(), ).any { neighbours -> neighbours.all { grid.get(it) < sizeOfTree } } } } fun day08Part1(input: List<String>): Int = input.parse().countVisibleFromOutside() fun day08Part2(input: List<String>): Int = input.parse().highestScenicScore()
0
Kotlin
0
0
8d4e3c87f6f2e34002b6dbc89c377f5a0860f571
2,820
advent-of-code-2022
Apache License 2.0
kotlin/src/Day17.kt
ekureina
433,709,362
false
{"Kotlin": 65477, "C": 12591, "Rust": 7560, "Makefile": 386}
import java.lang.Integer.parseInt import kotlin.math.abs fun main() { fun updateVelocity(velocity: Pair<Int, Int>): Pair<Int, Int> { val xVelocityChange = if (velocity.first == 0) { 0 } else if (velocity.first > 0) { -1 } else { 1 } return (velocity.first + xVelocityChange) to (velocity.second - 1) } fun runFiring(initialVelocity: Pair<Int, Int>, xRange: IntRange, yRange: IntRange): Int? { var xPos = 0 var yPos = 0 var highestY = 0 var velocity = initialVelocity while (xPos !in xRange || yPos !in yRange) { if (yPos < yRange.first) { return null } xPos += velocity.first yPos += velocity.second highestY = maxOf(highestY, yPos) velocity = updateVelocity(velocity) } return highestY } fun part1(input: List<String>): Int { val (xSpec, ySpec) = input[0].removePrefix("target area: x=").split(", y=") val xRange = xSpec.split("..").let { (low, high) -> parseInt(low)..parseInt(high) } val yRange = ySpec.split("..").let { (low, high) -> parseInt(low)..parseInt(high) } var highestY = 0 (0..xRange.last).forEach { initialXVelocity -> (yRange.first..abs(yRange.first) * 3).forEach { initialYVelocity -> runFiring(initialXVelocity to initialYVelocity, xRange, yRange)?.also { foundMax -> highestY = maxOf(highestY, foundMax) } } } return highestY } fun part2(input: List<String>): Int { val (xSpec, ySpec) = input[0].removePrefix("target area: x=").split(", y=") val xRange = xSpec.split("..").let { (low, high) -> parseInt(low)..parseInt(high) } val yRange = ySpec.split("..").let { (low, high) -> parseInt(low)..parseInt(high) } return (0..xRange.last).sumOf { initialXVelocity -> (yRange.first..abs(yRange.first) * 3).count { initialYVelocity -> runFiring(initialXVelocity to initialYVelocity, xRange, yRange) != null } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") check(part1(testInput) == 45) { "${part1(testInput)}" } check(part2(testInput) == 112) { "${part2(testInput)}" } val input = readInput("Day17") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
391d0017ba9c2494092d27d22d5fd9f73d0c8ded
2,464
aoc-2021
MIT License
src/day16/Day16.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day16 import readInput data class Node(val value: Int, val next: MutableList<String>) data class BfsEntry(val position: String, val remainder: Int, val open: List<String>) fun main() { fun floydWarshall(graph: Map<String, Node>): Map<String, Map<String, Int>> { val distances = mutableMapOf<String, MutableMap<String, Int>>() for (u in graph.keys) { distances[u] = mutableMapOf() for (v in graph.keys) { distances[u]!![v] = if (u == v) { 0 } else if (graph[u]!!.next.contains(v) || graph[v]!!.next.contains(u)) { 1 } else { graph.keys.size + 1 } } } for (i in graph.keys) for (j in graph.keys) for (k in graph.keys) { if (distances[i]!![k]!! + distances[k]!![j]!! <= distances[i]!![j]!!) { distances[i]?.set(j, distances[i]!![k]!! + distances[k]!![j]!!) distances[j]?.set(i, distances[i]!![k]!! + distances[k]!![j]!!) } } return distances } fun solutionGenerator( graph: Map<String, Node>, distances: Map<String, Map<String, Int>>, start: String, maxTime: Int, opened: Set<String> = setOf(), yieldAll: Boolean = false ) = sequence { val nodes: Set<String> = graph.filter { it.value.value > 0 }.filter { !opened.contains(it.key) }.keys val queue = mutableListOf(BfsEntry(start, maxTime, listOf())) while (queue.isNotEmpty()) { val (position, remainder, open) = queue.removeFirst() val successors = nodes.subtract(open.toSet()).filter { distances[position]?.get(it)!! + 1 <= remainder } if (yieldAll || successors.isEmpty()) { yield(open) } successors.forEach { next -> queue.add(BfsEntry( next, remainder - distances[position]?.get(next)!! - 1, open.toMutableList().also { it.add(next) } )) } } } fun getReleasedPressure( graph: Map<String, Node>, distances: Map<String, Map<String, Int>>, open: List<String>, start: String, maxTime: Int ): Int { var position = start var remainingTime = maxTime var pressureReleased = 0 for (next in open) { remainingTime -= distances[position]!![next]!! + 1 pressureReleased += remainingTime * graph[next]!!.value position = next } return pressureReleased } fun part1(graph: Map<String, Node>, start: String = "AA", maxTime: Int = 30): Int { val distances = floydWarshall(graph) return solutionGenerator(graph, distances, start, maxTime).asIterable() .maxOf { getReleasedPressure(graph, distances, it, start, maxTime) } } fun part2(graph: Map<String, Node>, start: String = "AA", maxTime: Int = 26): Int { val distances = floydWarshall(graph) return solutionGenerator(graph, distances, start, maxTime, setOf(), true).asIterable() .maxOf { val protagonistReleased = getReleasedPressure(graph, distances, it, start, maxTime) val elephantReleased = solutionGenerator(graph, distances, start, maxTime, it.toSet()).asIterable() .maxOf { elephant -> getReleasedPressure(graph, distances, elephant, start, maxTime) } protagonistReleased + elephantReleased } } fun preprocess(input: List<String>): Map<String, Node> = input.associate { inputStr -> val split = inputStr.split(" ") Pair( split[1], Node( split[4].removePrefix("rate=").removeSuffix(";").toInt(), split.subList(9, split.size).map { it.replace(',', ' ').trim() }.toMutableList() ) ) } // test if implementation meets criteria from the description, like: val testInput = readInput(16, true) check(part1(preprocess(testInput)) == 1651) val input = readInput(16) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 1707) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
4,379
advent-of-code-2022
Apache License 2.0
src/Day02.kt
brunojensen
572,665,994
false
{"Kotlin": 13161}
private operator fun String.component1() = this[0].toString() private operator fun String.component2() = this[1].toString() private operator fun String.component3() = this[2].toString() private enum class Play(val point: Int, val beats: Play? = null, val loses: Play? = null) { // Rock, Paper, Scissor A(0), B(0), C(0), X(1, C, B), Y(2, A, C), Z(3, B, A); } private fun game1(his: Play, mine: Play): Int { return when (his) { mine.beats -> mine.point + 6 mine.loses -> mine.point + 0 else -> mine.point + 3 } } private fun game2(his: Play, mine: Play): Int { return when (mine) { Play.X -> Play.values().filter { null != it.loses }.first { it.loses == his }.point + 0 Play.Z -> Play.values().filter { null != it.beats }.first { it.beats == his }.point + 6 Play.Y -> Play.values().filter { null != it.beats && null != it.loses }.first { it.beats != his && it.loses != his }.point + 3 else -> 0 } } fun main() { fun part1(input: List<String>): Int { return input .sumOf { val (first, _, last) = it game1(Play.valueOf(first), Play.valueOf(last)) } } fun part2(input: List<String>): Int { return input .sumOf { val (first, _, last) = it game2(Play.valueOf(first), Play.valueOf(last)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02.test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2707e76f5abd96c9d59c782e7122427fc6fdaad1
1,572
advent-of-code-kotlin-1
Apache License 2.0
gcj/y2020/kickstart_d/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.kickstart_d private fun solve(): Double { val (n, a, b) = readInts() val p = listOf(0, 0) + readInts() val p1 = probs(p, a) val p2 = probs(p, b) val x = (1 until p.size).map { p1[it].toLong() * p2[it] }.sum() return p.size - 1 - x / (p.size - 1.0) / (p.size - 1) } private fun probs(p: List<Int>, a: Int): IntArray { val q = 22 val n = p.size val r = List(q) { IntArray(n) } for (i in p.indices) r[0][i] = p[i] for (j in 1 until q) { for (i in p.indices) r[j][i] = r[j - 1][r[j - 1][i]] } val up = IntArray(n) { i -> var k = i for (j in 0 until q) { if (((a shr j) and 1) == 0) continue k = r[j][k] } k } val below = IntArray(n) for (i in below.indices.reversed()) { below[i]++ below[up[i]] += below[i] } return IntArray(n) { n - 1 - below[it] } } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ").filter { it.isNotEmpty() } private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,092
competitions
The Unlicense
src/Day05.kt
Miguel1235
726,260,839
false
{"Kotlin": 21105}
val obtainSeeds = { input: List<String> -> input[0].split(":")[1].trim().split(" ") } private data class Mapper(val name: String, val ranges: List<Range>) private data class Range(val ds: Long, val de: Long, val ss: Long, val se: Long, val range: Long, val diff: Long) private fun obtainMappers(input: List<String>): List<Mapper> { var ranges: List<Range> = mutableListOf() var cat: String = input[2] val mappers: List<Mapper> = mutableListOf() for (i in 2 + 1..<input.size) { val line = input[i] if (line.contains("seeds") || line.isEmpty()) continue if (line.contains("-to-")) { mappers.addLast(Mapper(cat, ranges)) cat = line ranges = mutableListOf() } else { val (ds, ss, r) = line.split(" ").map { it.toLong() } val de = ds + r - 1 val se = ss + r - 1 ranges.addLast(Range(ds, de, ss, se, r, ds - ss)) } } mappers.addLast(Mapper(cat, ranges)) return mappers } private fun applyMap(seed: Long, mapper: Mapper): Long { for (range in mapper.ranges) if (seed >= range.ss && seed <= range.se) return seed + range.diff return seed } private fun findFinalLocation(seed: Long, mappers: List<Mapper>): Long { var newSeedValue = seed for (map in mappers) newSeedValue = applyMap(newSeedValue, map) return newSeedValue } private fun part1(input: List<String>): Long { val seeds = obtainSeeds(input).map { it.toLong() } val mappers = obtainMappers(input) var min = 99999999999 for (seed in seeds) { val r = findFinalLocation(seed, mappers) if (r < min) min = r } return min } private fun obtainAllSeeds(input: List<String>): List<Sequence<Long>> { val line = input[0].split(":")[1].trim().split(" ").map { it.toLong() } val seeds: List<Sequence<Long>> = mutableListOf() for (i in line.indices step 2) { val startSeed = line[i] val items = line[i + 1] seeds.addLast(generateSequence(startSeed) { if (it < startSeed + items-1) it + 1 else null }) } return seeds } private fun part2(input: List<String>): Long { val seeds = obtainAllSeeds(input) val mappers = obtainMappers(input) var min = 99999999999 for (seed in seeds) { for(value in seed) { val r = findFinalLocation(value, mappers) if (r < min) min = r } } return min } fun main() { val testInput = readInput("Day05_test") check(part1(testInput) == 35L) check(part2(testInput) == 46L) val input = readInput("Day05") check(part1(input) == 836040384L) check(part2(input) == 10834440L) }
0
Kotlin
0
0
69a80acdc8d7ba072e4789044ec2d84f84500e00
2,686
advent-of-code-2023
MIT License
src/main/kotlin/aoc2023/Day04.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput import java.util.* import java.util.regex.Pattern import kotlin.math.pow private data class Card(val id: Int, val winningNumbers: Set<Int>, val cardNumbers: Set<Int>) { val matches = winningNumbers.intersect(cardNumbers) val worth = if (matches.isEmpty()) 0 else 2f.pow(matches.size - 1).toInt() companion object { private val regex = Pattern.compile("""Card\s+(?<id>\d+): (?<winning>[\d\s]+) \| (?<card>[\d\s]+)""") fun fromString(input: String): Card { val matcher = regex.matcher(input) if (matcher.matches()) { val winningNumbers = matcher.group("winning").split(' ').filter { it.isNotBlank() }.map { it.toInt() }.toSet() val cardNumbers = matcher.group("card").split(' ').filter { it.isNotBlank() }.map { it.toInt() }.toSet() return Card(matcher.group("id").toInt(), winningNumbers, cardNumbers) } else { throw IllegalArgumentException("Does not match: $input") } } } } object Day04 { fun part1(input: List<String>) = input.map { Card.fromString(it) }.sumOf { it.worth } fun part2(input: List<String>): Int { val cardMap = input.map { Card.fromString(it) }.associateBy { it.id } val myCards = cardMap.values.associateWith { 0 }.toMutableMap() cardMap.values.forEach { card -> val currentAmount = myCards[card] ?: 1 val newAmount = currentAmount + 1 myCards[card] = newAmount repeat(card.matches.size) { val wonCardId = card.id + it + 1 val wonCard = cardMap[wonCardId] ?: throw IllegalArgumentException("Unknown card: $wonCardId") myCards[wonCard] = (myCards[wonCard] ?: 0) + newAmount } } return myCards.values.sum() } } fun main() { val testInput = readInput("Day04_test", 2023) check(Day04.part1(testInput) == 13) check(Day04.part2(testInput) == 30) val input = readInput("Day04", 2023) println(Day04.part1(input)) println(Day04.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
2,150
adventOfCode
Apache License 2.0
src/day02/day02.kt
taer
573,051,280
false
{"Kotlin": 26121}
package day02 import readInput enum class RPS(val value: Int) { ROCK(1), PAPER(2), Scissors(3) } fun translate(input: String): RPS { return when (input) { "A", "X" -> RPS.ROCK "B", "Y" -> RPS.PAPER "C", "Z" -> RPS.Scissors else -> throw RuntimeException("Dunno what $input is") } } sealed class Result(val points: Int) { object Win : Result(6) object Tie : Result(3) object Lose : Result(0) } fun score(us: RPS, them: RPS): Result { return if (us == them) { Result.Tie } else { when (us) { RPS.ROCK -> if (them == RPS.Scissors) Result.Win else Result.Lose RPS.Scissors -> if (them == RPS.PAPER) Result.Win else Result.Lose RPS.PAPER -> if (them == RPS.ROCK) Result.Win else Result.Lose } } } data class Moves(val their: RPS, val ours: RPS) fun translateInput(input: List<String>): List<Moves> { return input.map { it.split(" ") }.map { val theirMove = translate(it[0]) val ourMove = translate(it[1]) Moves(their = theirMove, ours = ourMove) } } fun calcWin(input: List<Moves>) = input.sumOf { (theirMove, ourMove) -> val score = score(ourMove, theirMove) score.points + ourMove.value } fun main() { fun loseTo(input: RPS): RPS = when (input){ RPS.ROCK -> RPS.Scissors RPS.PAPER -> RPS.ROCK RPS.Scissors -> RPS.PAPER } fun winTo(input: RPS): RPS = when (input){ RPS.ROCK -> RPS.PAPER RPS.PAPER -> RPS.Scissors RPS.Scissors -> RPS.ROCK } fun tieTo(input: RPS): RPS = input fun part1(input: List<String>): Int { val inputData = translateInput(input) return calcWin(inputData) } fun part2(input: List<String>): Int { val inputData = translateInput(input) val newMoves = inputData.map { val desiredOutcome = when(it.ours){ RPS.ROCK -> Result.Lose RPS.PAPER -> Result.Tie RPS.Scissors -> Result.Win } val ourNewMove = when (desiredOutcome) { Result.Lose -> ::loseTo Result.Tie -> ::tieTo Result.Win -> ::winTo } it.copy(ours = ourNewMove(it.their)) } return calcWin(newMoves) } val testInput = readInput("day02", true) val input = readInput("day02") check(part1(testInput) == 15) println(part1(input)) check(part2(testInput) == 12) println(part2(input)) }
0
Kotlin
0
0
1bd19df8949d4a56b881af28af21a2b35d800b22
2,551
aoc2022
Apache License 2.0
src/main/kotlin/Day19.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset fun main() { class Rule(val category: Char, val limit: Int, val greater: Boolean, val result: String) { fun run(part: Map<Char, Int>): String? { return if (greater) { if (part[category]!! > limit) result else null } else { if (part[category]!! < limit) result else null } } } fun parseWorkflows(input: List<String>): Map<String, List<Rule>> { return input.associate { val items = it.split('{', '}', ',').filterNot { s -> s.isBlank() } val id = items.first val rules = items.subList(1, items.size).map { s -> if (s.contains(':')) { val parts = s.split('<', '>', ':') val greater = s[1] == '>' val limit = parts[1].toInt() Rule(s.first(), limit, greater, parts.last) } else { Rule('x', 0, true, s) } } id to rules } } fun parseParts(input: List<String>): List<Map<Char, Int>> { return input.map { val items = it.split('{', '}', ',').filterNot { s -> s.isBlank() } items.associateBy({ item -> item.first() }, { item -> item.substringAfter('=').toInt() }) } } fun part1(input: List<String>): Int { val divider = input.indexOf("") val workflows: Map<String, List<Rule>> = parseWorkflows(input.subList(0, divider)) val parts = parseParts(input.subList(divider + 1, input.size)) return parts.sumOf { var result = "in" while (result !in setOf("A", "R")) { val temp: List<Rule> = workflows[result]!! result = temp.firstNotNullOf { rule -> rule.run(it) } } if (result == "A") { it.values.sum() } else { 0 } } } fun getAcceptedMasks( workflows: Map<String, List<Rule>>, ): List<Pair<String, List<Pair<Char, IntRange>>>> { fun permuteRules( rules: List<Rule>, masks: List<Pair<Char, IntRange>> ): List<Pair<String, List<Pair<Char, IntRange>>>> { val rule = rules.first() if (rule.limit == 0) { return if (rule.result in setOf("A", "R")) { listOf(rule.result to masks) } else { permuteRules(workflows[rule.result]!!, masks) } } return if (rule.greater) { if (rule.result in setOf("A", "R")) { listOf(rule.result to (masks + (rule.category to rule.limit + 1..4000))) + permuteRules(rules.subList(1, rules.size), masks + (rule.category to (1..rule.limit))) } else { permuteRules(workflows[rule.result]!!, masks + (rule.category to (rule.limit + 1..4000))) + permuteRules(rules.subList(1, rules.size), masks + (rule.category to (1..rule.limit))) } } else { if (rule.result in setOf("A", "R")) { listOf(rule.result to (masks + (rule.category to (1..<rule.limit)))) + permuteRules(rules.subList(1, rules.size), masks + (rule.category to (rule.limit..4000))) } else { permuteRules(workflows[rule.result]!!, masks + (rule.category to (1..<rule.limit))) + permuteRules(rules.subList(1, rules.size), masks + (rule.category to (rule.limit..4000))) } } } return permuteRules(workflows["in"]!!, listOf('x' to (1..4000), 'm' to (1..4000), 'a' to (1..4000), 's' to (1..4000))) } fun part2(input: List<String>): Long { val divider = input.indexOf("") val workflows: Map<String, List<Rule>> = parseWorkflows(input.subList(0, divider)) val partMask = getAcceptedMasks(workflows) val res = partMask.filter { it.first == "A" }.sumOf { pair -> pair.second.groupBy({ it.first }, { it.second }) .values.map { it.fold((1..4000).toSet()) { acc, intRange -> acc.intersect(intRange) } }.fold(1L) { acc, ints -> acc * ints.size } } return res } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day19-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
4,911
aoc-2023-in-kotlin
Apache License 2.0
codeforces/globalround16/f.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.globalround16 private fun solve() { val (_, m) = readInts() val points = readInts().sorted() val segments = List(m) { readInts().let { it[0] to it[1] } } val groups = List(points.size + 1) { mutableListOf<Pair<Int, Int>>() } for (segment in segments) { val index = (-1..points.size).binarySearch { points[it] >= segment.first } if (index < points.size && points[index] <= segment.second) continue groups[index].add(segment) } var ifEats = 0L var ifGives = 0L val inf = Long.MAX_VALUE / 8 for (k in groups.indices) { groups[k].sortBy { it.first } val g = mutableListOf<Pair<Int, Int>>() for (segment in groups[k]) { if (g.isEmpty()) { g.add(segment) continue } if (g.last().first == segment.first && g.last().second <= segment.second) continue while (g.isNotEmpty() && g.last().first <= segment.first && segment.second <= g.last().second) { g.pop() } g.add(segment) } val pPrev = points.getOrElse(k - 1) { -inf }.toLong() val pNext = points.getOrElse(k) { inf }.toLong() var newIfEats = inf var newIfGives = inf for (i in 0..g.size) { val comeLeft = g.getOrNull(i - 1)?.first?.toLong() ?: pPrev val comeRight = g.getOrNull(i)?.second?.toLong() ?: pNext val leftBest = minOf(ifEats + 2 * (comeLeft - pPrev), ifGives + comeLeft - pPrev) val possibleIfEats = leftBest + pNext - comeRight newIfEats = minOf(newIfEats, possibleIfEats) val possibleIfGives = leftBest + 2 * (pNext - comeRight) newIfGives = minOf(newIfGives, possibleIfGives) } ifEats = newIfEats ifGives = newIfGives } println(minOf(ifEats, ifGives)) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() } private fun IntRange.binarySearch(predicate: (Int) -> Boolean): Int { var (low, high) = this.first to this.last // must be false ... must be true while (low + 1 < high) (low + (high - low) / 2).also { if (predicate(it)) high = it else low = it } return high // first true } private fun <T> MutableList<T>.pop() = removeAt(lastIndex)
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,190
competitions
The Unlicense
src/Day18.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
enum class Material { WATER, LAVA } fun main() { data class Cube(val x: Int, val y: Int, val z: Int) { operator fun plus(other: Cube): Cube { return Cube(x + other.x, y + other.y, z + other.z) } operator fun minus(other: Cube): Cube { return Cube(x - other.x, y - other.y, z - other.z) } fun neigbours(): List<Cube> { val diffs = listOf( Cube(1, 0, 0), Cube(-1, 0, 0), Cube(0, 1, 0), Cube(0, -1, 0), Cube(0, 0, 1), Cube(0, 0, -1) ) return diffs.map { x -> x + this } } fun volume(): Int { return x * y * z } } fun parseCube(input: String): Cube { val (x, y, z) = input.split(",").map { x -> x.toInt() } return Cube(x, y, z) } fun part1(input: List<String>): Int { val cubes = HashSet(input.map { s -> parseCube(s) }) var ans = cubes.size * 6 for (cube in cubes) { for (neigbour in cube.neigbours()) { if (neigbour in cubes) { ans -= 1 } } } return ans } fun dfs(cube: Cube, world: MutableMap<Cube, Material>, start: Cube, end: Cube) { for (neigbour in cube.neigbours()) { if (!world.contains(neigbour) && neigbour.x >= start.x && neigbour.y >= start.y && neigbour.z >= start.z && neigbour.x <= end.x && neigbour.y <= end.y && neigbour.z <= end.z) { world[neigbour] = Material.WATER dfs(neigbour, world, start, end) } } } fun part2(input: List<String>): Int { val cubes = HashSet(input.map { s -> parseCube(s) }) val start = Cube(cubes.minOf { cube -> cube.x } - 3, cubes.minOf { cube -> cube.y } - 3, cubes.minOf { cube -> cube.z } - 3) val end = Cube(cubes.maxOf { cube -> cube.x } + 3, cubes.maxOf { cube -> cube.y } + 3, cubes.maxOf { cube -> cube.z } + 3) val world = cubes.associateWith { _ -> Material.LAVA }.toMutableMap() world[start] = Material.WATER println("World Size: ${(end - start).volume()}") dfs(start, world, start, end) return cubes.sumOf { cube -> cube.neigbours().count { neigbour -> world[neigbour] == Material.WATER } } } val testInput = readInput("Day18-test") val input = readInput("Day18") println("Day18") println("test part1: ${part1(testInput)}") println("real part1: ${part1(input)}") println("test part2: ${part2(testInput)}") println("real part2: ${part2(input)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
2,695
aoc-2022
Apache License 2.0
src/Day08.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
fun List<Char>.distance(): Int = if (isNotEmpty()) size else 1 fun List<Char>.takeUntilEquals(target: Int): List<Char> { val list = mutableListOf<Char>() for (c in this) { list.add(c) if (c.digitToInt() >= target) { break } } return list } fun main() { fun part1(input: List<String>): Int { var count = 0 val perimeter = 2 * ((input.size - 2) + input.first().length) val rowLength = input.first().length - 1 for (y in 1 until input.size - 1) { for (x in 1 until rowLength) { // TODO this can be cleaned up val tree = input[y][x].digitToInt() val maxLeft = input[y].toCharArray().take(x).maxOf { it.digitToInt() } val maxRight = input[y].toCharArray().takeLast(rowLength - x).maxOf { it.digitToInt() } val maxTop = input.take(y).maxOf { it[x].digitToInt() } val maxBottom = input.takeLast(input.size - 1 - y).maxOf { it[x].digitToInt() } if ((tree > maxLeft) || (tree > maxRight) || (tree > maxTop) || (tree > maxBottom)) { count++ } } } return count + perimeter } fun part2(input: List<String>): Int { val rowLength = input.first().length - 1 var maxScore = 0 for (y in 1 until input.size - 1) { for (x in 1 until rowLength) { val tree = input[y][x].digitToInt() val treesLeft = input[y].toCharArray().take(x).reversed().takeUntilEquals(tree) val treesRight = input[y].toCharArray().takeLast(rowLength - x).takeUntilEquals(tree) val treesTop = input.take(y).map { it[x] }.reversed().takeUntilEquals(tree) val treesBottom = input.takeLast(input.size - 1 - y).map { it[x] }.takeUntilEquals(tree) val score = treesLeft.distance() * treesRight.distance() * treesTop.distance() * treesBottom.distance() maxScore = maxScore.coerceAtLeast(score) } } return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
2,406
advent-of-code-2022
Apache License 2.0
src/y2023/Day03.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.Pos import util.indexOfAll import util.neighbors import util.readInput import util.timingStatistics object Day03 { private fun numbers(input: List<String>): List<Pair<Set<Pos>, Int>> { return input.flatMapIndexed { row, line -> val numbers = Regex("\\d+").findAll(line) numbers.map { val positions = it.range.map { col -> row to col }.toSet() positions to it.value.toInt() } } } private fun symbols(input: List<String>): List<Pos> { return input.flatMapIndexed { row: Int, line: String -> val symbolPositions = line.toList().indexOfAll { it != '.' && !it.isDigit() } symbolPositions.map { row to it } } } fun part1(input: List<String>): Long { val numbers = numbers(input) val symbols = symbols(input) val neighbors = symbols.flatMap { it.neighbors() }.toSet() return numbers.filter { (poss, _) -> poss.any { it in neighbors } }.sumOf { it.second.toLong() } } private fun gearCandidates(input: List<String>): List<Pos> { return input.flatMapIndexed { row: Int, line: String -> val gearPositions = line.toList().indexOfAll { it == '*' } gearPositions.map { row to it } } } fun part2(input: List<String>): Int { val numbers = numbers(input) val numberLookup = numbers.flatMap {(poss, num) -> poss.map { it to (poss to num) } }.toMap() val gearCandidates = gearCandidates(input) return gearCandidates.map { it.neighbors() }.sumOf { gearNeighbors -> val numberNeighbors = gearNeighbors.mapNotNull { numberLookup[it] }.distinct() if (numberNeighbors.size == 2) { numberNeighbors[0].second * numberNeighbors[1].second } else { 0 } } } } fun main() { val testInput = """ 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...${'$'}.*.... .664.598.. """.trimIndent().split("\n") println("------Tests------") println(Day03.part1(testInput)) println(Day03.part2(testInput)) println("------Real------") val input = readInput("resources/2023/day03") println("Part 1 result: ${Day03.part1(input)}") println("Part 2 result: ${Day03.part2(input)}") timingStatistics { Day03.part1(input) } timingStatistics { Day03.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,648
advent-of-code
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day08/day8.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day08 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.findInput import biz.koziolek.adventofcode.parse2DMap fun main() { val inputFile = findInput(object {}) val trees = parseTrees(inputFile.bufferedReader().readLines()) println("Trees visible from edges: ${countVisibleTreesFromEdges(trees)}") println("Highest scenic score: ${findHighestScenicScore(trees)}") } fun parseTrees(lines: List<String>): Map<Coord, Int> = lines.parse2DMap { it.toString().toInt() }.toMap() fun countVisibleTreesFromEdges(trees: Map<Coord, Int>) = trees.count { (treeCoord, treeHeight) -> listOf( getNorthTrees(trees, treeCoord), getEastTrees(trees, treeCoord), getSouthTrees(trees, treeCoord), getWestTrees(trees, treeCoord), ).any { otherTrees -> isVisible(treeHeight, otherTrees.map { it.second }) } } fun isVisible(checkedTree: Int, otherTrees: List<Int>) = otherTrees.all { it < checkedTree } fun <T> getNorthTrees(trees: Map<Coord, T>, start: Coord): List<Pair<Coord, T>> = (start.y - 1 downTo 0) .filter { it >= 0 } .map { start.copy(y = it) } .map { it to trees[it]!! } fun <T> getEastTrees(trees: Map<Coord, T>, start: Coord): List<Pair<Coord, T>> = generateSequence(start.x + 1) { it + 1 } .map { start.copy(x = it) } .takeWhile { trees[it] != null } .map { it to trees[it]!! } .toList() fun <T> getSouthTrees(trees: Map<Coord, T>, start: Coord): List<Pair<Coord, T>> = generateSequence(start.y + 1) { it + 1 } .map { start.copy(y = it) } .takeWhile { trees[it] != null } .map { it to trees[it]!! } .toList() fun <T> getWestTrees(trees: Map<Coord, T>, start: Coord): List<Pair<Coord, T>> = (start.x - 1 downTo 0) .filter { it >= 0 } .map { start.copy(x = it) } .map { it to trees[it]!! } fun findHighestScenicScore(trees: Map<Coord, Int>) = trees.maxOf { getScenicScore(trees, it.key) } fun getScenicScore(trees: Map<Coord, Int>, checkedCoord: Coord): Int = listOf( getNorthTrees(trees, checkedCoord), getEastTrees(trees, checkedCoord), getSouthTrees(trees, checkedCoord), getWestTrees(trees, checkedCoord), ) .map { otherTrees -> getViewingDistance(trees[checkedCoord]!!, otherTrees.map { it.second }) } .reduce(Int::times) fun getViewingDistance(checkedTree: Int, otherTrees: List<Int>): Int { val shorterTrees = otherTrees.takeWhile { it < checkedTree }.count() val blockTree = if (shorterTrees < otherTrees.size) 1 else 0 return shorterTrees + blockTree }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,763
advent-of-code
MIT License
src/Day08.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { val day = "Day08" fun part1(input: List<String>): Int { var visible = 0 var forest = input.map { it -> it.toList().map { it.digitToInt() } } // Skip the edges for (i in 1..forest.size - 2) { for (j in 1..forest.size - 2) { var horizontal = forest[i] var vertical = getCol(j, forest) val treesLeft = horizontal.subList(1, j) val treesRight = horizontal.subList(j + 1, horizontal.size - 1) val treesLeftUp = vertical.subList(1, i) val treesRightDown = vertical.subList(i + 1, vertical.size - 1) val edgeLeft = horizontal[0] val edgeRight = horizontal[horizontal.size - 1] val edgeUp = vertical[0] val edgeDown = vertical[horizontal.size - 1] val tree = horizontal[j] val visibleLeft = isTreeVisible(edgeLeft, treesLeft, tree) val visibleRight = isTreeVisible(edgeRight, treesRight, tree) val visibleUp = isTreeVisible(edgeUp, treesLeftUp, tree) val visibleDown = isTreeVisible(edgeDown, treesRightDown, tree) if (visibleLeft || visibleRight || visibleUp || visibleDown) { visible++ } } } // println("visible trees found: $visible") val result = visible + forest.size * 4 - 4 // println("visible trees + perimeter : $result") return result } fun part2(input: List<String>): Int { var maxScore = 0 var forest = input.map { it -> it.toList().map { it.digitToInt() } } // Iterate over all the items for (i in forest.indices) { for (j in forest.indices) { var row = forest[i] var column = getCol(j, forest) val treesLeft = row.subList(0, j) val treesRight = row.subList(j + 1, row.size) val treesLeftUp = column.subList(0, i) val treesRightDown = column.subList(i + 1, column.size) val tree = row[j] val scoreL = calculateScore(treesLeft.reversed(), tree) val scoreR = calculateScore(treesRight, tree) val scoreU = calculateScore(treesLeftUp.reversed(), tree) val scoreD = calculateScore(treesRightDown, tree) var score = scoreL * scoreR * scoreU * scoreD if (score > maxScore) maxScore = score } } // println("score: $maxScore") return maxScore } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("$day") println(part1(input)) println(part2(input)) } private fun isTreeVisible(edge: Int, trees: List<Int>, tree: Int): Boolean { // A tree is visible if all the other trees between it and an edge of the grid are shorter than it var visible = false if (trees.isEmpty() && tree > edge) { visible = true } if (trees.isNotEmpty() && tree > edge) { visible = tree > trees.max() } return visible } private fun getCol(num: Int, input: List<List<Int>>): List<Int> { var r = mutableListOf<Int>() input.forEachIndexed { i, listOfTrees -> r.add(i, listOfTrees[num]) } return r } private fun calculateScore(trees: List<Int>, tree: Int): Int { var score = 0 for (i in trees) { if (i < tree) { score++ } else if (i >= tree){ score++ break } } return score }
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
3,787
advent-of-code-2022
Apache License 2.0
src/Day15.kt
iam-afk
572,941,009
false
{"Kotlin": 33272}
import kotlin.math.absoluteValue import kotlin.math.max fun main() { class Sensor(val x: Int, val y: Int, val bx: Int, val by: Int) { val d = (x - bx).absoluteValue + (y - by).absoluteValue } fun List<String>.sensors() = map { it.split('=', ',', ':') } .map { Sensor(it[1].toInt(), it[3].toInt(), it[5].toInt(), it[7].toInt()) } fun List<Sensor>.rangesAt(y: Int): List<IntRange> = this.map { val x = it.d - (it.y - y).absoluteValue it.x - x..it.x + x }.filterNot(IntRange::isEmpty).sortedBy { it.first } fun part1(input: List<String>, y: Int): Int { var count = 0 var last = Int.MIN_VALUE val sensors = input.sensors() for (range in sensors.rangesAt(y)) { if (last < range.last) { count += range.last - max(range.first, last + 1) + 1 } last = max(last, range.last) } val already = sensors.filter { it.by == y }.map { it.bx }.distinct().count() return count - already } fun part2(input: List<String>, maxY: Int): Long { val sensors = input.sensors() for (y in 0..maxY) { var last = -1 for (range in sensors.rangesAt(y)) { if (last + 1 < range.first) { return (last + 1).toLong() * 4_000_000L + y.toLong() } last = max(last, range.last) } } error("position not found") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input, 4_000_000)) }
0
Kotlin
0
0
b30c48f7941eedd4a820d8e1ee5f83598789667b
1,800
aockt
Apache License 2.0
src/Day03.kt
lukewalker128
573,611,809
false
{"Kotlin": 14077}
fun main() { val testInput = readInput("Day03_test") checkEquals(157, part1(testInput)) checkEquals(70, part2(testInput)) val input = readInput("Day03") println("Part 2: ${part2(input)}") println("Part 1: ${part1(input)}") } /** * Sums the priorities of items appearing in both compartments of each rucksack. */ private fun part1(input: List<String>): Int { return input.map { Rucksack(it) } .sumOf { it.findCommonItem().getPriority() } } private class Rucksack(input: String) { val compartment1: String val compartment2: String init { require(input.length % 2 == 0) compartment1 = input.substring(0 until input.length / 2) compartment2 = input.substring(input.length / 2) } fun findCommonItem(): Char { return compartment1.toSet().intersect(compartment2.toSet()).single() } } // This is split out into separate branches because [code] returns the UTF-16 code and lower and upper case letters do // not occupy a contiguous interval in UTF-16. private fun Char.getPriority() = when { this.isLowerCase() -> this.code - 'a'.code + 1 else -> this.code - 'A'.code + 27 } /** * Sums the priorities of the item types corresponding to the badge of each three-elf group. */ private fun part2(input: List<String>): Int { return input.chunked(3) .map { group -> group[0].toSet() .intersect(group[1].toSet()) .intersect(group[2].toSet()) .single() } .sumOf { it.getPriority() } }
0
Kotlin
0
0
c1aa17de335bd5c2f5f555ecbdf39874c1fb2854
1,567
advent-of-code-2022
Apache License 2.0
src/year_2023/day_12/Day12.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_12 import readInput data class SpringCollection( val pattern: List<Char>, val damageCounts: List<Int> ) object Day12 { private val memory = mutableMapOf<Pair<List<Char>, List<Int>>, Int>() /** * */ fun solutionOne(text: List<String>): Int { return text.sumOf { line -> val springCollection = parseSpring(line) findThem(springCollection.pattern, springCollection.damageCounts) } } /** * */ fun solutionTwo(text: List<String>): Int { return text.sumOf { line -> val springCollection = parseSpring(line) val actualPattern = listOf(springCollection.pattern, listOf('?'), springCollection.pattern, listOf('?'), springCollection.pattern, listOf('?'), springCollection.pattern, listOf('?'), springCollection.pattern).flatten() val actualDamageCounts = listOf(springCollection.damageCounts, springCollection.damageCounts, springCollection.damageCounts, springCollection.damageCounts, springCollection.damageCounts).flatten() findThem(actualPattern.toList(), actualDamageCounts) } } private fun parseSpring(text: String): SpringCollection { val split = text.split(" ") val pattern = split[0] val damagedCounts = split[1].split(",").map { it.toInt() } return SpringCollection(pattern.toList(), damagedCounts) } private fun findThem(pattern: List<Char>, brokenParts: List<Int>): Int { if (pattern.isEmpty()) { return when (brokenParts.size) { 0 -> 1 else -> 0 } } return when (pattern.first()) { '.' -> findThem(pattern.drop(1), brokenParts) '#' -> otherFun(pattern, brokenParts).also { memory[pattern to brokenParts] = it } '?' -> findThem(pattern.drop(1), brokenParts) + otherFun(pattern, brokenParts).also { memory[pattern to brokenParts] = it } else -> throw IllegalArgumentException("whats this? ${pattern.first()}") } } private fun otherFun( pattern: List<Char>, brokenCounts: List<Int> ): Int { memory[pattern to brokenCounts]?.let{ return it } // make sure need to look for broken counts if (brokenCounts.isEmpty()) { return 0 } // make sure there is enough characters val brokenCount = brokenCounts.first() if (pattern.size < brokenCount) { return 0 } // make sure there are enough not known good parts to meet need for (i in 0 until brokenCount) { if (pattern[i] == '.') { return 0 } } if (pattern.size == brokenCount) { return when (brokenCounts.size) { 1 -> 1 else -> 0 } } if (pattern[brokenCount] == '#') { return 0 } return findThem(pattern.drop(brokenCount + 1), brokenCounts.drop(1)) } } fun main() { val text = readInput("year_2023/day_12/Day12.txt") val solutionOne = Day12.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day12.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,332
advent_of_code
Apache License 2.0
src/Day07.kt
rinas-ink
572,920,513
false
{"Kotlin": 14483}
import java.lang.Integer.min fun main() { data class Node( var name: String, var isFile: Boolean, var parent: Node? = null, var size: Int = 0 ) { var children: MutableList<Node> = mutableListOf() } var root = Node("/", false) fun countSize(r: Node): Int { if (!r.isFile) r.size = r.children.sumOf { countSize(it) } return r.size } fun ls(cur: Node, result: List<String>, tmp: MutableList<Node> = mutableListOf()) { if (cur.isFile) throw IllegalArgumentException("Can't apply ls to file") for (r in result) { val (info, name) = r.split(' ') when (info) { "dir" -> cur.children.add(Node(name, false, cur)) else -> cur.children.add(Node(name, true, cur, info.toInt())) } } } fun cd(cur: Node, where: String) = when (where) { "/" -> root ".." -> cur.parent!! else -> cur.children.first { it.name == where && !it.isFile } } fun buildTree(input: List<String>) { root = Node("/", false) var cur = root var start = 0 while (start < input.size) { val cmd = input[start].split(' ').drop(1) var end = start + 1 while (end < input.size && input[end].first() != '$') end++ when (cmd[0]) { "ls" -> ls(cur, input.subList(start + 1, end)) "cd" -> cur = cd(cur, cmd[1]) else -> throw IllegalArgumentException("Only `ls` and `cd` commands are accepted") } start = end } } fun sumDirSizesMostOf(s: Int, r: Node): Int { if (r.isFile) return 0 var res = 0 if (r.size <= s) res += r.size for (c in r.children) res += sumDirSizesMostOf(s, c) return res } fun part1(input: List<String>): Int { buildTree(input) countSize(root) return sumDirSizesMostOf(100000, root) } fun smallestDirGreaterThen(s: Int, r: Node): Int { if (r.isFile || r.size < s) return Int.MAX_VALUE var res = Int.MAX_VALUE for (c in r.children) res = min(res, smallestDirGreaterThen(s, c)) return min(res, r.size) } fun part2(input: List<String>): Int { buildTree(input) countSize(root) return smallestDirGreaterThen(30000000 - (70000000 - root.size), root) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
462bcba7779f7bfc9a109d886af8f722ec14c485
2,709
anvent-kotlin
Apache License 2.0
src/Day02.kt
geodavies
575,035,123
false
{"Kotlin": 13226}
import Outcome.DRAW import Outcome.LOSE import Outcome.WIN import Shape.PAPER import Shape.ROCK import Shape.SCISSORS enum class Shape(private val mappings: List<String>) { ROCK(listOf("A", "X")), PAPER(listOf("B", "Y")), SCISSORS(listOf("C", "Z")); companion object { fun of(input: String): Shape { return values().find { it.mappings.contains(input) }!! } } } enum class Outcome(private val input: String, val score: Int) { LOSE("X", 0), DRAW("Y", 3), WIN("Z", 6); companion object { fun of(input: String): Outcome { return values().find { it.input == input }!! } } } val shapeToScore = mapOf( ROCK to 1, PAPER to 2, SCISSORS to 3, ) val combinations = mapOf( (ROCK to ROCK) to 3, (ROCK to PAPER) to 6, (ROCK to SCISSORS) to 0, (PAPER to ROCK) to 0, (PAPER to PAPER) to 3, (PAPER to SCISSORS) to 6, (SCISSORS to ROCK) to 6, (SCISSORS to PAPER) to 0, (SCISSORS to SCISSORS) to 3, ) val outcomeCombinations = mapOf( (ROCK to LOSE) to SCISSORS, (ROCK to DRAW) to ROCK, (ROCK to WIN) to PAPER, (PAPER to LOSE) to ROCK, (PAPER to DRAW) to PAPER, (PAPER to WIN) to SCISSORS, (SCISSORS to LOSE) to PAPER, (SCISSORS to DRAW) to SCISSORS, (SCISSORS to WIN) to ROCK, ) fun main() { fun part1(input: List<String>) = input.map { val split = it.split(" ") Shape.of(split[0]) to Shape.of(split[1]) }.map { shapeToScore[it.second]!! + combinations[it.first to it.second]!! }.reduce { acc, i -> acc + i } fun part2(input: List<String>) = input.map { val split = it.split(" ") Shape.of(split[0]) to Outcome.of(split[1]) }.map { val myShape = outcomeCombinations[it.first to it.second]!! shapeToScore[myShape]!! + it.second.score }.reduce { acc, i -> acc + i } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d04a336e412ba09a1cf368e2af537d1cf41a2060
2,175
advent-of-code-2022
Apache License 2.0
src/Day09.kt
gsalinaslopez
572,839,981
false
{"Kotlin": 21439}
import kotlin.math.pow import kotlin.math.sqrt enum class Direction(val xDiff: Int, val yDiff: Int) { C(0, 0), R(1, 0), L(-1, 0), U(0, 1), UR(1, 1), UL(-1, 1), D(0, -1), DR(1, -1), DL(-1, -1) } fun main() { fun distance(x1: Int, x2: Int, y1: Int, y2: Int) = sqrt((x2 - x1).toDouble().pow(2) + (y2 - y1).toDouble().pow(2)) fun moveHead(head: IntArray, direction: Direction) { head[0] = head[0] + direction.xDiff head[1] = head[1] + direction.yDiff } fun tailFollow(tail: IntArray, head: IntArray): Set<Pair<Int, Int>> { val visited = mutableSetOf<Pair<Int, Int>>() // shouldn't move if its in the immediate vicinity val shouldMove = Direction.values().all { diff -> tail[0] + diff.xDiff != head[0] || tail[1] + diff.yDiff != head[1] } if (!shouldMove) return visited if (head[0] == tail[0]) { // tail and head on the same col if (head[1] > tail[1]) { tail[1]++ } else { tail[1]-- } } else if (head[1] == tail[1]) { // tail and head on the same row if (head[0] > tail[0]) { tail[0]++ } else { tail[0]-- } } else { // forced to move diagonally val diagonalPositions = Direction.values().filter { it != Direction.C && it != Direction.R && it != Direction.L && it != Direction.U && it != Direction.D }.map { diff -> intArrayOf(tail[0] + diff.xDiff, tail[1] + diff.yDiff) }.minBy { distance(it[0], head[0], it[1], head[1]) } tail[0] = diagonalPositions[0] tail[1] = diagonalPositions[1] } visited.add(Pair(tail[0], tail[1])) return visited } fun simulateRope(input: List<String>, numOfTails: Int): Int { val visited = mutableSetOf(Pair(0, 0)) val nodes = Array(numOfTails + 1) { intArrayOf(0, 0) } input.map { it.split(" ") }.forEach { entry -> val direction = Direction.valueOf(entry[0]) val steps = entry[1].toInt() repeat(steps) { moveHead(nodes.last(), direction) for (i in nodes.size - 2 downTo 0) { val moves = tailFollow(nodes[i], nodes[i + 1]) if (i == 0) { visited.addAll(moves) } } } } return visited.size } // test if implementation meets criteria from the description, like: var testInput = readInput("Day09_test") check(simulateRope(testInput, 1) == 13) testInput = readInput("Day09_test2") check(simulateRope(testInput, 9) == 36) val input = readInput("Day09") println(simulateRope(input, 1)) println(simulateRope(input, 9)) }
0
Kotlin
0
0
041c7c3716bfdfdf4cc89975937fa297ea061830
2,957
aoc-2022-in-kotlin
Apache License 2.0
src/Day02.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
fun main() { fun parseInput(input: String): List<Char> { return input.split(' ').map { it[0] } } fun part1(input: List<String>): Int { val shapeValue = hashMapOf(Pair('X', 1), Pair('Y', 2), Pair('Z', 3)) val wins = hashMapOf(Pair('A', 'Y'), Pair('B', 'Z'), Pair('C', 'X')) return input .map(::parseInput) .sumOf { (first, second) -> val value = shapeValue[second] ?: 0 if (first - 'A' == second - 'X') 3 + value else if (wins[first] == second) 6 + value else value } } fun part2(input: List<String>): Int { val shapeValue = hashMapOf(Pair('A', 1), Pair('B', 2), Pair('C', 3)) val policyValue = hashMapOf(Pair('X', 0), Pair('Y', 3), Pair('Z', 6)) val policy = hashMapOf( Pair('X', hashMapOf(Pair('A', 'C'), Pair('B', 'A'), Pair('C', 'B'))), Pair('Y', hashMapOf(Pair('A', 'A'), Pair('B', 'B'), Pair('C', 'C'))), Pair('Z', hashMapOf(Pair('A', 'B'), Pair('B', 'C'), Pair('C', 'A'))) ) return input .map(::parseInput) .sumOf { (first, move) -> (shapeValue[policy[move]?.get(first) ?: 'A'] ?: 0) + (policyValue[move] ?: 0) } } // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputLines(2) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
1,419
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day13.kt
frango9000
573,098,370
false
{"Kotlin": 73317}
import kotlin.math.max fun main() { val input = readInput("Day13") printTime { println(Day13.part1(input)) } printTime { println(Day13.part2(input)) } } class Day13 { companion object { fun part1(input: List<String>): Int { val packetPairs = input.partitionOnElement("").map { it.map { parsePacket(it.substring(1, it.lastIndex)) } } val packetComparisons: List<Int> = packetPairs.map { (first, second) -> comparePackets(first, second) } return packetComparisons.withIndex().filter { it.value <= 0 }.sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val packet2 = parsePacket("[2]") val packet6 = parsePacket("[6]") val packets = input.filter { it != "" } .map { parsePacket(it.substring(1, it.lastIndex)) }.toMutableList().apply { add(packet2); add(packet6) } val sortedPackets = packets.sortedWith { p0, p1 -> comparePackets(p0, p1) } return sortedPackets.withIndex() .filter { comparePackets(packet2, it.value) == 0 || comparePackets(packet6, it.value) == 0 } .map { it.index + 1 }.product() } private fun comparePackets(first: Any, second: Any): Int { if (first is List<*> && second is List<*>) { for (index in 0..max(first.lastIndex, second.lastIndex)) { if (first.lastIndex < index) return -1 if (second.lastIndex < index) return 1 val packetComparison = comparePackets(first[index]!!, second[index]!!) if (packetComparison == 0) continue else return packetComparison } return 0 } if (first is List<*>) return comparePackets(first, listOf(second)) if (second is List<*>) return comparePackets(listOf(first), second) return (first as Int) - (second as Int) } private fun parsePacket(substring: String): List<Any> { val root = mutableListOf<Any>() val stack: ArrayDeque<MutableList<Any>> = ArrayDeque() stack.add(root) var index = 0 while (index < substring.length) { when (substring[index]) { '[' -> { val newStack = mutableListOf<Any>() stack.last().add(newStack) stack.addLast(newStack) index++ } ']' -> { stack.removeLast() index++ } ',' -> index++ else -> { val fromNumber = substring.substring(index) var indexOfNextClose = fromNumber.indexOfFirst { it == ']' || it == ',' } if (indexOfNextClose < 0) indexOfNextClose = fromNumber.length val number = fromNumber.substring(0, indexOfNextClose).toInt() stack.last().add(number) index += indexOfNextClose } } } return root } } }
0
Kotlin
0
0
62e91dd429554853564484d93575b607a2d137a3
3,287
advent-of-code-22
Apache License 2.0
src/Day16.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
fun main() { val day16 = Day16(readInput("inputs/Day16")) println(day16.part1()) println(day16.part2()) } class Day16(input: List<String>) { private val valves = input.map(Valve::from).associateBy(Valve::name) private val usefulValves = valves.filter { it.value.rate > 0 } private val distances = computeDistances() fun part1() = traverse(minutes = 30) fun part2() = traverse(minutes = 26, elephantGoesNext = true) private fun traverse( minutes: Int, current: Valve = valves.getValue("AA"), remaining: Set<Valve> = usefulValves.values.toSet(), cache: MutableMap<State, Int> = mutableMapOf(), elephantGoesNext: Boolean = false ): Int { val currentScore = minutes * current.rate val currentState = State(current.name, minutes, remaining) return currentScore + cache.getOrPut(currentState) { val validValves = remaining.filter { next -> distances[current.name]!![next.name]!! < minutes } var maxCurrent = 0 if (validValves.isNotEmpty()) { maxCurrent = validValves.maxOf { next -> val remainingMinutes = minutes - 1 - distances[current.name]!![next.name]!! traverse(remainingMinutes, next, remaining - next, cache, elephantGoesNext) } } maxOf(maxCurrent, if (elephantGoesNext) traverse(minutes = 26, remaining = remaining) else 0) } } private fun computeDistances(): Map<String, Map<String, Int>> { return valves.keys.map { valve -> val distances = mutableMapOf<String, Int>().withDefault { Int.MAX_VALUE }.apply { put(valve, 0) } val toVisit = mutableListOf(valve) while (toVisit.isNotEmpty()) { val current = toVisit.removeFirst() valves[current]!!.next.forEach { adj -> val newDistance = distances[current]!! + 1 if (newDistance < distances.getValue(adj)) { distances[adj] = newDistance toVisit.add(adj) } } } distances }.associateBy { it.keys.first() } } private data class State(val current: String, val minutes: Int, val opened: Set<Valve>) private data class Valve(val name: String, val rate: Int, val next: List<String>) { companion object { fun from(line: String): Valve { return Valve( name = line.substringAfter("Valve ").substringBefore(" "), rate = line.substringAfter("rate=").substringBefore(";").toInt(), next = line.substringAfter("to valve").substringAfter(" ").split(", ") ) } } } }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
2,840
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2020/AllergenAssessment.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.nonEmptyLines fun allergenAssessment1(input: String): Int { val foods = input.nonEmptyLines().map { Food.parse(it) } val ingredientsWithAllergens = ingredientsByAllergens(foods).flatMap { it.value } val safe = foods.flatMap { it.ingredients }.toSet() - ingredientsWithAllergens return foods.sumBy { food -> food.ingredients.count { it in safe } } } fun allergenAssessment2(input: String): String { val foods = input.nonEmptyLines().map { Food.parse(it) } val ingredientsByAllergens = ingredientsByAllergens(foods).mapValues { it.value.toMutableSet() }.toMutableMap() val result = sortedMapOf<String, String>() while (true) { val (allergen, ingredients) = ingredientsByAllergens.entries.find { it.value.size == 1 } ?: break val ingredient = ingredients.single() ingredientsByAllergens.remove(allergen) for (allergens in ingredientsByAllergens.values) allergens.remove(ingredient) result[allergen] = ingredient } return result.values.joinToString(",") } private fun ingredientsByAllergens(foods: List<Food>): Map<String, Set<String>> { val ingredients = foods.flatMap { it.ingredients }.toSet() val allergens = foods.flatMap { it.allergens }.toSet() val candidateAllergens = allergens.associateWith { ingredients.toMutableSet() } for (food in foods) for (allergen in food.allergens) candidateAllergens[allergen]?.retainAll(food.ingredients) return candidateAllergens } private data class Food(val ingredients: Set<String>, val allergens: Set<String>) { companion object { private val regex = Regex("""(.+) \(contains (.+)\)""") fun parse(s: String): Food { val (_, ingredients, allergens) = regex.matchEntire(s)?.groupValues ?: error("invalid line '$s'") return Food(ingredients.split(' ').toSet(), allergens.split(Regex(", ")).toSet()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,012
advent-of-code
MIT License
advent-of-code-2023/src/main/kotlin/Day07.kt
jomartigcal
433,713,130
false
{"Kotlin": 72459}
// Day 07: Camel Cards // https://adventofcode.com/2023/day/7 import java.io.File data class Card(val char: Char) fun Card.getValue(hasJoker: Boolean): Int { return when { char.isDigit() -> char.digitToInt() char == 'T' -> 10 char == 'J' && hasJoker.not() -> 11 char == 'J' && hasJoker -> 0 char == 'Q' -> 12 char == 'K' -> 13 char == 'A' -> 14 else -> 0 } } private val JOKER = Card('J') data class Hand(val cards: List<Card>, val bid: Int) { fun getRank(hasJoker: Boolean): Int { var cardsForRanking = cards.toMutableList() if (hasJoker && cards.contains(JOKER)) { if (cards.distinct().size != 5) { val idealCard = if (cards.count { it == JOKER } >= 3 && cards.distinct().size == 2 ) { cards.find { it != JOKER } } else if (cards.count { it == JOKER } == 5) { Card('A') } else { cardsForRanking.filterNot { it == JOKER } .groupingBy { it }.eachCount() .maxByOrNull { it.value }?.key } if (idealCard != null) { cardsForRanking = cards.map { if (it == JOKER) idealCard else it }.toMutableList() } } else { val idealCard = cards.maxByOrNull { it.getValue(true) } if (idealCard != null) { cardsForRanking = cards.map { if (it == JOKER) idealCard else it }.toMutableList() } } } return if (cardsForRanking.distinct().size == 1) { 6 // Five of a kinad } else if ( cardsForRanking.distinct().size == 2 && cardsForRanking.groupingBy { it }.eachCount().values.max() == 4 ) { 5 // Four of a kind } else if (cardsForRanking.distinct().size == 2) { 4 // Full House } else if (cardsForRanking.distinct().size == 3 && cardsForRanking.groupingBy { it }.eachCount().values.max() == 3 ) { 3 // Three of a kind } else if (cardsForRanking.distinct().size == 3) { 2 // Two pair } else if (cardsForRanking.distinct().size == 4) { 1 // One pair } else { 0 // High card } } } fun main() { val lines = File("src/main/resources/Day07.txt").readLines() val hands = lines.map { hand -> val (cards, bid) = hand.split(" ") Hand( cards.toList().map { card -> Card(card) }, bid.toInt() ) } println(getTotalWinnings(hands.toList(), hasJoker = false)) println(getTotalWinnings(hands.toList(), hasJoker = true)) } private fun getTotalWinnings(hands: List<Hand>, hasJoker: Boolean) = hands.sortedWith( compareBy<Hand> { it.getRank(hasJoker) } .thenBy { it.cards[0].getValue(hasJoker) } .thenBy { it.cards[1].getValue(hasJoker) } .thenBy { it.cards[2].getValue(hasJoker) } .thenBy { it.cards[3].getValue(hasJoker) } .thenBy { it.cards[4].getValue(hasJoker) } ).mapIndexed { index, hand -> hand.bid * (index + 1) }.sum()
0
Kotlin
0
0
6b0c4e61dc9df388383a894f5942c0b1fe41813f
3,426
advent-of-code
Apache License 2.0
src/2022/Day15.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput import kotlin.math.abs fun main() { fun findDistressedBeacon(sensorToDistance: List<Day15Input>, maxSize: Int): YPoint { (0..maxSize).forEach { y -> val ranges = sensorToDistance.toReverseRanges(y, maxSize) if (ranges.isNotEmpty()) { return ranges.first().start } } error("Can't find distressed beacon") } fun readInput(input: List<String>): List<Day15Input> { val sensorToDistance = input.map { s -> val (sensor, beacon) = "(x=|y=)(-?\\d+)" .toRegex().findAll(s) .map { it.groups[2]!!.value.toInt() } .chunked(2) .map { (x, y) -> YPoint(x, y) } .toList() val distance = sensor.dist(beacon) Day15Input(sensor, distance, beacon) } return sensorToDistance } fun part1(input: List<String>, row: Int): Int { val sensorToBeacon = readInput(input) val sensors = sensorToBeacon.map { it.sensor }.toSet() val beacons = sensorToBeacon.map { it.beacon }.toSet() val ranges = sensorToBeacon.toRanges(row) val minX = ranges.map { it.start.x }.min() val maxX = ranges.map { it.endInclusive.x }.max() return (minX..maxX).asSequence().filter { x -> val point = YPoint(x, row) !sensors.contains(point) && !beacons.contains(point) }.count() } fun part2(input: List<String>, maxSize: Int): Long { val sensorToDistance = readInput(input) val (x, y) = findDistressedBeacon(sensorToDistance, maxSize) return x * 4000000L + y } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") println(part1(testInput, 10)) println(part2(testInput, 20)) check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) } private fun YPoint.dist(other: YPoint): Int { return abs(x - other.x) + abs(y - other.y) } private data class Day15Input(val sensor: YPoint, val distance: Int, val beacon: YPoint) private data class YPoint(val x: Int, val y: Int): Comparable<YPoint> { override fun compareTo(other: YPoint): Int { return x - other.x } } private fun YPoint.prev(): YPoint { return YPoint(x - 1, y) } private fun YPoint.next(): YPoint { return YPoint(x + 1, y) } private fun List<Day15Input>.toRanges(row: Int): List<ClosedRange<YPoint>> { return mapNotNull { (sensor, distance) -> val delta = distance - abs(sensor.y - row) if (delta >= 0) { YPoint(sensor.x - delta, row)..YPoint(sensor.x + delta, row ) } else { null } } } private fun List<Day15Input>.toReverseRanges(row: Int, maxSize: Int): List<ClosedRange<YPoint>> { val ranges = toRanges(row) return ranges.fold(listOf(YPoint(0, row)..YPoint(maxSize, row))) { acc, range -> acc.subtract(range) } } private fun List<ClosedRange<YPoint>>.subtract(range: ClosedRange<YPoint>): List<ClosedRange<YPoint>> { return filter { !(range.contains(it.start) && range.contains(it.endInclusive)) }.flatMap { if (range.contains(it.start)) { listOf(range.endInclusive.next()..it.endInclusive) } else if (range.contains(it.endInclusive)) { listOf(it.start..range.start.prev()) } else if (it.contains(range.start)) { listOf( it.start..range.start.prev(), range.endInclusive.next()..it.endInclusive ) } else { listOf(it) } } }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
3,799
aoc-2022-in-kotlin
Apache License 2.0
src/Day09.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
import kotlin.math.abs fun main() { fun _process(input: List<String>, noOfKnots: Int): Int { val visited = mutableSetOf<Pair<Int, Int>>() visited.add(Pair(0, 0)) val knots = mutableListOf<Pair<Int, Int>>() (0..noOfKnots).forEach { _ -> knots.add(Pair(0, 0)) } input.forEachIndexed { cmdIdx, line -> val regex = "(.) (\\d+)".toRegex() val (cmd, value) = regex.find(line)!!.destructured.toList() (1..value.toInt()).forEach { step -> when (cmd) { "U" -> knots[0] = Pair(knots[0].first + 1, knots[0].second) "D" -> knots[0] = Pair(knots[0].first - 1, knots[0].second) "L" -> knots[0] = Pair(knots[0].first, knots[0].second - 1) "R" -> knots[0] = Pair(knots[0].first, knots[0].second + 1) } (1..noOfKnots).forEach { i -> var r = knots[i].first var c = knots[i].second if ((abs(knots[i - 1].first - knots[i].first) > 1 || abs(knots[i - 1].second - knots[i].second) > 1) && (knots[i - 1].first != knots[i].first && knots[i - 1].second != knots[i].second) ) { r += (knots[i - 1].first - knots[i].first) / abs(knots[i - 1].first - knots[i].first) c += (knots[i - 1].second - knots[i].second) / abs(knots[i - 1].second - knots[i].second) } else if (abs(knots[i - 1].first - knots[i].first) > 1) { r += (knots[i - 1].first - knots[i].first) / abs(knots[i - 1].first - knots[i].first) } else if (abs(knots[i - 1].second - knots[i].second) > 1) { c += (knots[i - 1].second - knots[i].second) / abs(knots[i - 1].second - knots[i].second) } knots[i] = Pair(r, c) } visited.add(knots[noOfKnots]) } } return visited.size } fun part1(input: List<String>): Int { return _process(input, 1) } fun part2(input: List<String>): Int { return _process(input, 9) } // test if implementation meets criteria from the description, like: val testInputPart1 = readInput("Day09_part1_test") val testInputPart2 = readInput("Day09_part2_test") check(part1(testInputPart1) == 13) check(part2(testInputPart2) == 36) val input = readInput("Day09") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
2,581
advent-of-code-2022-kotlin
Apache License 2.0
src/Day07.kt
seana-zr
725,858,211
false
{"Kotlin": 28265}
const val JOKER = true enum class HandType { HIGH, ONE_PAIR, TWO_PAIR, THREE, FULL, FOUR, FIVE; } fun String.distinct() = toSet().size fun String.frequencies() = groupingBy { it }.eachCount() fun String.getHandType(): HandType { return when (distinct()) { 1 -> HandType.FIVE 2 -> { val firstCardCount = count { it == this.first() } if (firstCardCount == 2 || firstCardCount == 3) { HandType.FULL } else { HandType.FOUR } } 3 -> { val frequencies = frequencies() if (frequencies.any { it.value == 3 }) { HandType.THREE } else { HandType.TWO_PAIR } } 4 -> HandType.ONE_PAIR 5 -> HandType.HIGH else -> throw IllegalStateException() } } fun String.jokerHand(): String { // edge case: most frequent card is J val frequencies = frequencies().filter { it.key != 'J' } // edge case: JJJJJ if (frequencies.isEmpty()) return "11111" val highestFrequency = frequencies.values.max() val mostFrequentCard = first { frequencies[it] == highestFrequency } return replace('J', mostFrequentCard) } // turn the jokers into whatever card has the highest frequency fun String.getHandTypeWithJoker(): HandType { return jokerHand().getHandType() } enum class Card(val n: Int) { A(14), K(13), Q(12), J(if (JOKER) 1 else 11), T(10) } fun Char.cardValue(): Int { val asString = this.toString() return if (Card.entries.any { it.name == asString }) Card.valueOf(asString).n else this.digitToInt() } data class Player( val hand: String, val bid: Int ) : Comparable<Player> { override fun compareTo(other: Player): Int { hand.zip(other.hand).forEach { (our, other) -> val difference = our.cardValue() - other.cardValue() if (difference != 0) return difference } return 0 } } fun main() { fun part1(input: List<String>): Int { var result = 0 // the rank of each player is their (index + 1) val players = input .map { val (hand, bid) = it.split(" ") Player(hand = hand, bid = bid.toInt()) } .sortedWith( compareBy({ it.hand.getHandType() }, { it }) ) players.forEachIndexed { index, player -> val rank = index + 1 val score = player.bid * rank println("${player.hand} ${player.bid} rank $rank score $score ${player.hand.getHandType()}") result += score } println("RESULT: $result") return result } fun part2(input: List<String>): Long { var result = 0.toLong() val players = input .map { val (hand, bid) = it.split(" ") Player(hand = hand, bid = bid.toInt()) } .sortedWith( compareBy({ it.hand.getHandTypeWithJoker() }, { it }) ) players.forEachIndexed { index, player -> val rank = index + 1 val score = player.bid * rank println("${player.hand} ${player.bid} rank $rank hand ${player.hand.jokerHand()} ${player.hand.getHandTypeWithJoker()}") result += score } println("RESULT: $result") return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test_2") // check(part1(testInput) == 6440) check(part2(testInput) == 6839.toLong()) val input = readInput("Day07") // part1(input).println() part2(input).println() }
0
Kotlin
0
0
da17a5de6e782e06accd3a3cbeeeeb4f1844e427
3,740
advent-of-code-kotlin-template
Apache License 2.0
src/Day15.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
import kotlin.math.abs fun Coordinate.manhattanDistanceTo(other: Coordinate) = abs(x - other.x) + abs(y - other.y) data class Sensor( val location: Coordinate, val closestBeacon: Coordinate, val distanceToBeacon: Int = location.manhattanDistanceTo(closestBeacon) ) fun main() { fun readSensors(input: List<String>): List<Sensor> { val re = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() return input.mapNotNull { re.matchEntire(it) } .map { Sensor( Coordinate(it.groupValues[1].toInt(), it.groupValues[2].toInt()), Coordinate(it.groupValues[3].toInt(), it.groupValues[4].toInt()), ) } } fun part1(input: List<String>, y: Int): Int { val sensors = readSensors(input) check(sensors.size == input.size) val minX = sensors.minOf { minOf(it.location.x - it.distanceToBeacon, it.closestBeacon.x) } val maxX = sensors.maxOf { maxOf(it.location.x + it.distanceToBeacon, it.closestBeacon.x) } return (minX..maxX) .map { x -> Coordinate(x, y) } .count { coord -> sensors.any { sensor -> coord != sensor.closestBeacon && coord.manhattanDistanceTo(sensor.location) <= sensor.distanceToBeacon } } } fun part2(input: List<String>, maxCoordinate: Int): Long { val sensors = readSensors(input) check(sensors.size == input.size) for (x in 0..maxCoordinate) { var y = 0 while (y <= maxCoordinate) { val coord = Coordinate(x, y) val furthestSensor = sensors.filter { sensor -> coord.manhattanDistanceTo(sensor.location) <= sensor.distanceToBeacon }.maxByOrNull { sensor -> sensor.distanceToBeacon - abs(sensor.location.x - x) } ?: return 4000000L * x + y y = furthestSensor.location.y + furthestSensor.distanceToBeacon - abs(furthestSensor.location.x - x) + 1 } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") check(part1(input, 2000000) == 4879972) val answer2 = part2(input, 4000000) check(answer2 > 1602012312L) println(answer2) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
2,678
advent-of-code-2022
Apache License 2.0
src/Day07.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
private sealed interface FileSystemObject { val name: String val parent: Directory val size: Int } private sealed interface Directory : FileSystemObject { val children: MutableList<FileSystemObject> fun getChild(name: String): FileSystemObject } private class File (override val name: String, override val parent: Directory, override val size: Int) : FileSystemObject private class DirectoryImpl(override val name: String, parent: Directory?): Directory { override val parent: Directory = parent ?: this override val children: MutableList<FileSystemObject> = mutableListOf() override val size: Int get() = children.sumOf { it.size } override fun getChild(name: String): FileSystemObject = children.single { it.name == name } } fun main() { fun readFileSystem(input: List<String>): Directory { val root = DirectoryImpl("/", null) var currentDirectory: Directory = root for (line in input.drop(1)) { when { line.startsWith("$ cd") -> { val dirName = line.split(' ').last() currentDirectory = if (dirName == "..") { currentDirectory.parent } else { currentDirectory.getChild(dirName) as Directory } } line.startsWith("dir") -> { val dirName = line.split(' ').last() currentDirectory.children.add(DirectoryImpl(dirName, currentDirectory)) } line.contains(Regex("""^\d+""")) -> { val (size, name) = line.split(' ') currentDirectory.children.add(File(name, currentDirectory, size.toInt())) } } } return root } fun sumDirectorySizes(root: Directory, maxSize: Int): Int { val childrenSize = root.children.filterIsInstance<Directory>().sumOf { sumDirectorySizes(it, maxSize) } val size = root.size return childrenSize + if (size > maxSize) 0 else size } fun findSmallestDirectory(root: Directory, minSize: Int): Directory? { val size = root.size if (size < minSize) return null val smallestChild = root.children.filterIsInstance<Directory>().mapNotNull { findSmallestDirectory(it, minSize) }.minByOrNull { it.size } return smallestChild ?: root } fun part1(input: List<String>): Int { val tree = readFileSystem(input) return sumDirectorySizes(tree, 100000) } fun part2(input: List<String>): Int { val tree = readFileSystem(input) val maxSpace = 70000000 val neededSpace = 30000000 val availableSpace = maxSpace - tree.size val spaceToFree = neededSpace - availableSpace return findSmallestDirectory(tree, spaceToFree)!!.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
afbcec6a05b8df34ebd8543ac04394baa10216f0
3,184
advent-of-code-22
Apache License 2.0
src/main/kotlin/Day5.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import java.lang.Long.min import kotlin.String import kotlin.collections.List object Day5 { data class Range(val start: Long, val end: Long) data class RangeMapping(val destinationRangeStart: Long, val sourceRangeStart: Long, val rangeLength: Long) { fun next(id: Long): Long { return if (sourceRangeStart <= id && id <= sourceRangeStart + rangeLength) { val offset = id - sourceRangeStart destinationRangeStart + offset } else { id } } fun next(range: Range): Range { val offset = range.start - sourceRangeStart return Range(destinationRangeStart + offset, destinationRangeStart + offset + range.end - range.start) } fun overlaps(id: Long): Boolean { return sourceRangeStart <= id && id < sourceRangeStart + rangeLength } fun overlaps(range: Range): Boolean { return sourceRangeStart <= range.start && range.end <= sourceRangeStart + rangeLength - 1 } } data class Mapping( val category: String, val rangeMappings: List<RangeMapping> ) { fun fork(range: Range): List<Range> { if (rangeMappings.any { it.overlaps(range) }) { return listOf(range) } var start = range.start val end = range.end val ranges = mutableListOf<Range>() while (start <= end) { val closestWithoutGoingOver = rangeMappings.filter { it.sourceRangeStart <= start && start < it.sourceRangeStart + it.rangeLength } .minByOrNull { it.sourceRangeStart - range.start } if (closestWithoutGoingOver != null) { val newEnd = min(end, closestWithoutGoingOver.sourceRangeStart + closestWithoutGoingOver.rangeLength - 1) ranges.add(Range(start, newEnd)) start = newEnd + 1 } else { val closestWithGoingOver = rangeMappings.filter { it.sourceRangeStart + it.rangeLength > start } .minByOrNull { it.sourceRangeStart - start } if (closestWithGoingOver == null) { ranges.add(Range(start, end)) start = end + 1 } else { val newEnd = min(end, closestWithGoingOver.sourceRangeStart - 1) ranges.add(Range(start, newEnd)) start = newEnd + 1 } } } return ranges } companion object { fun parseMappings(input: List<String>): List<Mapping> { var remainingInput = input val mappings = mutableListOf<Mapping>() while (remainingInput.isNotEmpty()) { val category = remainingInput.first().split(" ").first() val ranges = remainingInput.drop(1).takeWhile { it.isNotEmpty() }.map { val (destinationRangeStart, sourceRangeStart, rangeLength) = it.split(" ") RangeMapping( destinationRangeStart.toLong(), sourceRangeStart.toLong(), rangeLength.toLong() ) } mappings.add(Mapping(category, ranges)) remainingInput = remainingInput.drop(ranges.size + 2) } return mappings } } } fun part1(input: List<String>): String { val seeds = input.first().replace("seeds: ", "") .split(" ") .map { it.toLong() } val mappings = Mapping.parseMappings(input.drop(2)) val finalMappings = mappings.fold(seeds) { acc, mapping -> acc.map { id -> val range = mapping.rangeMappings.find { it.overlaps(id) } range?.next(id) ?: id } } return finalMappings.min().toString() } fun part2(input: List<String>): String { val ranges = input.first().replace("seeds: ", "") .split(" ") .map { it.toLong() } .chunked(2) .map { Range(it.first(), it.first() + it.last()) } val mappings = Mapping.parseMappings(input.drop(2)) val finalRanges = mappings.fold(ranges) { transformedRanges, mapping -> transformedRanges.flatMap { range -> val nextRanges = mapping.fork(range).map { forkedRange -> val overlaps = mapping.rangeMappings.filter { it.overlaps(forkedRange) } .minByOrNull { it.sourceRangeStart - forkedRange.start } overlaps?.next(forkedRange) ?: forkedRange } nextRanges } } return finalRanges.minBy { it.start }.start.toString() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
5,096
kotlin-kringle
Apache License 2.0
src/Day15.kt
6234456
572,616,769
false
{"Kotlin": 39979}
import kotlin.math.abs fun main() { fun merge(list: List<Pair<Int, Int>>):List<Pair<Int, Int>>{ if (list.isEmpty()) return emptyList() var ans:MutableList<Pair<Int, Int>> = mutableListOf(list.first()) list.drop(1).forEach { val last = ans.last() if (it.first > last.second){ ans.add(it) }else{ ans = ans.dropLast(1).toMutableList() ans.add(last.first to kotlin.math.max(last.second, it.second)) } } return ans } fun merge(list: List<Pair<Int, Int>>, y: Int, ma: Int):Long{ val sums: (Int, Int) -> Long = { x0, x1 -> (x0 .. x1.toLong()).sum() * 4000000 + y * (x1 + 1 - x0)} if (list.isEmpty()) return sums(0, ma) var ans:MutableList<Pair<Int, Int>> = mutableListOf(list.first()) list.drop(1).forEach { val last = ans.last() if (it.first > last.second){ ans.add(it) }else{ ans = ans.dropLast(1).toMutableList() ans.add(last.first to kotlin.math.max(last.second, it.second)) } } var cnt = 0 var answer = 0L while (cnt <= ma){ if (ans.isEmpty()){ answer += sums(cnt, ma) return answer } val f = ans.first() if (cnt < f.first){ answer += sums(cnt, f.first - 1) cnt = f.second + 1 }else if (f.second >= cnt){ cnt = f.second + 1 } ans = ans.drop(1).toMutableList() } return answer } fun part1(input: List<String>, y:Int=10): Int { val digits = """(-?\d+)""".toRegex() val p = input.map { val arr = digits.findAll(it).toList().map { it.value.toInt() } val vertical = abs(arr[1] - y) val distance = abs(arr[1] - arr[3]) + abs(arr[0] - arr[2]) if(distance >= vertical){ (arr[0] - distance + vertical) to (arr[0] + distance - vertical) }else null }.filterNotNull().sortedBy { it.first } return merge(p).map { it.second - it.first }.sum() } fun part2(input: List<String>, ma:Int = 20, mi:Int = 0): Long{ val digits = """(-?\d+)""".toRegex() val p = input.map { digits.findAll(it).toList().map { it.value.toInt() } } var y = mi var ans:Long = 0 while (y <= ma){ val tmp = p.map { arr -> val vertical = abs(arr[1] - y) val distance = abs(arr[1] - arr[3]) + abs(arr[0] - arr[2]) if(distance >= vertical){ (arr[0] - distance + vertical) to (arr[0] + distance - vertical) }else null }.filterNotNull().sortedBy { it.first } ans += merge(tmp, y, ma) y++ } return ans } var input = readInput("Test15") println(part1(input)) println(part2(input)) input = readInput("Day15") println(part1(input, y=2000000)) println(part2(input, ma=4000000)) }
0
Kotlin
0
0
b6d683e0900ab2136537089e2392b96905652c4e
3,270
advent-of-code-kotlin-2022
Apache License 2.0
lib/src/main/kotlin/com/bloidonia/advent/day08/Day08.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day08 import com.bloidonia.advent.readList data class Digit(val wires: Set<Char>) { private fun intersections(vararg other: Digit) = other.map { wires.intersect(it.wires).size }.toList() fun matches(expectedSegmentCount: Int, known: Array<Digit>, overlapWith1: Int, overlapWith4: Int) = !known.contains(this) && this.wires.size == expectedSegmentCount && intersections(known[1], known[4]) == listOf(overlapWith1, overlapWith4) } data class Line(val digits: List<Digit>, val display: List<Digit>) { fun numberKnown(): Int = display.count { it.wires.size in listOf(2, 3, 4, 7) } fun derive(): String { val resolved = Array(10) { Digit(setOf()) } resolved[1] = digits.first { it.wires.size == 2 } resolved[4] = digits.first { it.wires.size == 4 } resolved[7] = digits.first { it.wires.size == 3 } resolved[8] = digits.first { it.wires.size == 7 } resolved[2] = digits.first { it.matches(5, resolved, 1, 2) } resolved[3] = digits.first { it.matches(5, resolved, 2, 3) } resolved[5] = digits.first { it.matches(5, resolved, 1, 3) } resolved[0] = digits.first { it.matches(6, resolved, 2, 3) } resolved[6] = digits.first { it.matches(6, resolved, 1, 3) } resolved[9] = digits.first { it.matches(6, resolved, 2, 4) } return display.joinToString(separator = "") { resolved.indexOf(it).toString() } } } fun String.toDigit() = Digit(this.toCharArray().toSet()) fun String.toLine(): Line = this.split("|", limit = 2).let { (lhs, rhs) -> Line( lhs.trim().split(" ").map { it.toDigit() }.toList(), rhs.trim().split(" ").map { it.toDigit() }.toList() ) } fun main() { // Part 1 println(readList("/day08input.txt") { it.toLine() }.sumOf { it.numberKnown() }) // Part 2 println(readList("/day08input.txt") { it.toLine() }.sumOf { it.derive().toLong() }) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,969
advent-of-kotlin-2021
MIT License
src/Day11.kt
proggler23
573,129,757
false
{"Kotlin": 27990}
fun main() { fun part1(input: List<String>): Long { val monkeys = parse11(input) repeat(20) { monkeys.forEach { it.takeTurn(monkeys) } } return monkeys.sortedByDescending { it.inspections }.take(2).productOfLong { it.inspections } } fun part2(input: List<String>): Long { val monkeys = parse11(input) repeat(10000) { monkeys.forEach { it.takeTurn(monkeys, false) } } return monkeys.sortedByDescending { it.inspections }.take(2).productOfLong { it.inspections } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) } fun parse11(lines: List<String>): List<Monkey> { val operationRegex = Regex("new = old (.) (\\d+|old)") var i = 0 return buildList { while (++i < lines.size) { val startingItems = lines[i++].substringAfter("Starting items: ").split(", ").map { it.toLong() } val operation = operationRegex.find(lines[i++])!!.let { val v = it.groupValues[2].toLongOrNull() if (it.groupValues[1] == "*") { item: Long -> item * (v ?: item) } else { item: Long -> item + (v ?: item) } } val divisableBy = lines[i++].substringAfter("divisible by ").toInt() val positiveThrow = lines[i++].substringAfter("throw to monkey ").toInt() val negativeThrow = lines[i++].substringAfter("throw to monkey ").toInt() val test = { item: Long -> if (item.mod(divisableBy) == 0) positiveThrow else negativeThrow } add(Monkey(startingItems, operation, test, divisableBy)) i++ } } } fun <T> List<T>.productOfLong(transform: (T) -> Long) = fold(1L) { acc, t -> acc * transform(t) } class Monkey( startingItems: List<Long>, private val operation: (Long) -> Long, private val test: (Long) -> Int, private val divisor: Int ) { private val items = startingItems.toMutableList() var inspections = 0L fun takeTurn(monkeys: List<Monkey>, relief: Boolean = true) { while (items.isNotEmpty()) { inspections++ var item = items.removeFirst() item = operation(item) if (relief) item /= 3 else item = item.mod(monkeys.productOfLong { it.divisor.toLong() }) monkeys[test(item)].items += item } } }
0
Kotlin
0
0
584fa4d73f8589bc17ef56c8e1864d64a23483c8
2,613
advent-of-code-2022
Apache License 2.0
src/day18/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day18 import day06.main import readInput fun main() { data class Cube(val x: Int, val y: Int, val z: Int) { fun dimension(i: Int) = when (i % 3) { 0 -> x 1 -> y else -> z } fun adjacent() = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1), ) } fun parse(input: List<String>) = input.map { it.split(",").map(String::toInt).let { (x, y, z) -> Cube(x, y, z) } }.toSet() fun Cube.extractOtherDimension(dimension: Int) = Pair(dimension(dimension + 1), dimension(dimension + 2)) fun Set<Cube>.adjacentFaces(dimension: Int) = groupBy { it.dimension(dimension) }.let { List(it.keys.max() + 1) { i -> it[i] ?: emptyList() } }.zipWithNext() .sumOf { (prev, next) -> prev.map { cube -> cube.extractOtherDimension(dimension) } .intersect(next.map { cube -> cube.extractOtherDimension(dimension) }.toSet()).count() } fun part1(cubes: Set<Cube>) = 6 * cubes.size - 2 * (cubes.adjacentFaces(0) + cubes.adjacentFaces(1) + cubes.adjacentFaces(2)) fun part2(input: Set<Cube>) = with(mutableSetOf<Cube>()) { val xRange = (input.minOf { it.x } - 1)..(input.maxOf { it.x } + 1) val yRange = (input.minOf { it.y } - 1)..(input.maxOf { it.y } + 1) val zRange = (input.minOf { it.z } - 1)..(input.maxOf { it.z } + 1) generateSequence( Cube(xRange.first, yRange.first, zRange.first).adjacent() ) { frontier -> frontier.filter { cube -> cube.x in xRange && cube.y in yRange && cube.z in zRange && cube !in this && cube !in input }.takeIf(List<Cube>::isNotEmpty)?.let { validCubes -> if (addAll(validCubes)) { validCubes.flatMap { it.adjacent() }.toSet() } else null } }.last().let { sumOf { external -> external.adjacent().count { it in input } } } } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
2,284
AOC2022
Apache License 2.0
src/day02/Day02.kt
emartynov
572,129,354
false
{"Kotlin": 11347}
package day02 import readInput /* A,X - Rock B,Y - Paper C,Z - Scissors Rock -> Scissors Scissors -> Paper Paper -> Rock */ enum class Variants { Rock, Paper, Scissors } val mapping = mapOf( 'A' to Variants.Rock, 'X' to Variants.Rock, 'B' to Variants.Paper, 'Y' to Variants.Paper, 'C' to Variants.Scissors, 'Z' to Variants.Scissors, ) fun Variants.value() = ordinal + 1 infix fun Variants.test(other: Variants): Int { return when (ordinal - other.ordinal) { 0 -> 3 // same 1 -> 6 // every wins over predecessor -2 -> 6 // rock wins scissors else -> 0 // lost } } infix fun Variants.score(other: Variants) = value() + (this test other) fun Variants.selectVariant(strategy: Char): Variants { return if (strategy == 'Y') this //draw else { // lose val selectVariantOrdinal = if (strategy == 'X') ordinal - 1 else ordinal + 1 if (selectVariantOrdinal < 0) Variants.Scissors else if (selectVariantOrdinal > Variants.Scissors.ordinal) Variants.Rock else Variants.values()[selectVariantOrdinal] } } fun main() { fun part1(input: List<String>): Int { return input.map { moveString -> moveString[0].toVariants() to moveString[2].toVariants() } .sumOf { it.second score it.first } } fun part2(input: List<String>): Int { return input.map { moveString -> val opponentVariant = moveString[0].toVariants() opponentVariant to opponentVariant.selectVariant(moveString[2]) }.sumOf { it.second score it.first } } // test if implementation meets criteria from the description, like: val testInput = readInput("day02/Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02/Day02") println(part1(input)) println(part2(input)) } private fun Char.toVariants(): Variants = mapping[this]!!
0
Kotlin
0
1
8f3598cf29948fbf55feda585f613591c1ea4b42
2,000
advent-of-code-2022
Apache License 2.0
src/main/Day19.kt
ssiegler
572,678,606
false
{"Kotlin": 76434}
package day19 import utils.readInput import java.lang.Integer.max enum class Material { Ore, Clay, Obsidian, Geode } typealias Cost = Map<Material, Int> data class Blueprint(val id: Int, val costs: Map<Material, Cost>) { private val maxNeeded: Cost = costs.values .flatMap(Cost::asSequence) .groupingBy { it.key } .aggregate { _, accumulator, element, _ -> max(element.value, accumulator ?: 0) } fun qualityLevel(minutes: Int) = id * maxGeodes(minutes) fun maxGeodes(minutes: Int): Int { var maxGeodes = 0 val stack = ArrayDeque<State>() stack.addLast(State(emptyMap(), mapOf(Material.Ore to 1), minutes)) while (stack.isNotEmpty()) { val state = stack.removeLast() if (state.potential(this) < maxGeodes) continue maxGeodes = max(maxGeodes, state.estimate) for ((robot, costs) in costs) { if (state.robots(robot) >= maxNeeded(robot)) continue val demand = state.demand(costs) if (demand.any { (material, _) -> state.robots(material) == 0 }) continue val delta = demand.maxOfOrNull { (material, demand) -> val robots = state.robots(material) (demand + robots - 1) / robots } ?: 0 if (delta < state.time) { stack.addLast(state.addRobot(robot, costs, delta)) } } } return maxGeodes } private fun State.demand(costs: Cost) = costs.mapValues { (material, cost) -> cost - supply(material) }.filterValues { it >= 0 } private fun maxNeeded(robot: Material) = maxNeeded.getOrDefault(robot, Int.MAX_VALUE) } fun readBlueprints(filename: String) = readInput(filename) .map { """\d+""".toRegex().findAll(it).map(MatchResult::value).map(String::toInt).toList() } .map { Blueprint( it[0], mapOf( Material.Ore to mapOf(Material.Ore to it[1]), Material.Clay to mapOf(Material.Ore to it[2]), Material.Obsidian to mapOf(Material.Ore to it[3], Material.Clay to it[4]), Material.Geode to mapOf(Material.Ore to it[5], Material.Obsidian to it[6]), ) ) } data class State(val materials: Map<Material, Int>, val robots: Map<Material, Int>, val time: Int) { val estimate = listOfNotNull(materials[Material.Geode], robots[Material.Geode]?.times(time)).sum() fun potential(blueprint: Blueprint): Int { val materials = materials.toMutableMap() val additionalRobots = mutableMapOf<Material, Int>() repeat(time) { for ((robot, count) in robots.asSequence() + additionalRobots.asSequence()) { materials[robot] = materials.getOrDefault(robot, 0) + count } for (robot in blueprint.affordableRobots(materials, additionalRobots)) { additionalRobots[robot] = additionalRobots.getOrDefault(robot, 0).inc() } } return materials.getOrDefault(Material.Geode, 0) } fun supply(material: Material) = materials.getOrDefault(material, 0) fun robots(robot: Material) = robots.getOrDefault(robot, 0) fun addRobot(robot: Material, costs: Cost, delta: Int) = State( materials.toMutableMap().apply { for ((material, count) in robots) { this[material] = getOrDefault(material, 0) + count.times(delta.inc()) } for ((material, cost) in costs) { this[material] = getOrDefault(material, 0) - cost } }, robots.plus(robot to robots(robot).inc()), time - delta - 1, ) private fun Blueprint.affordableRobots( materials: MutableMap<Material, Int>, additionalRobots: MutableMap<Material, Int> ) = costs .filter { (robot, costs) -> costs.all { (material, cost) -> materials.getOrDefault(material, 0) >= additionalRobots.getOrDefault(robot, 0).inc() * cost } } .map { (robot, _) -> robot } } fun part1(filename: String) = readBlueprints(filename).sumOf { it.qualityLevel(24) } fun part2(filename: String) = readBlueprints(filename).take(3).map { it.maxGeodes(32) }.reduce(Int::times) private const val filename = "Day19" fun main() { println(part1(filename)) println(part2(filename)) }
0
Kotlin
0
0
9133485ca742ec16ee4c7f7f2a78410e66f51d80
4,729
aoc-2022
Apache License 2.0
src/year2023/day11/Day11.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day11 import check import readInput fun main() { val testInput1 = readInput("2023", "Day11_test") check(part1(testInput1), 374) check(part2(testInput1, expansionFactor = 10), 1030) check(part2(testInput1, expansionFactor = 100), 8410) val input = readInput("2023", "Day11") println(part1(input)) println(part2(input, expansionFactor = 1_000_000)) } private fun part1(input: List<String>): Long { val (emptyRows, emptyCols) = input.findEmptyRowsAndCols() return input .findAllGalaxies() .createPairs() .sumOf { it.first.distanceTo( other = it.second, emptyRows = emptyRows, emptyCols = emptyCols, expansionFactor = 2, ) } } private fun part2(input: List<String>, expansionFactor: Int): Long { val (emptyRows, emptyCols) = input.findEmptyRowsAndCols() return input .findAllGalaxies() .createPairs() .sumOf { it.first.distanceTo( other = it.second, emptyRows = emptyRows, emptyCols = emptyCols, expansionFactor = expansionFactor, ) } } private data class Pos(val x: Int, val y: Int) private fun List<String>.findAllGalaxies(): Set<Pos> { val galaxies = mutableSetOf<Pos>() for ((y, line) in withIndex()) { for ((x, c) in line.withIndex()) { if (c == '#') { galaxies += Pos(x, y) } } } return galaxies } private fun Set<Pos>.createPairs(): Set<Pair<Pos, Pos>> { val pairs = mutableSetOf<Set<Pos>>() for (a in this) { for (b in this) { if (a != b) { pairs += setOf(a, b) } } } return pairs.map { Pair(it.first(), it.last()) }.toSet() } private fun Pos.distanceTo(other: Pos, emptyRows: List<Int>, emptyCols: List<Int>, expansionFactor: Int): Long { val xRange = x.coerceAtMost(other.x)..x.coerceAtLeast(other.x) val yRange = y.coerceAtMost(other.y)..y.coerceAtLeast(other.y) val yExpansion = emptyRows.count { it in yRange } val xExpansion = emptyCols.count { it in xRange } return (xRange.last - xRange.first) + (yRange.last - yRange.first) + xExpansion * (expansionFactor - 1L) + yExpansion * (expansionFactor - 1L) } private fun List<String>.findEmptyRowsAndCols(): Pair<List<Int>, List<Int>> { val emptyRows = mutableListOf<Int>() val emptyCols = mutableListOf<Int>() for ((y, line) in withIndex()) { if (line.all { it == '.' }) { emptyRows += y } } for (x in first().indices) { if (all { it[x] == '.' }) { emptyCols += x } } return emptyRows to emptyCols }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,852
AdventOfCode
Apache License 2.0
src/main/java/com/ncorti/aoc2021/Exercise08.kt
cortinico
433,486,684
false
{"Kotlin": 36975}
package com.ncorti.aoc2021 object Exercise08 { fun part1(): Int = getInputAsTest("08") { split("\n") } .map { it.substring(it.indexOf(" | ") + 1) } .map(String::trim) .flatMap { it.split(" ") } .count { it.length in setOf(2, 3, 4, 7) } fun part2(): Int = getInputAsTest("08") { split("\n") } .map { it.split(" | ").let { tokens -> tokens[0] to tokens[1] } } .sumOf { (template, code) -> val combo = Array(7) { "" } val patterns = template.split(" ") patterns.filter { it.length == 2 }.forEach { combo[2] = it combo[5] = it } patterns.filter { it.length == 3 }.forEach { combo[0] = it.toCharArray().first { char -> char !in combo[2] }.toString() } patterns.filter { it.length == 4 }.forEach { val char4 = it.toCharArray().filter { char -> char !in combo[2] }.joinToString("") combo[1] = char4 combo[3] = char4 } patterns.filter { it.length == 5 }.forEach { val char5 = it.toCharArray() .filter { char -> char !in combo[0] && char !in combo[1] && char !in combo[2] } .joinToString("") if (char5.length == 1) { combo[6] = char5 } else { combo[4] = char5 } } combo[4] = combo[4].toCharArray().filter { it !in combo[6] }.joinToString("") val intersect6 = patterns .filter { it.length == 6 } .map { it.toCharArray().toSet() } .reduce { curr, next -> curr intersect next } .filter { it !in combo[0] && it !in combo[6] } val comb5 = intersect6.first { it in combo[5] } combo[5] = comb5.toString() combo[2] = combo[2].toCharArray().filter { it !in combo[5] }.joinToString("") combo[1] = intersect6.first { it != comb5 }.toString() combo[3] = patterns .first { it.length == 7 } .toCharArray() .first { it !in combo[0] && it !in combo[1] && it !in combo[2] && it !in combo[4] && it !in combo[5] && it !in combo[6] } .toString() code.trim() .split(" ") .joinToString("") { when (it.length) { 7 -> "8" 3 -> "7" 2 -> "1" 4 -> "4" 6 -> if (combo[3] !in it) "0" else if (combo[2] !in it) "6" else "9" else -> if (combo[1] in it) "5" else if (combo[4] in it) "2" else "3" } } .toInt() } } fun main() { println(Exercise08.part1()) println(Exercise08.part2()) }
0
Kotlin
0
4
af3df72d31b74857201c85f923a96f563c450996
3,606
adventofcode-2021
MIT License
src/Day08.kt
TinusHeystek
574,474,118
false
{"Kotlin": 53071}
class Day08 : Day(8) { private fun parseInput(input: String) : Array<IntArray> { val lines = input.lines() val rows = lines.count() val col = lines[0].length val array: Array<IntArray> = Array(rows) { IntArray(col) } lines.forEachIndexed { index, line -> array[index] = line.map { it.digitToInt() }.toIntArray() } return array } private fun getSurroundingTrees(r : Int, c: Int, array: Array<IntArray>) : List<List<Int>> { val surroundingTrees = mutableListOf<List<Int>>() surroundingTrees.add(array[r].take(c).reversed()) surroundingTrees.add(array[r].drop(c + 1)) surroundingTrees.add(array.filterIndexed{ index, _ -> index < r}.map{ it[c] }.reversed()) surroundingTrees.add(array.filterIndexed{ index, _ -> index > r}.map{ it[c] }) return surroundingTrees } // --- Part 1 --- override fun part1ToInt(input: String): Int { val array = parseInput(input) var hiddenCount = 0 for (r in 1 until array.size - 1) { for (c in 1 until array[0].size - 1) { val tree = array[r][c] val surroundingTrees = getSurroundingTrees(r, c, array) if (surroundingTrees.all {it.max() >= tree}) hiddenCount++ } } return (array.size * array[0].size) - hiddenCount } // --- Part 2 --- override fun part2ToInt(input: String): Int { val array = parseInput(input) var largestScenicScore = 0 for (r in 1 until array.size - 1) { for (c in 1 until array[0].size - 1) { val tree = array[r][c] val surroundingTrees = getSurroundingTrees(r, c, array) val distances = surroundingTrees.map { trees -> if (trees.indexOfFirst { it >= tree} < 0) trees.count() else trees.indexOfFirst { it >= tree} + 1 } val scenicScore = distances.multiplyingOf { it } if (scenicScore > largestScenicScore) largestScenicScore = scenicScore } } return largestScenicScore } } fun main() { val day = Day08() day.printToIntResults(21, 8) } inline fun <T> Iterable<T>.multiplyingOf(selector: (T) -> Int): Int { var total = 1 for (element in this) { total *= selector(element) } return total }
0
Kotlin
0
0
80b9ea6b25869a8267432c3a6f794fcaed2cf28b
2,538
aoc-2022-in-kotlin
Apache License 2.0
src/Day04.kt
coolcut69
572,865,721
false
{"Kotlin": 36853}
fun main() { fun part1(inputs: List<String>): Int { inputs.asSequence() val sections: List<Sections> = inputs.map { it.split(",") } .map { Sections(Section.from(it.first()), Section.from(it.last())) } return sections.count { it.fullyOverlap() } } fun part2(inputs: List<String>): Int { val sections: List<Sections> = inputs.map { it.split(",") } .map { Sections(Section.from(it.first()), Section.from(it.last())) } return sections.count { it.partialOverlap() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) check(part1(input) == 475) println(part2(input)) check(part2(input) == 825) } data class Section(val start: Int, val end: Int) { companion object { fun from(s: String): Section { val split = s.split("-") return Section(split.get(0).toInt(), split.get(1).toInt()) } } } data class Sections(val first: Section, val second: Section) { fun fullyOverlap(): Boolean { val firstList = (first.start..first.end).toList() val secondList = (second.start..second.end).toList() val intersect = firstList.intersect(secondList) return firstList.size == intersect.size || secondList.size == intersect.size } fun partialOverlap(): Boolean { val firstList = (first.start..first.end).toList() val secondList = (second.start..second.end).toList() val intersect = firstList.intersect(secondList) return intersect.size > 0 } }
0
Kotlin
0
0
031301607c2e1c21a6d4658b1e96685c4135fd44
1,771
aoc-2022-in-kotlin
Apache License 2.0
src/Day11.kt
bin-wang
572,801,360
false
{"Kotlin": 19395}
object Day11 { } fun main() { data class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val divisor: Int, val trueMonkeyIndex: Int, val falseMonkeyIndex: Int ) { fun testAndThrow(item: Long) = if (item % divisor == 0L) trueMonkeyIndex else falseMonkeyIndex } fun parseMonkey(description: List<String>): Monkey { val items = description[1].split(":")[1].split(",").map { it.trim().toLong() } val (operator, other) = description[2].split(" ").takeLast(2) val operation = when (operator) { "+" -> { old: Long -> StrictMath.addExact(old, other.toLong()) } "*" -> if (other == "old") { old: Long -> StrictMath.multiplyExact(old, old) } else { old: Long -> StrictMath.multiplyExact(old, other.toInt()) } else -> error("Unexpected operator") } val (divisor, ifTrue, ifFalse) = description.takeLast(3).map { it.split(" ").last().toInt() } return Monkey(items.toMutableList(), operation, divisor, ifTrue, ifFalse) } fun run(monkeys: List<Monkey>, worryCopingMethod: (Long) -> Long, repetitions: Int): Map<Int, Int> { val business = mutableMapOf<Int, Int>() repeat(repetitions) { monkeys.forEachIndexed { i, monkey -> business[i] = business.getOrDefault(i, 0) + monkey.items.size val itemsToThrowByMonkeyIndex: Map<Int, List<Long>> = monkey .items .map { worry -> worry.run(monkey.operation).run(worryCopingMethod) } .groupBy(monkey::testAndThrow) monkey.items.clear() itemsToThrowByMonkeyIndex.forEach { (monkeyIndex, itemsToThrow) -> monkeys[monkeyIndex].items.addAll(itemsToThrow) } } } return business } fun part1(input: String): Long { val monkeys = input.split("\n\n").map { parseMonkey(it.trim().lines()) } val business = run(monkeys, worryCopingMethod = { x -> x / 3 }, 20) return business.values.sortedDescending().take(2).fold(1L) { acc, i -> acc * i } } fun part2(input: String): Long { val monkeys = input.split("\n\n").map { parseMonkey(it.trim().lines()) } val commonMultiplier = monkeys.map { it.divisor }.fold(1) {acc, i -> acc * i } val business = run(monkeys, worryCopingMethod = { x -> x % commonMultiplier }, 10000) return business.values.sortedDescending().take(2).fold(1L) { acc, i -> acc * i } } val testInput = readInputAsString("Day11_test") val input = readInputAsString("Day11") println(part1(testInput)) println(part1(input)) println(part2(testInput)) println(part2(input)) }
0
Kotlin
0
0
dca2c4915594a4b4ca2791843b53b71fd068fe28
2,887
aoc22-kt
Apache License 2.0
src/main/kotlin/Day11.kt
amitdev
574,336,754
false
{"Kotlin": 21489}
import java.io.File fun main() { val result = File("inputs/day_11_1.txt").useLines { totalBusiness(monkeys(it), 10000, 1) } println(result) } fun totalBusiness(startState: Map<Int, Monkey>, times: Int = 20, divideBy: Int = 3) = (1..times) .fold(startState) { acc, _ -> simulateThrows(acc, divideBy, startState.values.totalDivides()) } .values.map { it.count } .sortedDescending() .take(2) .reduce(Long::times) private fun Collection<Monkey>.totalDivides() = map { it.divisibleBy }.reduce(Int::times) fun simulateThrows(monkeys: Map<Int, Monkey>, divideBy: Int, totalDivides: Int) = monkeys.keys.fold(monkeys) { acc, i -> rearrange(acc, acc[i]!!.throwStuff(divideBy, totalDivides)) } fun rearrange(acc: Map<Int, Monkey>, newPositions: Map<Int, List<Long>>) = newPositions.entries.fold(acc) { a, (n, items) -> a + (n to a[n]!!.updateItems(items)) } fun monkeys(lines: Sequence<String>) = lines.filter { it.isNotBlank() } .chunked(6) .map { parseMonkey(it) } .associateBy { it.n } fun parseMonkey(lines: List<String>) = Monkey( n = lines[0].split(" ")[1].split(":")[0].toInt(), items = lines[1].split(": ")[1].split(", ").map { it.toLong() }, operation = parseOp(lines[2].split("= ")[1].split(" ")), next = parseDivisible(lastInt(lines[3]), lastInt(lines[4]), lastInt(lines[5])), divisibleBy = lastInt(lines[3]) ) fun parseDivisible(divisibleBy: Int, option1: Int, option2: Int) = { n: Long -> if (n % divisibleBy == 0L) option1 else option2 } private fun lastInt(line: String) = line.split(" ").last().toInt() fun parseOp(s: List<String>) = when (s[1]) { "*" -> operation(s[0], s[2], Long::times) "+" -> operation(s[0], s[2], Long::plus) "-" -> operation(s[0], s[2], Long::minus) "/" -> operation(s[0], s[2], Long::div) else -> throw IllegalArgumentException() } fun operation(op1: String, op2: String, param: (Long, Long) -> Long) = op1.toLongOrNull() ?.let {operand1 -> op2.toLongOrNull()?.let { { _: Long -> param(operand1, it) } } ?: { n: Long -> param(n, operand1) } } ?: op2.toLongOrNull()?.let { { n: Long -> param(n, it) } } ?: { n: Long -> param(n, n) } data class Monkey( val n: Int, val items: List<Long>, val operation: Function1<Long, Long>, val next: (Long) -> Int, val divisibleBy: Int, val count: Long = 0) { fun throwStuff(divideBy: Int, totalDivides: Int) = items.map { (operation(it % totalDivides) / divideBy) }.groupBy { next(it) } + (n to listOf()) fun updateItems(newItems: List<Long>) = if (newItems.isEmpty()) copy(items = listOf(), count = count + items.size) else copy(items = items + newItems) override fun toString(): String { return "Monkey(n=$n, items=$items, count=$count)" } }
0
Kotlin
0
0
b2cb4ecac94fdbf8f71547465b2d6543710adbb9
2,725
advent_2022
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day17/Day17.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day17 import com.bloidonia.advent.readText private fun integerSumCalc(n: Int) = n * (n + 1) / 2 fun yRanges(speed: Int): Sequence<Int> = integerSumCalc(speed).let { initialSpeed -> val initial = if (speed >= 0) { generateSequence(speed) { it - 1 }.takeWhile { it > 0 }.map { initialSpeed - integerSumCalc(it - 1) } } else { emptySequence() } val drop = if (speed >= 0) { generateSequence(0) { it - 1 }.map { initialSpeed - integerSumCalc(it - 1) } } else { generateSequence(speed) { it - 1 }.map { initialSpeed - integerSumCalc(it - 1) } } return initial + drop } fun xRanges(speed: Int) = integerSumCalc(speed).let { initialSpeed -> generateSequence(speed) { it - 1 }.takeWhile { it > 0 }.map { initialSpeed - integerSumCalc(it - 1) } + generateSequence { initialSpeed } } fun validXValues(speed: Int, target: Target) = xRanges(speed) .takeWhile { it <= target.x.last }.let { it.any { target.x.contains(it) } } fun validYValues(speed: Int, target: Target) = yRanges(speed) .takeWhile { it >= target.y.first }.let { it.any { target.y.contains(it) } } data class Target(val x: IntRange, val y: IntRange) fun String.toRange() = this.split("=", limit = 2).last().split("..", limit = 2).let { (min, max) -> IntRange(min.toInt(), max.toInt()) } // target area: x=20..30, y=-10..-5 fun String.toTarget() = this.drop(13).split(", ".toPattern(), limit = 2).let { (x, y) -> Target(x.toRange(), y.toRange()) } fun <T, S> Collection<T>.cartesianProduct(other: Iterable<S>): List<Pair<T, S>> { return cartesianProduct(other) { first, second -> first to second } } fun <T, S, V> Collection<T>.cartesianProduct(other: Iterable<S>, transformer: (first: T, second: S) -> V): List<V> { return this.flatMap { first -> other.map { second -> transformer.invoke(first, second) } } } data class Part1(val xSpeed: Int, val ySpeed: Int, val valid: Boolean, val locations: List<Pair<Int, Int>>) fun validTrajectories(target: Target): List<Part1> { val xValues = (0..target.x.last) .dropWhile { integerSumCalc(it) < target.x.first } .filter { speed -> validXValues(speed, target) } val yValues = (-100..100) .filter { speed -> validYValues(speed, target) } return xValues.cartesianProduct(yValues) .map { (xSpeed, ySpeed) -> val locations = yRanges(ySpeed).zip(xRanges(xSpeed)) .takeWhile { it.first >= target.y.minOf { it } && it.second <= target.x.maxOf { it } } .toList() val valid = locations .any { target.x.contains(it.second) && target.y.contains(it.first) } Part1(xSpeed, ySpeed, valid, locations) } .filter { it.valid } } fun part1(target: Target) = validTrajectories(target).map { it.locations.maxOf { it.first } }.maxOf { it } fun part2(target: Target) = validTrajectories(target).size fun main() { println(part1(readText("/day17input.txt").toTarget())) println(part2(readText("/day17input.txt").toTarget())) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
3,148
advent-of-kotlin-2021
MIT License
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day23Test.kt
dirkgroot
317,968,017
false
{"Kotlin": 187862}
package nl.dirkgroot.adventofcode.year2022 import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import nl.dirkgroot.adventofcode.util.input import nl.dirkgroot.adventofcode.util.invokedWith private fun solution1(input: String) = parse(input).let { map -> repeat(10) { map.round() } val x1 = map.elves.minOf { it.x } val x2 = map.elves.maxOf { it.x } val y1 = map.elves.minOf { it.y } val y2 = map.elves.maxOf { it.y } (y1..y2).flatMap { y -> (x1..x2).map { x -> y to x } } .count { pos -> !map.positions.contains(pos) } } private fun solution2(input: String) = parse(input).let { map -> generateSequence { map.round() } .takeWhile { elvesMoved -> elvesMoved } .count() + 1 } private fun parse(input: String) = Map(input.lineSequence().flatMapIndexed { y, row -> row.asSequence().mapIndexedNotNull { x, char -> if (char == '#') Elf(y, x) else null } }.toList()) private class Map(val elves: List<Elf>) { val positions = elves.associateBy { it.y to it.x }.toMutableMap() private val proposalOrder = mutableListOf(Direction.N, Direction.S, Direction.W, Direction.E) fun round(): Boolean { val proposals = elves.mapNotNull { elf -> if (elf.neighbors().none { positions.contains(it) }) null else proposalOrder.firstOrNull { dir -> elf.neighbors(dir).none { pos -> positions.contains(pos) } } ?.let { when (it) { Direction.N -> (elf.y - 1 to elf.x) to elf Direction.S -> (elf.y + 1 to elf.x) to elf Direction.W -> (elf.y to elf.x - 1) to elf Direction.E -> (elf.y to elf.x + 1) to elf } } }.groupBy({ (pos, _) -> pos }, { (_, elf) -> elf }) .filter { (_, l) -> l.size == 1 } .map { (pos, l) -> pos to l.first() } proposals.forEach { (pos, elf) -> positions.remove(elf.y to elf.x) positions[pos] = elf elf.y = pos.first elf.x = pos.second } rotateProposalOrder() return proposals.isNotEmpty() } private fun rotateProposalOrder() { val dir = proposalOrder.removeFirst() proposalOrder.add(dir) } } private class Elf(var y: Int, var x: Int) { fun neighbors() = listOf( y - 1 to x - 1, y to x - 1, y + 1 to x - 1, y - 1 to x, y + 1 to x, y - 1 to x + 1, y to x + 1, y + 1 to x + 1, ) fun neighbors(dir: Direction) = when (dir) { Direction.N -> listOf(y - 1 to x - 1, y - 1 to x, y - 1 to x + 1) Direction.S -> listOf(y + 1 to x - 1, y + 1 to x, y + 1 to x + 1) Direction.W -> listOf(y - 1 to x - 1, y to x - 1, y + 1 to x - 1) Direction.E -> listOf(y - 1 to x + 1, y to x + 1, y + 1 to x + 1) } } private enum class Direction { N, S, W, E } //===============================================================================================\\ private const val YEAR = 2022 private const val DAY = 23 class Day23Test : StringSpec({ "example part 1" { ::solution1 invokedWith exampleInput shouldBe 110 } "part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 4070 } "example part 2" { ::solution2 invokedWith exampleInput shouldBe 20 } "part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 881 } }) private val exampleInput = """ ....#.. ..###.# #...#.# .#...## #.###.. ##.#.## .#..#.. """.trimIndent()
1
Kotlin
1
1
ffdffedc8659aa3deea3216d6a9a1fd4e02ec128
3,699
adventofcode-kotlin
MIT License
y2015/src/main/kotlin/adventofcode/y2015/Day24.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2015 import adventofcode.io.AdventSolution object Day24 : AdventSolution(2015, 24, "It Hangs in the Balance") { override fun solvePartOne(input: String) = input.lines().map(String::toInt).let { solve(it, 3) } override fun solvePartTwo(input: String) = input.lines().map(String::toInt).let { solve(it, 4) } private fun solve(presents: List<Int>, groupCount: Int): Long? { val target = presents.sum() / groupCount //meet-in-the-middle style solution val a: Map<Int, Group> = powerSetByWeight(presents.filterIndexed { i, _ -> i % 2 == 0 }, target) val b: Map<Int, Group> = powerSetByWeight(presents.filterIndexed { i, _ -> i % 2 != 0 }, target) return a.mapNotNull { b[target - it.key]?.mergeWith(it.value) }.minOrNull()?.quantum } private fun powerSetByWeight(presents: List<Int>, targetWeight: Int): Map<Int, Group> { return presents.fold(listOf(Group.empty) as Collection<Group>) { old, present -> (old + old.map { it.addPresent(present) }) .groupBy { it.weight } .filterKeys { it <= targetWeight } .mapValues { it.value.minOrNull()!! } .values } .associateBy { it.weight } } private data class Group(val count: Int, val weight: Int, val quantum: Long) : Comparable<Group> { fun addPresent(o: Int) = Group(count + 1, weight + o, quantum * o) fun mergeWith(o: Group) = Group(count + o.count, weight + o.weight, quantum * o.quantum) companion object { val empty = Group(0, 0, 1L) } override fun compareTo(other: Group) = compareValuesBy(this, other, Group::weight, Group::count, Group::quantum) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,758
advent-of-code
MIT License
src/main/kotlin/aoc2022/Day15.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput import java.util.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min data class SensorBeaconPair(val sensor: Point, val beacon: Point) { val hammingDistance = abs(sensor.x - beacon.x) + abs(sensor.y - beacon.y) companion object { fun fromString(input: String): SensorBeaconPair { val split = input.drop("Sensor at x=".length).split(": closest beacon is at x=") val (sensorX, sensorY) = split[0].split(", y=").map { value -> value.toInt() } val (beaconX, beaconY) = split[1].split(", y=").map { value -> value.toInt() } return SensorBeaconPair(Point(sensorX, sensorY), Point(beaconX, beaconY)) } } } private fun part1(input: List<String>, row: Int): Int { // Sensor at x=2, y=18: closest beacon is at x=-2, y=15 val allPairs = input.map { SensorBeaconPair.fromString(it) }.filter { row in it.sensor.y - it.hammingDistance..it.sensor.y + it.hammingDistance } val coveredPoints = mutableSetOf<Int>() allPairs.forEach { val distanceToTargetRow = abs(it.sensor.y - row) val remainingHammingValue = it.hammingDistance - distanceToTargetRow for (x in it.sensor.x - remainingHammingValue..it.sensor.x + remainingHammingValue) { coveredPoints.add(x) } } val beaconsInRow = allPairs.map { it.beacon }.distinct().count { it.y == row } val sensorsInRow = allPairs.map { it.sensor }.distinct().count { it.y == row } return coveredPoints.size - beaconsInRow - sensorsInRow } private fun part2(input: List<String>, maxValue: Int): Long { val allPairs = input.map { SensorBeaconPair.fromString(it) } for (row in 0..maxValue) { if (row % 100000 == 0) { print(".") } val coveredPoints = BitSet(maxValue + 1) allPairs.forEach { val distanceToTargetRow = abs(it.sensor.y - row) val remainingHammingValue = it.hammingDistance - distanceToTargetRow if (it.beacon.y == row && it.beacon.x >= 0 && it.beacon.x <= maxValue) { coveredPoints.set(it.beacon.x) } if (it.sensor.y == row && it.sensor.x >= 0 && it.sensor.x <= maxValue) { coveredPoints.set(it.sensor.x) } if (remainingHammingValue > 0) { val range = max(0, it.sensor.x - remainingHammingValue)..min(maxValue, it.sensor.x + remainingHammingValue) coveredPoints.set(range.first, range.last + 1) } } if (coveredPoints.cardinality() <= maxValue) { for (x in 0..maxValue) { if (!coveredPoints[x]) { val signalPosition = Point(x, row) println("\nSignal found at $signalPosition -> ${signalPosition.x * 4000000L + signalPosition.y}") return signalPosition.x * 4000000L + signalPosition.y } } } } throw IllegalArgumentException("No distress signal found") } fun main() { val testInput = readInput("Day15_test", 2022) check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15", 2022) println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,361
adventOfCode
Apache License 2.0
app/src/main/kotlin/day12/Day12.kt
KingOfDog
433,706,881
false
{"Kotlin": 76907}
package day12 import common.InputRepo import common.readSessionCookie import common.solve import java.nio.file.Path fun main(args: Array<String>) { val day = 12 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay12Part1, ::solveDay12Part2) } fun solveDay12Part1(input: List<String>): Int { return execute(input, canVisitSmallTwice = false) } private fun execute(input: List<String>, canVisitSmallTwice: Boolean): Int { val caveConnections = input.map { line -> line.split("-") }.map { parts -> Cave(parts[0]) to Cave(parts[1]) } val caveGraph = Graph<Cave>() caveConnections.forEach { connection -> caveGraph.addEdge(connection.first, connection.second) } val start = Cave("start") val paths = caveGraph.getPossiblePaths(start, emptyList(), canVisitSmallTwice) return paths.size } fun solveDay12Part2(input: List<String>): Int { return execute(input, canVisitSmallTwice = true) } private fun Graph<Cave>.getPossiblePaths(from: Cave, path: List<Cave>, canVisitSmallTwice: Boolean): List<List<Cave>> { val pathWithSelf = path + from if (from.isEnd) { return listOf(pathWithSelf) } val possibilities = this.adjacencyMap.getOrDefault(from, emptySet()) .filterNot { it.isStart } .filterNot { !canVisitSmallTwice && it.isSmall && path.contains(it) } return possibilities.map { getPossiblePaths( it, pathWithSelf, canVisitSmallTwice = canVisitSmallTwice && (!it.isSmall || !path.contains(it)) ) }.flatten().toSet().toList() } class Graph<T> { val adjacencyMap: HashMap<T, HashSet<T>> = HashMap() fun addEdge(sourceVertex: T, destinationVertex: T) { // Add edge to source vertex / node. adjacencyMap .computeIfAbsent(sourceVertex) { HashSet() } .add(destinationVertex) // Add edge to destination vertex / node. adjacencyMap .computeIfAbsent(destinationVertex) { HashSet() } .add(sourceVertex) } override fun toString(): String = StringBuffer().apply { for (key in adjacencyMap.keys) { append("$key -> ") append(adjacencyMap[key]?.joinToString(", ", "[", "]\n")) } }.toString() } data class Cave(val name: String) { val isSmall = name.lowercase() == name val isStart = name == "start" val isEnd = name == "end" }
0
Kotlin
0
0
576e5599ada224e5cf21ccf20757673ca6f8310a
2,467
advent-of-code-kt
Apache License 2.0
src/Day02.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
enum class Result { LOSE, DRAW, WIN; companion object { fun of(char: String) = Result.values()[char.single() - 'X'] } } enum class Choice { PAPER, ROCK, SCISSORS; private val value get() = when (this) {ROCK -> 1; PAPER -> 2; SCISSORS -> 3 } fun against(other: Choice) = (4 + other.ordinal - ordinal) % 3 - 1 fun score(other: Choice) = (against(other) + 1) * 3 + value companion object { fun of(char: String) = when (char) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException("$char not valid") } } } fun main() { fun part1(input: List<String>): Int { return input.map { it.split(' ') } .map { Pair(Choice.of(it[0]), Choice.of(it[1])) } .sumOf { (them, you) -> you.score(them) } } fun wanted(them: Choice, result: Result) = Choice.values() .first { it.against(them) == result.ordinal - 1 } fun part2(input: List<String>): Int { return input.map { it.split(' ') } .map { Pair(Choice.of(it[0]), Result.of(it[1])) } .map { (them, result) -> Pair(them, wanted(them, result)) } .sumOf { (them, you) -> you.score(them) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") checkThat(part1(testInput), 15) checkThat(part2(testInput), 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
1,574
aoc22
Apache License 2.0
src/Day16.kt
inssein
573,116,957
false
{"Kotlin": 47333}
import kotlin.math.max data class Valve( val name: String, val flowRate: Int, val tunnels: List<String>, val index: Int ) data class Path(val time: Int, val valve: String, val bitmask: Int) fun main() { fun List<String>.toValves() = this.mapIndexed { i, it -> val name = it.substringAfter("Valve ").take(2) val rate = it.substringAfter("=").substringBefore(";").toInt() val valves = it.split(", ").mapIndexed { ix, s -> if (ix == 0) s.takeLast(2) else s } Valve(name, rate, valves, i) } /** * Calculate the shortest paths using the floyd warshall algorithm. */ fun shortestPaths(valves: Map<String, Valve>): Map<String, Map<String, Int>> { val shortestPaths = valves.mapValues { (_, v) -> v.tunnels.associateWith { 1 }.toMutableMap() }.toMutableMap() for (k in shortestPaths.keys) { for (i in shortestPaths.keys) { for (j in shortestPaths.keys) { val ik = shortestPaths[i]?.get(k) ?: 99 val kj = shortestPaths[k]?.get(j) ?: 99 val ij = shortestPaths[i]?.get(j) ?: 99 if (ik + kj < ij) { shortestPaths[i]?.set(j, ik + kj) } } } } // filter out paths that have 0 flow rate return shortestPaths.mapValues { (_, v) -> v.filter { valves[it.key]?.flowRate != 0 } } } fun dfs( path: Path, cache: MutableMap<Path, Int>, valves: Map<String, Valve>, shortestPaths: Map<String, Map<String, Int>>, ): Int { val cached = cache[path] if (cached != null) { return cached } val paths = shortestPaths[path.valve] ?: error("invalid") var maxTime = 0 paths.forEach { (k, d) -> val valve = valves[k] ?: error("invalid") val time = path.time - d - 1 val bit = 1 shl valve.index if (path.bitmask.and(bit) == 0 && time > 0) { maxTime = max( maxTime, dfs(Path(time, k, path.bitmask.or(bit)), cache, valves, shortestPaths) + valve.flowRate * time ) } } return maxTime.also { cache[path] = maxTime } } fun part1(input: List<String>): Int { val valves = input.toValves() val valveMap = valves.associateBy { it.name } val shortestPaths = shortestPaths(valveMap) return dfs(Path(30, "AA", 0), mutableMapOf(), valveMap, shortestPaths) } fun part2(input: List<String>): Int { val valves = input.toValves() val shortestPaths = shortestPaths(valves.associateBy { it.name }) val optimalValves = valves.filter { it.flowRate > 0 }.mapIndexed { i, it -> it.copy(index = i) } val optimalValveMap = optimalValves.associateBy { it.name } val cache = mutableMapOf<Path, Int>() val bitmask = (1 shl optimalValves.size) - 1 var maxTime = 0 for (i in 0..(bitmask + 1) / 2) { val elf = dfs(Path(26, "AA", i), cache, optimalValveMap, shortestPaths) val elephant = dfs(Path(26, "AA", bitmask.xor(i)), cache, optimalValveMap, shortestPaths) maxTime = max(maxTime, elf + elephant) } return maxTime } val testInput = readInput("Day16_test") println(part1(testInput)) // 1651 println(part2(testInput)) // 1707 val input = readInput("Day16") println(part1(input)) // 1474 println(part2(input)) // 2100 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
3,672
advent-of-code-2022
Apache License 2.0
src/Day13.kt
marciprete
574,547,125
false
{"Kotlin": 13734}
import kotlin.math.sign typealias Signal = List<Any> fun main() { fun parse(input: Iterator<Char>): List<Any> { val list = mutableListOf<Any>() while(input.hasNext()) { var c = input.next() if(c=='[') { list.add(parse(input)) } else if(c.isDigit()) { var s = "" while((c.isDigit())) { s += c.toString() c = input.next() } list.add(s.toInt()) } if(c==']') { return list } } return list } fun compareIn(left: Signal , right: Signal): Int { var rightOrder = 0 val leftIterator = left.iterator() val rightIterator = right.iterator() while((leftIterator.hasNext() || rightIterator.hasNext()) && rightOrder == 0) { if(!leftIterator.hasNext() || !rightIterator.hasNext()) { rightOrder = (right.size - left.size).sign } else { val l = leftIterator.next() val r = rightIterator.next() val leftIsList = l is List<*> val rightIsList = r is List<*> if (!leftIsList && !rightIsList) { rightOrder = r.toString().toInt().compareTo(l.toString().toInt()) } else { rightOrder = compareIn( (if (leftIsList) l as Signal else listOf(l)) as Signal, (if (rightIsList) r as Signal else listOf(r)) as Signal ) } } } if(rightOrder==0) { rightOrder = (right.size - left.size).sign } return rightOrder } fun compare(it: Pair<Any, Any>): Int { val left = it.first //as List<Any> val right = it.second //as List<Any> return compareIn(left as Signal, right as Signal) } fun part1(input: List<String>): Int { val pairs = input.windowed(2,3).map { Pair(parse(it[0].iterator())[0], parse(it[1].iterator())[0]) } return pairs.mapIndexed{ idx, it -> val compare = compare(it) when(compare >0) { true -> idx+1 else -> 0 } }.sum() } fun part2(input: List<String>): Int { val dividerPkt1 = parse("[[2]]".iterator())[0] val dividerPkt2 = parse("[[6]]".iterator())[0] val pairs = input.windowed(2,3).map { Pair(parse(it[0].iterator())[0], parse(it[1].iterator())[0]) } as MutableList pairs.add(Pair(dividerPkt1, dividerPkt2)) val signals = mutableListOf<Any>() pairs.forEach { signals.addAll(it.toList())} signals.sortWith(Comparator { x, y -> compareIn(y as Signal,x as Signal)} ) val so = signals.mapIndexed{ index, item -> when { item==dividerPkt1 || item == dividerPkt2 -> index+1 else -> 1 } }.reduce{tot, elem -> tot*elem} return so } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) val test2Input = readInput("Day13_test") check(part2(test2Input) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6345abc8f2c90d9bd1f5f82072af678e3f80e486
3,471
Kotlin-AoC-2022
Apache License 2.0
src/main/kotlin/Day5.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
private const val MIN_COUNT_CROSSING = 2 data class Point(val x: Int, val y: Int) class Segment(val start: Point, val end: Point) { private fun checkPoints(): Segment { if (start.x < end.x) return this if (start.x == end.x && start.y < end.y) return this return Segment(end, start) } fun getPoints(): List<Point> = with(checkPoints()) { if (start.x == end.x) { return (start.y..end.y).map { Point(start.x, it) } } if (start.y == end.y) { return (start.x..end.x).map { Point(it, start.y) } } val distanceX = end.x - start.x val distanceY = end.y - start.y val direction = when { distanceY > 0 -> 1 distanceY < 0 -> -1 else -> 0 } return (0..distanceX).map { delta -> Point(start.x + delta, start.y + direction * delta) } } } private fun getSegments(data: List<String>) = data.map { val (start, end) = it.split("->") val (x1, y1) = start.split(",") val (x2, y2) = end.split(",") Segment( Point(x1.trim().toInt(), y1.trim().toInt()), Point(x2.trim().toInt(), y2.trim().toInt()) ) } fun main() { val data = readInputFile("day5") val segments = getSegments(data) fun countCrossing(segments: List<Segment>): Int { val count = mutableMapOf<Point, Int>() for (line in segments) { for (point in line.getPoints()) { count[point] = (count[point] ?: 0) + 1 } } return count.filter { it.value >= MIN_COUNT_CROSSING }.count() } fun part1(): Int { val filtered = segments.filter { it.start.x == it.end.x || it.start.y == it.end.y } return countCrossing(filtered) } fun part2(): Int { return countCrossing(segments) } println("Result part1: ${part1()}") println("Result part2: ${part2()}") }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
1,955
AOC2021
Apache License 2.0
src/y2023/Day04.kt
a3nv
574,208,224
false
{"Kotlin": 34115, "Java": 1914}
package y2023 import utils.readInput fun main() { /* Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 */ fun part1(input: List<String>): Int { var sum = 0 input.forEach { card -> val cardData = card.split(":") cardData.filter { it.isNotBlank() && !it.startsWith("Card") }.forEach { data -> val winners = data.substringBefore("|").trim() .split(" ").filter { it.isNotBlank() }.toSet() val playerHand = data.substringAfter("|").trim() .split(" ").filter { it.isNotBlank() }.toSet() val count = winners.intersect(playerHand).count() // println("Winners $winners --> player $playerHand = ${winners.intersect(playerHand)}") sum += 1 shl (count - 1) } } return sum } fun part2(input: List<String>): Int { val map = mutableMapOf<Int, Int>() input.forEach { card -> val cardData = card.split("Card") cardData.filter { it.isNotBlank()}.forEach { data -> val cardNumber = data.substringBefore(":").trim().toInt() map[cardNumber] = map.getOrDefault(cardNumber, 0) + 1 val dataSets = data.substringAfter(": ").trim() val winners = dataSets.substringBefore("|").trim() .split(" ").filter { it.isNotBlank() }.toSet() val playerHand = dataSets.substringAfter("|").trim() .split(" ").filter { it.isNotBlank() }.toSet() val count = winners.intersect(playerHand).count() // println("Winners $winners --> player $playerHand = ${winners.intersect(playerHand)}") for (i in 1 .. count ) { map[cardNumber + i] = map.getOrDefault(cardNumber + i, 0) + (map[cardNumber] ?: 1) } } } return map.values.sum() } // test if implementation meets criteria from the description, like: var testInput = readInput("y2023", "Day04_test_part1") println(part1(testInput)) check(part1(testInput) == 13) println(part2(testInput)) check(part2(testInput) == 30) val input = readInput("y2023", "Day04") check(part1(input) == 20407) println(part1(input)) check(part2(input) == 23806951) println(part2(input)) }
0
Kotlin
0
0
ab2206ab5030ace967e08c7051becb4ae44aea39
2,404
advent-of-code-kotlin
Apache License 2.0
src/year2023/day05/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day05 import arrow.core.nonEmptyListOf import utils.ProblemPart import utils.intersect import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 5, transform = ::parse) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(35), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(46), algorithm = ::part2, ), ) } private fun parse(input: List<String>) = Input( seeds = input.first() .drop(7) .split(' ') .map { it.toLong() }, mappings = input.drop(2).fold(mutableListOf(mutableListOf<Pair<LongRange, Long>>())) { accumulator, line -> if (line.isEmpty()) accumulator.add(mutableListOf()) else if (!line.first().isLetter()) line.splitToSequence(' ') .map { it.toLong() } .toList() .let { (end, start, length) -> accumulator.last().add( Pair( (start until (start + length)), end - start, ) ) } accumulator } ) private fun part1(input: Input): Long { return input.seeds.asSequence() .map { seed -> input.mappings.fold(seed) { location, mapping -> val offset = mapping.firstOrNull { location in it.first }?.second ?: 0L location + offset } } .min() } private fun part2(input: Input): Long { val seeds = input.seeds.chunked(2) { (start, length) -> start until (start + length) } return input.mappings .fold(seeds) { seedsPositions, mapping -> seedsPositions.flatMap { seedRange -> val newSeedRanges = mapping.mapNotNull { (range, offset) -> (range intersect seedRange)?.to(offset) } val unmovedSeeds = newSeedRanges.fold(listOf(seedRange)) { unusedRanges, (usedRange) -> unusedRanges.flatMap { unusedRange -> val intersect = unusedRange intersect usedRange if (intersect == null) listOf(unusedRange) else { val startRange = unusedRange.first until usedRange.first val endRange = (usedRange.last + 1)..unusedRange.last listOfNotNull(startRange.takeUnless { it.isEmpty() }, endRange.takeUnless { it.isEmpty() }) } } } newSeedRanges.mapTo(unmovedSeeds.toMutableList()) { (it.first.first + it.second)..(it.first.last + it.second) } } } .minOf { it.first } } private data class Input( val seeds: List<Long>, val mappings: List<List<Pair<LongRange, Long>>>, )
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
3,046
Advent-of-Code
Apache License 2.0
src/main/kotlin/day19.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day19 import aoc.utils.Timer import aoc.utils.findInts import aoc.utils.readInput fun main() { part2().let { println(it) } } fun part1(): Int { val bluePrints = bluePrints() return run(24, bluePrints) .map { it.first * it.second.geode } .sum() } fun part2(): Int { // 661217579 // 4318464576 lol val bluePrints = bluePrints().take(3) run(32, bluePrints) return 1 } class Optimizer { // timeLeft, geodeCollected private val highScore = mutableMapOf<Int, Int>() fun alreadyWorse(timeLeft: Int, resources: Resources, production: Resources): Boolean { // How much geode would accumulate if building one geode robot each turn forward val additionalGeode = (1..timeLeft).sum() // How much would current production yield val current = production.geode * timeLeft val total = additionalGeode + current + resources.geode return total <= (highScore[timeLeft] ?: -1) } fun update(timeLeft: Int, resources: Resources) { if ((highScore[timeLeft] ?: -1) < resources.geode) { highScore[timeLeft] = resources.geode } } fun asString(): String { return highScore.map { "${it.key}:${it.value}" }.joinToString(",") } } data class Resources(val ore: Int, val clay: Int, val obsidian: Int, val geode: Int) { fun plus(other: Resources): Resources { return copy( ore = ore + other.ore, clay = clay + other.clay, obsidian = obsidian + other.obsidian, geode = geode + other.geode, ) } fun minus(other: Resources): Resources { return copy( ore = ore - other.ore, clay = clay - other.clay, obsidian = obsidian - other.obsidian, geode = geode - other.geode, ) } fun asString(): String { return ",$ore,$clay,$obsidian,$geode," } } data class Robot(val cost: Resources, val production: Resources) data class BluePrint(val oreRobot: Robot, val clayRobot: Robot, val obsidianRobot: Robot, val geodeRobot: Robot) val states = mutableMapOf<String,Resources>(); fun run(time: Int, bluePrints: List<BluePrint>): List<Pair<Int, Resources>> { val timer = Timer(bluePrints.size.toLong()) return bluePrints .mapIndexed { index, bluePrint -> println("Processing blueprint ${index + 1}") val result = produceGeode(time, bluePrint) timer.processed = index.toLong() + 1 val r = Pair(index + 1, result) println("DONE blueprint ${index + 1}: $r took ${globalCounter} steps") // states.toList() // .sortedByDescending { it.second } // .filter { it.first.split(",").last().toInt() > 10 } // .take(50) // .forEach{ println(it) } globalCounter = 0 states.clear() r } } fun produceGeode(time: Int, bluePrint: BluePrint): Resources { val highScore = Optimizer() val production = Resources(1, 0, 0, 0) val resources = Resources(0, 0, 0, 0) return testProduction(time, bluePrint, production, resources, highScore) } var globalCounter = 0L; fun testProduction( timeLeft: Int, bluePrint: BluePrint, production: Resources, resources: Resources, highScore: Optimizer ): Resources { val key = production.asString()+resources.asString()+timeLeft val result = states[key] if(result!=null) return result globalCounter++ // println("$identifier score: ${resources.geode}") if (timeLeft == 0) return resources if (highScore.alreadyWorse(timeLeft, resources, production)) { // print("$identifier Stopping") return resources } val newTime = timeLeft - 1 // val prettyGoodAction = whatsNext( // newTime, // bluePrint, // production, // resources, // highScore // ) val results = listOfNotNull( // prettyGoodAction, testProductionIfResources( newTime, bluePrint, production, resources, bluePrint.geodeRobot, highScore ), testProductionIfResources( newTime, bluePrint, production, resources, bluePrint.oreRobot, highScore ), testProductionIfResources( newTime, bluePrint, production, resources, bluePrint.clayRobot, highScore ), testProductionIfResources( newTime, bluePrint, production, resources, bluePrint.obsidianRobot, highScore ), if (hasResourcesForAnyRobot(bluePrint, resources)) null else testProduction(newTime, bluePrint, production, resources.plus(production), highScore) ) val bestResult = results.maxByOrNull { it.geode }!! highScore.update(timeLeft, resources) if(timeLeft > 10) states[key]=bestResult return bestResult } fun whatsNext( timeLeft: Int, bluePrint: BluePrint, production: Resources, resources: Resources, highScore: Optimizer ): Resources? { if (production.ore <= 1) { if (hasResourcesForRobot(bluePrint.oreRobot, resources)) return testProduction( timeLeft, bluePrint, production.plus(bluePrint.oreRobot.production), resources.minus(bluePrint.oreRobot.cost).plus(production), highScore ) } if (production.clay < 1) { if (hasResourcesForRobot(bluePrint.clayRobot, resources)) return testProduction( timeLeft, bluePrint, production.plus(bluePrint.clayRobot.production), resources.minus(bluePrint.clayRobot.cost).plus(production), highScore ) } if (production.obsidian < 1) { if (hasResourcesForRobot(bluePrint.obsidianRobot, resources)) return testProduction( timeLeft, bluePrint, production.plus(bluePrint.obsidianRobot.production), resources.minus(bluePrint.obsidianRobot.cost).plus(production), highScore ) } if (production.geode < 1) { if (hasResourcesForRobot(bluePrint.geodeRobot, resources)) return testProduction( timeLeft, bluePrint, production.plus(bluePrint.geodeRobot.production), resources.minus(bluePrint.geodeRobot.cost).plus(production), highScore ) } return null } fun hasResourcesForAnyRobot(bluePrint: BluePrint, resources: Resources): Boolean { return hasResourcesForRobot(bluePrint.oreRobot, resources) && hasResourcesForRobot(bluePrint.clayRobot, resources) && hasResourcesForRobot(bluePrint.obsidianRobot, resources) && hasResourcesForRobot(bluePrint.geodeRobot, resources) } fun testProductionIfResources( newTime: Int, bluePrint: BluePrint, production: Resources, resources: Resources, robot: Robot, highScore: Optimizer ): Resources? { return if (hasResourcesForRobot(robot, resources)) testProduction( newTime, bluePrint, production.plus(robot.production), resources.minus(robot.cost).plus(production), highScore ) else null } fun hasResourcesForRobot(type: Robot, resources: Resources): Boolean { return resources.ore >= type.cost.ore && resources.clay >= type.cost.clay && resources.obsidian >= type.cost.obsidian } private fun bluePrints(): List<BluePrint> { val bluePrints = readInput("day19-input.txt") .map { it.findInts() } .map { BluePrint( Robot(Resources(it[1], 0, 0, 0), Resources(1, 0, 0, 0)), Robot(Resources(it[2], 0, 0, 0), Resources(0, 1, 0, 0)), Robot(Resources(it[3], it[4], 0, 0), Resources(0, 0, 1, 0)), Robot(Resources(it[5], 0, it[6], 0), Resources(0, 0, 0, 1)), ) } return bluePrints }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
8,426
adventOfCode2022
Apache License 2.0
src/Day12.kt
dmarmelo
573,485,455
false
{"Kotlin": 28178}
private data class HeightMap( val elevations: Map<Point2D, Int>, val start: Point2D, val end: Point2D ) { fun getNeighbors(point: Point2D) = point.cardinalNeighbors.filter { n -> n in elevations } } fun main() { fun List<String>.parseInput(): HeightMap { var start: Point2D? = null var end: Point2D? = null val elevations = flatMapIndexed { y, row -> row.mapIndexed { x, char -> val point = Point2D(x, y) point to when (char) { 'S' -> 0.also { start = point } 'E' -> ('z' - 'a').also { end = point } else -> char - 'a' } } }.toMap() return HeightMap(elevations, start!!, end!!) } fun <T> breathFirstSearch( start: T, isGoal: (T) -> Boolean, getNeighbors: (T) -> Iterable<T>, canMove: (from: T, to: T) -> Boolean = { _, _ -> true } ): Int { val seen = mutableSetOf<T>() val queue = ArrayDeque<Pair<T, Int>>().apply { add(start to 0) } while (queue.isNotEmpty()) { val (item, cost) = queue.removeFirst() if (isGoal(item)) { return cost } getNeighbors(item) .filter { canMove(item, it) } .filter { it !in seen } .forEach { seen += it queue.add(it to cost + 1) } } return -1 } fun part1(map: HeightMap): Int { return breathFirstSearch( start = map.start, isGoal = { it == map.end }, getNeighbors = { map.getNeighbors(it) }, canMove = { from, to -> map.elevations[to]!! - map.elevations[from]!! <= 1 } ) } fun part2(map: HeightMap): Int { return breathFirstSearch( start = map.end, isGoal = { map.elevations[it]!! == 0 }, getNeighbors = { map.getNeighbors(it) }, canMove = { from, to -> map.elevations[from]!! - map.elevations[to]!! <= 1 } ) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test").parseInput() check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12").parseInput() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d3cbd227f950693b813d2a5dc3220463ea9f0e4
2,445
advent-of-code-2022
Apache License 2.0
src/Day13.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { val day = 13 fun parseItems(s: MutableList<Char>): List<Any> { val list = mutableListOf<Any>() var token: String? = null while (s.isNotEmpty()) { when (val ch = s.removeFirst()) { '[' -> list.add(parseItems(s)) ']' -> { if (token != null) list.add(token.toInt()) return list } ',' -> { if (token != null) list.add(token.toInt()) token = null } else -> token = (token ?: "") + ch } } return list } fun parseItems(s: String) = parseItems(s.toMutableList()).first() as List<Any> fun parseInput(input: List<String>) = input.chunked(3) .asSequence() .map { parseItems(it[0]) to parseItems(it[1]) } fun correct(left: List<Any>, right: List<Any>): Boolean? { if (left.isEmpty() && right.isEmpty()) return null if (left.isEmpty()) return true if (right.isEmpty()) return false val lhead = left.first() val rhead = right.first() val result = when { lhead is Int && rhead is Int -> if (lhead < rhead) true else if (lhead > rhead) false else null lhead is Int -> correct(listOf(lhead), rhead as List<Any>) rhead is Int -> correct(lhead as List<Any>, listOf(rhead)) else -> correct(lhead as List<Any>, rhead as List<Any>) } if (result != null) return result return correct(left.drop(1), right.drop(1)) } fun part1(input: List<String>) = parseInput(input).mapIndexed { i, p -> i + 1 to correct(p.first, p.second)!! } .filter { it.second } .sumOf { it.first } fun part2(input: List<String>): Int { val dividers: List<List<Any>> = listOf(listOf(listOf(2)), listOf(listOf(6))) return input.filter { it.isNotEmpty() } .map { parseItems(it) } .toList() .plus(dividers) .sortedWith { a, b -> when { correct(a, b) == true -> -1 correct(a, b) == false -> 1 else -> 0 }} .foldIndexed(1) { i, a, v -> if (v in dividers) (i+1) * a else a } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day.pad(2)}_test") checkTest(13) { part1(testInput) } checkTest(140) { part2(testInput) } val input = readInput("Day${day.pad(2)}") solution { part1(input) } solution { part2(input) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
2,734
aoc22
Apache License 2.0
src/main/kotlin/day7/solver.kt
derekaspaulding
317,756,568
false
null
package day7 import java.io.File typealias RuleSet = Map<String, List<Pair<String, Int>>> val BAG_REGEX = Regex("(^|no|\\d).+?(?=\\sbags?)") fun parseRuleset(rules: List<String>): RuleSet { var ruleSet: RuleSet = mapOf() for (rule in rules) { val bagDescriptions = BAG_REGEX.findAll(rule).toList().map { it.value } ruleSet = ruleSet + mapOf( bagDescriptions[0] to bagDescriptions .subList(1, bagDescriptions.size) .filter { it != "no other" } .map { val (num, description) = it.split(" ", limit = 2) Pair(description, num.toInt()) } ) } return ruleSet } fun canCarryShinyGoldBag(ruleSet: RuleSet, bag: String): Boolean { val rules = ruleSet[bag] ?: listOf() return rules.any { it.first == "shiny gold" || canCarryShinyGoldBag(ruleSet, it.first) } } fun solveProblemOne(ruleList: List<String>): List<String> { val ruleSet = parseRuleset(ruleList) return ruleSet.keys.filter { canCarryShinyGoldBag(ruleSet, it) } } fun getInnerBags(ruleSet: RuleSet, bag: String): Int { val rules = ruleSet[bag] ?: listOf() return rules.fold(0, { acc, pair -> val (innerBag, num) = pair acc + num + (num * getInnerBags(ruleSet, innerBag)) }) } fun solveProblemTwo(ruleList: List<String>): Int { val ruleSet = parseRuleset(ruleList) return getInnerBags(ruleSet, "shiny gold") } fun main() { val ruleList = File("src/main/resources/day7/input.txt").useLines { it.toList() } val firstSolution = solveProblemOne(ruleList) println("${firstSolution.size} bags can hold a shiny gold bag") println("a shiny gold bag must contain ${solveProblemTwo(ruleList)} other bags") }
0
Kotlin
0
0
0e26fdbb3415fac413ea833bc7579c09561b49e5
1,827
advent-of-code-2020
MIT License
src/year2022/15/Day15.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2022.`15` import kotlin.math.abs import readInput data class Point( val x: Int, val y: Int ) data class SensorToBeacon( val sensor: Point, val beacon: Point ) fun parseInput(input: List<String>): List<SensorToBeacon> { return input.map { val items = it.split("=", ",", ":").mapNotNull { it.toIntOrNull() } val sensor = Point(items[0], items[1]) val beacon = Point(items[2], items[3]) SensorToBeacon(sensor, beacon) } } private fun Point.distressSignal(): Long = x * 4000000L + y private fun Point.calculateDistanceTo(point: Point): Int { val x = x - point.x val y = y - point.y return abs(x) + abs(y) } private fun List<Pair<Point, Point>>.iteratePointsRange(): Sequence<Point> = sequence { forEach { (left, right) -> (left.x..right.x).forEach { yield(Point(it, left.y)) } } }.distinct() private fun createSetOfIndexes( result: List<SensorToBeacon>, row: Int ): List<Pair<Point, Point>> { val mutableResult = mutableListOf<Pair<Point, Point>>() val minX = result.minOf { minOf(it.beacon.x, it.sensor.x) } val maxX = result.maxOf { maxOf(it.beacon.x, it.sensor.x) } (minX..maxX).forEach { val point = Point(it, row) result.forEach { (sensor, beacon) -> if (point.calculateDistanceTo(sensor) == sensor.calculateDistanceTo(beacon)) { val pair = findPairForCurrentPointY(sensor, beacon, point) mutableResult.add(pair) } } } return mutableResult } private fun iteratePointsAroundEachSensor( result: List<SensorToBeacon>, size: Int ): Sequence<Point> = sequence { val range = 0..size result.map { it.sensor to it.sensor.calculateDistanceTo(it.beacon) + 1 } .forEach { (sensor, distance) -> for (xDelta in -distance..distance) { val yDelta = distance - abs(xDelta) val res = listOf( Point(sensor.x + xDelta, y = sensor.y + yDelta), Point(sensor.x + xDelta, y = sensor.y - yDelta) ).filter { it.x in range && it.y in range } yieldAll(res) } } }.distinct() private fun findPairForCurrentPointY( sensor: Point, beacon: Point, point: Point ): Pair<Point, Point> { val distance = sensor.calculateDistanceTo(beacon) val rightPart = distance - abs(sensor.y - point.y) val firstX = sensor.x + rightPart val secondX = sensor.x - rightPart return Point(minOf(firstX, secondX), point.y) to Point(maxOf(firstX, secondX), point.y) } private fun isPointOutsideOfAllSensors( result: List<SensorToBeacon>, point: Point ) = result.all { (sensor, beacon) -> sensor.calculateDistanceTo(point) > sensor.calculateDistanceTo(beacon) } fun main() { fun part1(input: List<String>, row: Int): Int { val result = parseInput(input) val setOfBeacons = result.map { it.beacon }.toSet() val mutableResult = createSetOfIndexes(result, row) return mutableResult.iteratePointsRange().count { it !in setOfBeacons } } fun part2(input: List<String>, size: Int): Point { val result = parseInput(input) return iteratePointsAroundEachSensor( result = result, size = size ).first { point -> isPointOutsideOfAllSensors(result, point) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") val part1Test = part1(testInput, 10) val part2Test = part2(testInput, 20) check(part1Test == 26) check(part2Test.distressSignal() == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4_000_000).distressSignal()) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,795
KotlinAdventOfCode
Apache License 2.0
src/Day04.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
fun checkOverlap(pair: Pair<IntRange, IntRange>, completely: Boolean = true): Boolean { val elf1 = pair.first val elf2 = pair.second return if (completely) { val smallest = minOf(elf1.last - elf1.first + 1, elf2.last - elf2.first + 1) smallest == elf1.intersect(elf2).size } else { elf1.intersect(elf2).isNotEmpty() } } fun strToElfPair(strInput: String): Pair<IntRange, IntRange> { return strInput .split(',') .map { strElf -> val (start, end) = strElf.split('-').map { it.toInt() } start..end } .chunked(2) .map { Pair(it.first(), it[1]) } .first() } fun main() { fun part1(input: List<String>): Int { val redundantPairs = input .map { strToElfPair(it) } .map { checkOverlap(it) } .filter { it } return redundantPairs.size } fun part2(input: List<String>): Int { val redundantPairs = input .map { strToElfPair(it) } .map { checkOverlap(it, false) } .filter { it } return redundantPairs.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
1,412
advent-of-code-2022
Apache License 2.0
src/main/kotlin/de/nilsdruyen/aoc/Day08.kt
nilsjr
571,758,796
false
{"Kotlin": 15971}
package de.nilsdruyen.aoc fun main() { fun part1(input: List<String>): Int { val forest = input.map { it.map { tree -> tree.digitToInt() } } val forestWidth = forest.first().size - 1 val forestHeight = forest.size - 1 val outerVisible = forest.first().size * 2 + (forest.size * 2) - 4 val innerVisible = forest .mapIndexed { indexR, row -> row.mapIndexed { indexT, t -> if (indexT in 1 until forestWidth && indexR in 1 until forestHeight) { val leftVisible = forest[indexR].slice(0 until indexT).max() < t val rightVisible = forest[indexR].slice(indexT + 1..forestWidth).max() < t val topVisible = forest.map { it[indexT] }.slice(0 until indexR).max() < t val bottomVisible = forest.map { it[indexT] }.slice(indexR + 1..forestHeight).max() < t listOf(leftVisible, rightVisible, topVisible, bottomVisible).any { it } } else { false } } } .flatten() .count { it } return outerVisible + innerVisible } fun part2(input: List<String>): Int { val forest = input.map { it.map { tree -> tree.digitToInt() } } val forestWidth = forest.first().size - 1 val forestHeight = forest.size - 1 val scenicScore = forest .mapIndexed { indexR, row -> row.mapIndexed { indexT, t -> if (indexT in 1 until forestWidth && indexR in 1 until forestHeight) { val leftVisible = forest[indexR] .slice(0 until indexT) .reversed() val rightVisible = forest[indexR].slice(indexT + 1..forestWidth) val topVisible = forest .map { it[indexT] } .slice(0 until indexR) .reversed() val bottomVisible = forest.map { it[indexT] }.slice(indexR + 1..forestHeight) println("check $indexR/$indexT - $t") val list = listOf(leftVisible, rightVisible, topVisible, bottomVisible) println(list) list .map { direction -> val zipped = direction.zipWithNext().ifEmpty { listOf(Pair(direction.first(), 0)) } if (t <= zipped.first().first) { 1 } else { zipped.takeWhile { it.first <= it.second }.oneIfEmpty() } } .fold(1) { result, count -> result * count } } else { 0 } } } .flatten() .max() return scenicScore } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) check(part2(testInput) == 12) val input = readInput("Day08") println(part1(input)) println(part2(input)) // 1023568 too high , 360 low } private fun <T> List<T>.oneIfEmpty(): Int { return if (this.isEmpty()) 1 else this.size + 1 }
0
Kotlin
0
0
1b71664d18076210e54b60bab1afda92e975d9ff
3,575
advent-of-code-2022
Apache License 2.0
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day14/Day14.kt
sanderploegsma
224,286,922
false
{"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171}
package nl.sanderp.aoc.aoc2021.day14 import nl.sanderp.aoc.common.increaseBy import nl.sanderp.aoc.common.measureDuration import nl.sanderp.aoc.common.prettyPrint import nl.sanderp.aoc.common.readResource fun main() { val input = readResource("Day14.txt").lines() val template = parseTemplate(input.first()) val rules = input.drop(2).associate { parseRule(it) } val (answer1, duration1) = measureDuration<Long> { partOne(template, rules) } println("Part one: $answer1 (took ${duration1.prettyPrint()})") val (answer2, duration2) = measureDuration<Long> { partTwo(template, rules) } println("Part one: $answer2 (took ${duration2.prettyPrint()})") } private fun parseTemplate(template: String) = template.zipWithNext { a, b -> a to b }.groupingBy { it }.eachCount().mapValues { it.value.toLong() } private fun parseRule(rule: String) = rule.split(" -> ").let { (it[0][0] to it[0][1]) to it[1][0] } private fun insert(polymer: Map<Pair<Char, Char>, Long>, rules: Map<Pair<Char, Char>, Char>) = buildMap<Pair<Char, Char>, Long> { for ((pair, n) in polymer) { val c = rules[pair]!! increaseBy(pair.first to c, n) increaseBy(c to pair.second, n) } } private fun build(polymer: Map<Pair<Char, Char>, Long>, rules: Map<Pair<Char, Char>, Char>) = generateSequence(polymer) { insert(it, rules) } private fun partOne(polymer: Map<Pair<Char, Char>, Long>, rules: Map<Pair<Char, Char>, Char>): Long { val result = build(polymer, rules).drop(10).first() val counts = result.map { it.key.second to it.value }.groupBy { it.first }.mapValues { it.value.sumOf { it.second } } return counts.maxOf { it.value } - counts.minOf { it.value } } private fun partTwo(polymer: Map<Pair<Char, Char>, Long>, rules: Map<Pair<Char, Char>, Char>): Long { val result = build(polymer, rules).drop(40).first() val counts = result.map { it.key.second to it.value }.groupBy { it.first }.mapValues { it.value.sumOf { it.second } } return counts.maxOf { it.value } - counts.minOf { it.value } }
0
C#
0
6
8e96dff21c23f08dcf665c68e9f3e60db821c1e5
2,049
advent-of-code
MIT License
src/year2022/day11/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2022.day11 import readInput fun main() { val day = "11" val expectedTest1 = 10605L val expectedTest2 = 2713310158L data class Monkey( var items: List<Long>, val operType: (Long) -> Long, val testDivisor: Long, val destinationDivisible: Long, val destinationNotDivisible: Long, val processed: Long ) { fun calculateDestinations(worryLevelDecreaser: Long, mmc: Long): Map<Long, List<Long>> { return items.map { val newWorryLevel = (operType(it) / worryLevelDecreaser) % mmc when (newWorryLevel % testDivisor) { 0L -> destinationDivisible else -> destinationNotDivisible } to newWorryLevel }.groupBy({ it.first }, { it.second }) } } fun toFunction(it: List<String>): (Long) -> Long { return when (it[it.size - 2]) { "*" -> { a: Long -> a * (it.last().toLongOrNull() ?: a) } "/" -> { a: Long -> a / (it.last().toLongOrNull() ?: a) } "+" -> { a: Long -> a + (it.last().toLongOrNull() ?: a) } "-" -> { a: Long -> a - (it.last().toLongOrNull() ?: a) } else -> { _ -> throw IllegalArgumentException() } } } fun geOriginalState(input: List<String>): Map<Long, Monkey> { val originalMonkeys = input.chunked(7).mapIndexed { idx, chunk -> idx * 1L to Monkey( items = chunk[1].split(":", ",", " ").mapNotNull { it.toLongOrNull() }, operType = toFunction(chunk[2].split(" ")), testDivisor = chunk[3].split(" ").last().toLong(), destinationDivisible = chunk[4].split(" ").last().toLong(), destinationNotDivisible = chunk[5].split(" ").last().toLong(), processed = 0 ) }.toMap() return originalMonkeys } fun getIt(input: List<String>, worryDecrease: Long, rounds: Int): Long { val originalMonkeys = geOriginalState(input) val mmc = originalMonkeys.map { it.value.testDivisor }.reduce { a, b -> a * b } return List(rounds) { List(originalMonkeys.size) { it * 1L } }.asSequence().flatten().fold(originalMonkeys) { acc, i -> val destinations = acc[i]?.calculateDestinations(worryDecrease, mmc) ?: throw IllegalArgumentException() acc.map { e -> e.key to e.value.copy( items = when (e.key) { i -> listOf() else -> e.value.items + (destinations[e.key] ?: listOf()) }, processed = e.value.processed + when (e.key) { i -> e.value.items.size else -> 0 } ) }.toMap() }.map { it.value.processed } .sortedDescending() .take(2) .reduce{ a, b -> a * b } } fun part1(input: List<String>): Long { return getIt(input, 3, 20) } fun part2(input: List<String>): Long { return getIt(input, 1, 10000) } // test if implementation meets criteria from the description, like: val testInput = readInput("year2022/day$day/test") val part1Test = part1(testInput) check(part1Test == expectedTest1) { "expected $expectedTest1 but was $part1Test" } val input = readInput("year2022/day$day/input") println(part1(input)) val part2Test = part2(testInput) check(part2Test == expectedTest2) { "expected $expectedTest2 but was $part2Test" } println(part2(input)) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
3,748
adventOfCode
Apache License 2.0
kotlin/src/main/kotlin/year2023/Day12.kt
adrisalas
725,641,735
false
{"Kotlin": 130217, "Python": 1548}
package year2023 fun main() { val input = readInput("Day12") Day12.part1(input).println() Day12.part2(input).println() } object Day12 { private val memo = hashMapOf<Pair<String, List<Int>>, Long>() fun part1(input: List<String>): Long { return input.map { line -> val springs = line.split(" ")[0] val numbers = line.split(" ")[1] .split(",") .filter { it.isNotBlank() } .map { it.toInt() } Pair(springs, numbers) }.sumOf { countSolutions(it.first, it.second) } } private fun countSolutions(springs: String, numbers: List<Int>): Long { if (numbers.isEmpty()) { return if (springs.contains("#")) 0 else 1 } if (springs.isEmpty()) { return 0 } return memo.getOrPut(Pair(springs, numbers)) { var count = 0L if (canBeAHealthySpring(springs.first())) { count += countSolutions(springs.drop(1), numbers) } if (canStartWithAGroupOfBrokenSprings(springs, numbers.first())) { count += countSolutions(springs.drop(numbers.first() + 1), numbers.drop(1)) } count } } private fun canBeAHealthySpring(spring: Char): Boolean { return spring != '#' } private fun canStartWithAGroupOfBrokenSprings(springs: String, length: Int): Boolean { val enoughSize = springs.length >= length val hasNoHealthySprings = !springs.take(length).contains('.') val hasSameSize = length == springs.length val nextSpringIsNotBroken = springs.getOrNull(length) != '#' return enoughSize && hasNoHealthySprings && (hasSameSize || nextSpringIsNotBroken) } fun part2(input: List<String>): Long { return input.map { line -> val springs = "${line.split(" ")[0]}?" .repeat(5) .dropLast(1) val numbers = "${line.split(" ")[1]}," .repeat(5) .split(",") .filter { it.isNotBlank() } .map { it.toInt() } Pair(springs, numbers) }.sumOf { countSolutions(it.first, it.second) } } }
0
Kotlin
0
2
6733e3a270781ad0d0c383f7996be9f027c56c0e
2,270
advent-of-code
MIT License
src/Day09.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
import kotlin.math.abs import kotlin.math.sign private class Solution09(input: List<String>, ropeLength: Int) { val moves = input.map { it.split(" ") }.flatMap { (move, count) -> (0 until count.toInt()).map { move } } var rope = (0 until ropeLength).map { Coordinate() }.toMutableList() val tailPositions = mutableSetOf<Coordinate>() fun solve(): Int { for (m in moves) { rope.indices.forEach { if (it == 0) moveHead(m) else if (hasToMove(it)) move(it) } tailPositions.add(rope.last()) } return tailPositions.size } private fun moveHead(m: String) { val head = rope.first() rope[0] = when (m) { "U" -> Coordinate(head.x, head.y + 1) "D" -> Coordinate(head.x, head.y - 1) "L" -> Coordinate(head.x - 1, head.y) "R" -> Coordinate(head.x + 1, head.y) else -> throw IllegalArgumentException() } } private fun hasToMove(node: Int): Boolean { val predecessor = rope[node - 1] val successor = rope[node] return abs(predecessor.x - successor.x) > 1 || abs(predecessor.y - successor.y) > 1 } private fun move(node: Int) { val predecessor = rope[node - 1] val successor = rope[node] rope[node] = Coordinate( successor.x - (successor.x - predecessor.x).sign, successor.y - (successor.y - predecessor.y).sign ) } } fun main() { val testSolution = Solution09(readInput("Day09_test"), 2) check(testSolution.solve() == 13) val testSolution2 = Solution09(readInput("Day09_test"), 10) check(testSolution2.solve() == 1) val testSolution3 = Solution09(readInput("Day09_test2"), 10) check(testSolution3.solve() == 36) val solution = Solution09(readInput("Day09"), 2) println(solution.solve()) val solution2 = Solution09(readInput("Day09"), 10) println(solution2.solve()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,960
aoc-2022
Apache License 2.0
y2017/src/main/kotlin/adventofcode/y2017/Day21.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2017 import adventofcode.io.AdventSolution import adventofcode.util.algorithm.transpose private val startingConfiguration: Square = ".#./..#/###".split('/') object Day21 : AdventSolution(2017, 21, "Fractal Art") { override fun solvePartOne(input: String) = puzzle(input, 5) override fun solvePartTwo(input: String) = puzzle(input, 18) private fun puzzle(input: String, i: Int): Int { val rules = parseRewriteRules(input) var grid = startingConfiguration repeat(i) { val squareSize = if (grid.size % 2 == 0) 2 else 3 grid = grid.step(squareSize, rules) } return grid.countLights() } } private fun parseRewriteRules(input: String): Map<Square, Square> = input.lines() .map { it.split(" => ").map { it.split("/") } } .flatMap { (old, new) -> old.symmetries().map { symmetryOfOld -> symmetryOfOld to new } } .toMap() private fun Square.symmetries(): List<Square> { val rotations = generateSequence(this) { it.rotate() }.take(4).asIterable() return rotations + rotations.map { it.reversed() } } private fun Square.rotate(): Square = indices.map { i -> this[0].indices.reversed() .map { j -> this[j][i] } .fold(StringBuilder(), StringBuilder::append) .toString() } private fun Square.step(squareSize: Int, fullRules: Map<Square, Square>): Square = chunked(squareSize).flatMap { chunkRow -> chunkRow.map { line -> line.chunked(squareSize) } .transpose() .map { square -> fullRules.getValue(square) } .transpose() .map { line -> line.fold(StringBuilder(), StringBuilder::append).toString() } } private fun Square.countLights() = sumOf { line -> line.count { char -> char == '#' } } private typealias Square = List<String>
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,723
advent-of-code
MIT License
src/main/kotlin/Day7.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import kotlin.String import kotlin.collections.List object Day7 { interface CardHand : Comparable<CardHand> { val maxSimilarCards: Int val bid: Long val secondMaxSimilarCards: Int val cards: CharArray val cardValues: Map<Char, Int> fun score(rank: Int): Long { return bid * rank } override fun compareTo(other: CardHand): Int { return compareBy<CardHand> { it.maxSimilarCards } .thenBy { it.secondMaxSimilarCards } .then { first, second -> val thisCardValues = first.cards.map { cardValues[it] ?: 0 } val otherCardValues = second.cards.map { cardValues[it] ?: 0 } thisCardValues.zip(otherCardValues).map { it.first - it.second }.firstOrNull { it != 0 } ?: 0 } .compare(this, other) } } data class CamelCardHandWithJokers(override val cards: CharArray, override val bid: Long) : CardHand { override val maxSimilarCards: Int private val possibleCards: CharArray = arrayOf('J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A').toCharArray() override val secondMaxSimilarCards: Int override val cardValues = possibleCards.zip(possibleCards.indices).toMap() init { val numJokers = cards.count { it == 'J' } val nonJokers = cards.filter { it != 'J' }.groupBy { it }.mapValues { it.value.size } val values = nonJokers.values.sortedDescending() val maxNonJokers = values.firstOrNull() ?: 0 val secondMaxNonJokers = values.drop(1).firstOrNull() ?: 0 maxSimilarCards = maxNonJokers + numJokers secondMaxSimilarCards = secondMaxNonJokers } companion object { fun parse(input: String): CamelCardHandWithJokers { val (cards, bid) = input.split(" ") return CamelCardHandWithJokers(cards.toCharArray(), bid.toLong()) } } } data class CamelCardHand(override val cards: CharArray, override val bid: Long) : CardHand { override val maxSimilarCards: Int override val secondMaxSimilarCards: Int private val possibleCards: CharArray = arrayOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A').toCharArray() override val cardValues = possibleCards.zip(possibleCards.indices).toMap() init { val grouped = cards.groupBy { it }.mapValues { it.value.size } val values = grouped.values.sortedDescending() maxSimilarCards = values.first() secondMaxSimilarCards = values.drop(1).firstOrNull() ?: 0 } companion object { fun parse(input: String): CamelCardHand { val (cards, bid) = input.split(" ") return CamelCardHand(cards.toCharArray(), bid.toLong()) } } } fun part1(input: List<String>): String { val hands = input.map(CamelCardHand::parse) return score(hands).toString() } fun part2(input: List<String>): String { val hands = input.map(CamelCardHandWithJokers::parse) return score(hands).toString() } private fun score(hands: List<CardHand>): Long { val sortedHands = hands.sorted() return sortedHands.zip(sortedHands.indices).sumOf { (hand, index) -> hand.score(index + 1) } } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
3,507
kotlin-kringle
Apache License 2.0
src/year2015/day13/Day13.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day13 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2015", "Day13_test") check(part1(testInput), 330) val input = readInput("2015", "Day13") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val graph = parseGraph(input) return getHappinessForBestSeatingCombination(graph) } private fun part2(input: List<String>): Int { val graph = parseGraph(input).toMutableMap() graph["Me"] = emptyMap() return getHappinessForBestSeatingCombination(graph) } private fun parseGraph(input: List<String>): Map<String, Map<String, Int>> { val graph = hashMapOf<String, MutableMap<String, Int>>() val pattern = "(\\w+) would (gain|lose) (\\d+) happiness units by sitting next to (\\w+).".toRegex() input.forEach { line -> val (_, a, gainOrLose, happyness, b) = pattern.matchEntire(line)?.groupValues ?: error("Line not matching pattern: $line") val change = (if (gainOrLose == "lose") -1 else 1) * happyness.toInt() graph.getOrPut(a) { hashMapOf() } += b to change } return graph } private fun getHappinessForBestSeatingCombination(graph: Map<String, Map<String, Int>>): Int { val combinations = getCombinations(graph.keys) val totalHappinessByCombination = combinations.associateWith { combination -> (combination.windowed(2) + listOf(listOf(combination.first(), combination.last()))).sumOf { (a, b) -> (graph.getValue(a)[b] ?: 0) + (graph.getValue(b)[a] ?: 0) } } return totalHappinessByCombination.values.max() } private fun getCombinations(remaining: Set<String>, people: List<String> = emptyList()): List<List<String>> { if (remaining.isEmpty()) return listOf(people) val result = mutableListOf<List<String>>() for (person in remaining) { result += getCombinations(remaining - person, people + person) } return result }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,038
AdventOfCode
Apache License 2.0
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day15/Day15.kt
jntakpe
433,584,164
false
{"Kotlin": 64657, "Rust": 51491}
package com.github.jntakpe.aoc2021.days.day15 import com.github.jntakpe.aoc2021.shared.Day import com.github.jntakpe.aoc2021.shared.readInputLines import java.util.* object Day15 : Day { override val input = Instructions.from(readInputLines(15)) override fun part1() = input.shortestPath() override fun part2(): Int { val scale = input.scale(5) return scale.shortestPath() } class Instructions(private val positions: Map<Position, Int>, private val end: Position) { companion object { fun from(lines: List<String>): Instructions { val positions = lines.map { l -> l.toCharArray().map { it.digitToInt() } } .flatMapIndexed { y, i -> i.mapIndexed { x, v -> (Position(x, y) to v) } } .toMap() return Instructions(positions, positions.keys.last()) } } fun scale(times: Int): Instructions { var positions = positions listOf<(Position, Int) -> Position>({ p, i -> p.scaleX(end, i) }, { p, i -> p.scaleY(end, i) }) .forEach { scale -> positions = (1 until times).fold(positions.toMutableMap()) { a, c -> a.apply { putAll(positions.mapKeys { (p, _) -> scale(p, c) }.mapValues { (_, v) -> ((c + v - 1) % 9) + 1 }) } } } return Instructions(positions, positions.keys.last()) } fun shortestPath(): Int { val queue = PriorityQueue<Node>().apply { add(Node(Position.START, 0)) } val risks = positions.mapValues { (k, _) -> if (k == Position.START) 0 else Int.MAX_VALUE }.toMutableMap() while (queue.isNotEmpty()) { val node = queue.poll() if (node.position == end) return risks[end]!! if (risks[node.position]!! < node.risk) continue node.position.adjacent() .mapNotNull { p -> positions[p]?.let { Node(p, it + node.risk) } } .filter { it.risk < risks[it.position]!! } .forEach { risks[it.position] = it.risk; queue.add(it) } } error("Shortest path not found") } } class Node(val position: Position, val risk: Int) : Comparable<Node> { override fun compareTo(other: Node) = risk - other.risk } data class Position(val x: Int, val y: Int) { companion object { val START = Position(0, 0) } fun adjacent() = listOf(copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1)) fun scaleX(size: Position, times: Int) = copy(x = x + (size.x + 1) * times) fun scaleY(size: Position, times: Int) = copy(y = y + (size.y + 1) * times) } }
0
Kotlin
1
5
230b957cd18e44719fd581c7e380b5bcd46ea615
2,885
aoc2021
MIT License
12/kotlin/src/main/kotlin/se/nyquist/Main.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist import java.io.File fun main() { val lines = File("input.txt").readLines() val values = lines.map { it.split("-") }.toList() val pairs = values.map { Pair(it[0], it[1] )}.union(values.map { Pair(it[1], it[0] )}) exercise1(pairs.distinct().toList()) exercise2(pairs.distinct().toList()) } fun exercise1(pairs: List<Pair<String, String>>) { val paths = buildAllPaths(pairs.distinct().toList()) println("Number of paths: ${paths.size}") } fun exercise2(pairs: List<Pair<String, String>>) { val paths = buildAllPaths2(pairs.distinct().toList()) println("Number of paths: ${paths.size}") } fun buildAllPaths(values: List<Pair<String, String>>) : List<String> { val startNodes = values.filter { it.first == "start"}.distinct().toList() return startNodes.flatMap { findPathFrom(it, values, mutableListOf(it.first)) }.distinct() } fun findPathFrom(current: Pair<String, String>, values: List<Pair<String, String>>, visited : MutableList<String>) : List<String> { if (visited.contains(current.second) && current.second == current.second.lowercase()) { return listOf() } visited.add(current.second) val next = values.filter { it.first == current.second && (it.second == it.second.uppercase() || ! visited.contains(it.second)) } val result = mutableListOf<String>() if (next.isNotEmpty()) { next.forEach { if (it.second != "end") { val found = findPathFrom(it, values, visited) if (found.isNotEmpty()) { result.addAll(found) } } else { visited.add(it.second) val path = visited.joinToString("-") // println(path) result.add(path) visited.removeLast() } } } visited.removeLast() return result.distinct().toList() } fun buildAllPaths2(values: List<Pair<String, String>>) : List<String> { val startNodes = values.filter { it.first == "start"}.distinct().toList() return startNodes.flatMap { findPathFrom2(it, values, mutableListOf(it.first)) }.distinct() } fun findPathFrom2(current: Pair<String, String>, values: List<Pair<String, String>>, visited : MutableList<String>) : List<String> { visited.add(current.second) if (! isAcceptable(current, visited)) { visited.removeLast() return listOf() } val next = values.filter { it.first == current.second && isAcceptable(it, visited) } val result = mutableListOf<String>() if (next.isNotEmpty()) { next.forEach { if (it.second != "end") { val found = findPathFrom2(it, values, visited) if (found.isNotEmpty()) { result.addAll(found) } } else { visited.add(it.second) val path = visited.joinToString("-") // println(path) result.add(path) visited.removeLast() } } } visited.removeLast() return result.distinct().toList() } private fun isAcceptable( it: Pair<String, String>, visited: MutableList<String> ) : Boolean { val isBigCave = it.second == it.second.uppercase() val occurrenceMap = visited.filter { it == it.lowercase() }.groupingBy { it }.eachCount().filterNot { it.value == 1 } return isBigCave || (it.second != "start" && occurrenceMap.size <= 1 && occurrenceMap.none{ it.value > 2 }) }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
3,523
adventofcode2021
Apache License 2.0
y2023/src/main/kotlin/adventofcode/y2023/Day05.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2023 import adventofcode.io.AdventSolution fun main() { Day05.solve() } object Day05 : AdventSolution(2023, 5, "If You Give A Seed A Fertilizer") { override fun solvePartOne(input: String): Long? { val (seeds, converters) = parse(input) return seeds.minOfOrNull { seed -> converters.fold(seed) { category, converter -> converter.shift(category) } } } override fun solvePartTwo(input: String): Long { val (seeds, converters) = parse(input) val seedRanges = seeds.chunked(2).map { (start, length) -> start until start + length } return converters .fold(seedRanges) { categoryRanges, converter -> converter.cut(categoryRanges).map { categoryRange -> converter.shiftRange(categoryRange) } } .minOf { it.first } } } private fun parse(input: String): Pair<List<Long>, List<Converter>> { val sections = input.split("\n\n") val seeds = sections[0].substringAfter("seeds: ").split(" ").map(String::toLong) val converters = sections.drop(1).map { section -> section.lines().drop(1) .map { line -> val (dest, source, length) = line.split(" ").map(String::toLong) Shifter(source until source + length, dest - source) } .let(::Converter) } return Pair(seeds, converters) } private data class Converter(val ranges: List<Shifter>) { //cut up the set of intervals such that each interval is entirely inside or outside a shifter fun cut(categoryRanges: List<LongRange>) = ranges.fold(categoryRanges) { range, shifter -> range.flatMap { it.cutWith(shifter.range) } } fun shift(input: Long) = input + (ranges.find { input in it.range }?.delta ?: 0L) fun shiftRange(input: LongRange) = shift(input.first)..shift(input.last) } private data class Shifter(val range: LongRange, val delta: Long) private fun LongRange.cutWith(interval: LongRange): List<LongRange> { val before = first..last.coerceAtMost(interval.first - 1) val inside = first.coerceAtLeast(interval.first)..last.coerceAtMost(interval.last) val after = first.coerceAtLeast(interval.last + 1)..last return listOf(before, inside, after).filterNot(LongRange::isEmpty) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,324
advent-of-code
MIT License
src/main/kotlin/eu/michalchomo/adventofcode/year2022/Day07.kt
MichalChomo
572,214,942
false
{"Kotlin": 56758}
package eu.michalchomo.adventofcode.year2022 sealed class File data class DataFile(val size: Long) : File() data class Directory(val path: String, val files: MutableList<File>) : File() { fun size(): Long = files.sumOf { when (it) { is DataFile -> it.size is Directory -> it.size() } } } data class MutablePair(var currentPath: String, val pathToDirectory: MutableMap<String, Directory>) fun main() { fun String.removeLastPathElement() = substringBeforeLast("/").ifEmpty { "/" } fun List<String>.toDirectories(): List<Directory> = fold(MutablePair("", mutableMapOf("/" to Directory("/", mutableListOf())))) { acc, s -> when { s == "$ ls" -> acc s == "$ cd .." -> acc.apply { currentPath = currentPath.removeLastPathElement() } s.startsWith("$ cd") -> acc.apply { val path = if (currentPath.length < 2) currentPath else "$currentPath/" currentPath = path + s.split(" ")[2] } s.startsWith("dir") -> acc.apply { val path = if (currentPath == "/") currentPath else "$currentPath/" Directory(path + s.split(" ")[1], mutableListOf()).let { pathToDirectory[it.path] = it pathToDirectory[currentPath]?.files?.add(it) } } else -> acc.apply { pathToDirectory[currentPath]?.files?.add(DataFile(s.split(" ")[0].toLong())) } } } .pathToDirectory.values .toList() fun part1(input: List<String>): Long = input.toDirectories() .asSequence() .map { it.size() } .filter { it < 100_000 } .sum() fun part2(input: List<String>): Long = input.toDirectories().let { directories -> val neededSpace = directories.asSequence() .filter { it.path == "/" } .map { it.size() } .first() .let { usedSpace -> 30_000_000 - (70_000_000 - usedSpace) } directories.asSequence() .map { it.size() } .filter { it >= neededSpace } .min() } val testInput = readInputLines("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInputLines("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a95d478aee72034321fdf37930722c23b246dd6b
2,494
advent-of-code
Apache License 2.0
src/day08/Day08_functional.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day08 import readLines /** * Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin) * I'm experimenting with his solutions to better learn functional programming in Kotlin. * Files without the _functional suffix are my original solutions. */ private val input: List<String> = readLines("day08/input") private val forest: Array<IntArray> = input.map { row -> row.map { it.digitToInt() }.toIntArray() }.toTypedArray() private val rows: Int = forest.size private val cols: Int = forest.first().size private fun Array<IntArray>.isVisible(row: Int, col: Int): Boolean = viewFrom(row, col) // get list in each direction .any { direction -> // check for any direction... direction.all { it < this[row][col] } // are all values in list less than current position? } private fun Array<IntArray>.viewFrom(row: Int, col: Int): List<List<Int>> = listOf( (row - 1 downTo 0).map { this[it][col] }, // Up (row + 1 until rows).map { this[it][col] }, // Down this[row].take(col).asReversed(), // Left this[row].drop(col + 1) // Right ) inline fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> { val list = ArrayList<T>() for (item in this) { list.add(item) if (predicate(item)) { break } } return list } fun Iterable<Int>.product(): Int = reduce { a, b -> a * b } private fun Array<IntArray>.scoreAt(row: Int, col: Int): Int = viewFrom(row, col) // get list in each direction .map { direction -> direction // for each list/direction call takeUntil you find a bigger tree .takeUntil { it >= this[row][col] }.count() // count the result of takeUntil for direction }.product() // calculate the product of the results from the 4 directions private fun part1(): Int { var visibleCount = (1 until rows - 1).sumOf { r -> // for each row... (1 until cols - 1).count { c -> // for each col... forest.isVisible(r, c) // is edge visible from here? } } val perimeterCount = (2 * rows) + (2 * cols) - 4 // we skipped the perimeter from above, so calculate that here visibleCount += perimeterCount return visibleCount } private fun part2(): Int { var scenicScore = (1 until rows - 1).maxOf { r -> // for each row... (1 until cols - 1).maxOf { c -> // for each col... forest.scoreAt(r, c) // calculate the scenic score. maxOf will return the max. } } return scenicScore } fun main() { println(part1()) println(part2()) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
2,643
aoc2022
Apache License 2.0
src/year2023/day08/Day08.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day08 import check import lcm import readInput fun main() { val testInput1 = readInput("2023", "Day08_test_part1") val testInput2 = readInput("2023", "Day08_test_part2") check(part1(testInput1), 6) check(part2(testInput2), 6) val input = readInput("2023", "Day08") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Long { val pathsByPos = input.getPathsByPos() return pathsByPos.countStepsUntil( startingPos = "AAA", instructions = input.getInstructions(), ) { it == "ZZZ" } } private fun part2(input: List<String>): Long { val pathsByPos = input.getPathsByPos() val startingPositions = pathsByPos.keys.filter { it.endsWith("A") } return startingPositions.map { startingPos -> pathsByPos.countStepsUntil( startingPos = startingPos, instructions = input.getInstructions(), ) { it.endsWith("Z") } }.lcm() } private fun Map<String, Pair<String, String>>.countStepsUntil( startingPos: String, instructions: Instructions, predicate: (String) -> Boolean, ): Long { var currentPos = startingPos var steps = 0L while (!predicate(currentPos)) { currentPos = getValue(currentPos).take(instructions.next()) steps++ } return steps } private enum class Direction { L, R } private data class Instructions(val seq: List<Direction>, var index: Int = 0) { fun next(): Direction = seq[index++ % seq.size] } private fun Pair<String, String>.take(dir: Direction): String = if (dir == Direction.L) first else second private fun List<String>.getInstructions() = Instructions(first().map { if (it == 'L') Direction.L else Direction.R }) private fun List<String>.getPathsByPos() = drop(2).associate { line -> val pos = line.substring(0, 3) val left = line.substring(7, 10) val right = line.substring(12, 15) pos to Pair(left, right) }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,953
AdventOfCode
Apache License 2.0
src/Day15.kt
MatthiasDruwe
571,730,990
false
{"Kotlin": 47864}
import kotlin.math.abs import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>, y: Long): Int { val sensors = input.map { val values = it.split(" ") val sensorX = values[2].split("=")[1].removeSuffix(",").toLong() val sensorY = values[3].split("=")[1].removeSuffix(":").toLong() val beaconX = values[8].split("=")[1].removeSuffix(",").toLong() val beaconY = values[9].split("=")[1].toLong() Pair(Pair(sensorX, sensorY), Pair(beaconX, beaconY)) } val noBeacons = mutableSetOf<Pair<Long, Long>>() sensors.forEach { pair -> val sensor = pair.first val beacon = pair.second val distance = abs(sensor.first - beacon.first) + abs(sensor.second - beacon.second) if (distance - abs(sensor.second - y) >= 0) { val x1 = distance - abs(sensor.second - y) + sensor.first val x2 = -(distance - abs(sensor.second - y)) + sensor.first for (i in min(x1, x2)..max(x1, x2)) { noBeacons.add(Pair(i, y)) } } } println(noBeacons.size) val output = noBeacons.count { nobeacon -> sensors.find { it.first == nobeacon || it.second == nobeacon } == null } println(output) return output } fun manhattanDistance(pair1: Pair<Long, Long>, pair2: Pair<Long, Long>): Long { return abs(pair1.first - pair2.first) + abs(pair1.second - pair2.second) } fun part2(input: List<String>, size: Int): Long { val sensors = input.map { val values = it.split(" ") val sensorX = values[2].split("=")[1].removeSuffix(",").toLong() val sensorY = values[3].split("=")[1].removeSuffix(":").toLong() val beaconX = values[8].split("=")[1].removeSuffix(",").toLong() val beaconY = values[9].split("=")[1].toLong() Pair(Pair(sensorX, sensorY), Pair(beaconX, beaconY)) } var point = Pair(0L, 0L) for (y in 0..size) { var x = 0 while (x <= size) { val visibleSensors = sensors.filter { manhattanDistance(it.first, Pair(x.toLong(), y.toLong())) <= manhattanDistance(it.first, it.second) } if (visibleSensors.isEmpty()) { point = Pair(x.toLong(), y.toLong()) break } x = visibleSensors.maxOf { manhattanDistance( it.first, it.second ) - abs(it.first.second - y) + it.first.first } .toInt() + 1 } if (point != Pair(0L, 0L)) { break } } return point.first * 4000000 + point.second } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_example") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
3,302
Advent-of-code-2022
Apache License 2.0
src/Day08.kt
armandmgt
573,595,523
false
{"Kotlin": 47774}
fun main() { fun countInDir(input: List<String>, dir: Direction): MutableList<Pair<Int, Int>> { val visibleTrees = mutableListOf<Pair<Int, Int>>() var currentSize = -1 val range = when (dir) { Direction.NORTH, Direction.WEST -> input.indices.reversed() Direction.SOUTH, Direction.EAST -> input.indices } for (c in input.indices) { for (m in range) { val pos = when (dir) { Direction.NORTH, Direction.SOUTH -> Pair(c, m) Direction.WEST, Direction.EAST -> Pair(m, c) } if ((input[pos.first][pos.second] - '0') > currentSize) { currentSize = input[pos.first][pos.second] - '0' visibleTrees.add(pos) } } currentSize = -1 } return visibleTrees; } fun part1(input: List<String>): Int { return (countInDir(input, Direction.NORTH) + countInDir(input, Direction.SOUTH) + countInDir(input, Direction.EAST) + countInDir(input, Direction.WEST)).toSet().size } fun viewFrom(input: List<String>, x: Int, y: Int, dir: Direction): Int { var count = 0 val range = when (dir) { Direction.NORTH -> (0 until y).reversed() Direction.SOUTH -> (y + 1..input.lastIndex) Direction.EAST -> (x + 1..input.lastIndex) Direction.WEST -> (0 until x).reversed() } range.forEach { count += 1 when (dir) { Direction.NORTH, Direction.SOUTH -> if (input[it][x] >= input[y][x]) return count Direction.EAST, Direction.WEST -> if (input[y][it] >= input[y][x]) return count } } return count } fun scenicScore(input: List<String>, x: Int, y: Int): Int { return viewFrom(input, x, y, Direction.NORTH) * viewFrom(input, x, y, Direction.SOUTH) * viewFrom(input, x, y, Direction.EAST) * viewFrom(input, x, y, Direction.WEST) } fun part2(input: List<String>): Int { return input.indices.maxOf { y -> input.indices.maxOf { x -> scenicScore(input, x, y) } } } // test if implementation meets criteria from the description, like: val testInput = readInput("resources/Day08_test") check(part1(testInput) == 21) val input = readInput("resources/Day08") println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
1
0d63a5974dd65a88e99a70e04243512a8f286145
2,654
advent_of_code_2022
Apache License 2.0
src/Day07.kt
dmarmelo
573,485,455
false
{"Kotlin": 28178}
private typealias Command = Pair<String, List<String>> sealed class FsEntry( val name: String ) { abstract val size: Int } private class Directory( name: String, var children: List<FsEntry> = emptyList() ) : FsEntry(name) { override val size: Int get() = children.sumOf { it.size } } private class File( name: String, override val size: Int, ) : FsEntry(name) private fun Directory.findAllSubDirectorires(): List<Directory> = children .filterIsInstance<Directory>() .fold(emptyList()) { acc, directory -> acc + directory + directory.findAllSubDirectorires() } private fun Directory.findSubDirectory(path: String): Directory? { val subPaths = path.split("/").filter { it.isNotBlank() } var currentDirectory = this for (subPath in subPaths) { currentDirectory = currentDirectory.children .filterIsInstance<Directory>() .find { it.name == subPath } ?: return null } return currentDirectory } fun main() { fun String.parseInput(): List<Command> { return split("$ ") .drop(1) .map { it.trim() } .map { val lines = it.lines() lines.first() to lines.drop(1) } } fun List<Command>.buildFileTree(): Directory { var currentPath = "/" val root = Directory("/") forEach { (command, output) -> with(command) { when { startsWith("cd") -> { currentPath = when (val argument = command.removePrefix("cd ")) { "/" -> "/" ".." -> currentPath.substringBeforeLast("/", "/") else -> if (currentPath.endsWith("/")) currentPath + argument else "$currentPath/$argument" } } startsWith("ls") -> { val newEntries = output.map { val (sizeOrType, name) = it.split(" ") if (sizeOrType == "dir") { Directory(name) } else { File(name, sizeOrType.toInt()) } } root.findSubDirectory(currentPath)?.apply { children += newEntries } ?: error("Unknown path $currentPath") } else -> error("Unknown command $command") } } } return root } fun part1(root: Directory): Int { return root.findAllSubDirectorires() .map { it.size } .filter { it <= 100_000 } .sum() } fun part2(root: Directory): Int { val totalDiskSpace = 70_000_000 val spaceRequired = 30_000_000 val spaceUsed = root.size val unusedSpace = totalDiskSpace - spaceUsed val spaceToClean = spaceRequired - unusedSpace return root.findAllSubDirectorires() .map { it.size } .filter { it >= spaceToClean } .min() } // test if implementation meets criteria from the description, like: val testInput = readInputText("Day07_test").parseInput().buildFileTree() check(part1(testInput) == 95_437) check(part2(testInput) == 24_933_642) val input = readInputText("Day07").parseInput().buildFileTree() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5d3cbd227f950693b813d2a5dc3220463ea9f0e4
3,667
advent-of-code-2022
Apache License 2.0
src/year_2022/day_01/Day01.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_01 import readInput data class Elf(val foodCalories: List<Int>) { val totalCalories: Int get() = foodCalories.sum() } object Day01 { /** * Calculate the position and elf with the most calories * * @return Elf position to Total Calories */ fun solutionOne(elvesText: List<String>): Pair<Int, Int> { val elves = parseElves(elvesText) val highestCalorieElf = elves .mapIndexed { index, elf -> index to elf } .maxByOrNull { (_, elf) -> elf.totalCalories }!! return highestCalorieElf.first + 1 to highestCalorieElf.second.totalCalories } /** * Calculate the total calories for the 3 elves with the most calories * * @return Sum of Top 3 Calorie Elves */ fun solutionTwo(elvesText: List<String>): Int { val elves = parseElves(elvesText) return elves .mapIndexed { index, elf -> index to elf } .sortedByDescending { (_, elf) -> elf.totalCalories } .subList(0, 3) .sumOf { (_, elf) -> elf.totalCalories } } private fun parseElves(input: List<String>): List<Elf> { val mutableElves = mutableListOf<Elf>() var currentFoodList = mutableListOf<Int>() input.forEach { text -> if (text.isEmpty()) { mutableElves.add(Elf(currentFoodList)) currentFoodList = mutableListOf() } else { currentFoodList.add(text.toInt()) } } mutableElves.add(Elf(currentFoodList)) return mutableElves } } fun main() { val elvesText = readInput("year_2022/day_01/Day01.txt") val solutionOne = Day01.solutionOne(elvesText) println("Solution 1: Elf: ${solutionOne.first}. Total Calories: ${solutionOne.second}") val solutionTwo = Day01.solutionTwo(elvesText) println("Solution 2: Total 3 Total Calories: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
1,954
advent_of_code
Apache License 2.0