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/year2015/day21/Day21.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day21 import readInput import kotlin.math.max fun main() { val input = readInput("2015", "Day21") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val (bossInitialHP, bossDmg, bossArmor) = input.map { it.split(' ').last().toInt() } val combinations = getEquipmentCombinations() val cheapestWinningCombination = combinations.first { playerStats -> fightBoss(playerStats, bossArmor, bossDmg, bossInitialHP) } return cheapestWinningCombination.cost } private fun part2(input: List<String>): Int { val (bossInitialHP, bossDmg, bossArmor) = input.map { it.split(' ').last().toInt() } val combinations = getEquipmentCombinations() val mostExpensiveLosingCombination = combinations.last { playerStats -> !fightBoss(playerStats, bossArmor, bossDmg, bossInitialHP) } return mostExpensiveLosingCombination.cost } private fun fightBoss( playerStats: Stats, bossArmor: Int, bossDmg: Int, bossInitialHP: Int, playerInitialHP: Int = 100, ): Boolean { var bossHP = bossInitialHP var playerHP = playerInitialHP val playerDmgPerRound = max(playerStats.damage - bossArmor, 1) val bossDmgPerRound = max(bossDmg - playerStats.armor, 1) while (bossHP > 0 && playerHP > 0) { bossHP -= playerDmgPerRound if (bossHP > 0) { playerHP -= bossDmgPerRound } } return playerHP > 0 } private data class Stats( val cost: Int, val damage: Int, val armor: Int, ) { operator fun plus(other: Stats) = Stats( cost = cost + other.cost, damage = damage + other.damage, armor = armor + other.armor, ) } private fun getEquipmentCombinations(): List<Stats> { val weapons = listOf( Stats(8, 4, 0), Stats(10, 5, 0), Stats(25, 6, 0), Stats(40, 7, 0), Stats(74, 8, 0), ) val armors = listOf( Stats(13, 0, 1), Stats(31, 0, 2), Stats(53, 0, 3), Stats(75, 0, 4), Stats(102, 0, 5), ) val rings = listOf( Stats(25, 1, 0), Stats(50, 2, 0), Stats(100, 3, 0), Stats(20, 0, 1), Stats(40, 0, 2), Stats(80, 0, 3), ) val combinations = HashSet(weapons) combinations += armors.flatMap { armor -> combinations.map { armor + it } } val ringCombos = rings.flatMap { ring -> rings.map { ring to it } } .filter { it.first != it.second } .map { it.first + it.second } combinations += rings.flatMap { ring -> combinations.map { ring + it } } + ringCombos.flatMap { ringCombo -> combinations.map { ringCombo + it } } return combinations.sortedBy { it.cost } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,756
AdventOfCode
Apache License 2.0
src/2022/Day18.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun part1(input: List<String>): Int { val drops = input.map { val (x, y, z) = it.split(",").map(String::toInt) Point3(x, y, z) }.toSet() return drops.sumOf { drop -> drop.slideNeighbors().filter { !drops.contains(it) }.size } } fun part2(input: List<String>): Int { val drops = input.map { val (x, y, z) = it.split(",").map(String::toInt) Point3(x, y, z) }.toSet() val maxX = drops.maxOf { it.x } val maxY = drops.maxOf { it.y } val maxZ = drops.maxOf { it.z } val minX = drops.minOf { it.x } val minY = drops.minOf { it.y } val minZ = drops.minOf { it.z } return drops.sumOf { lavaDrop -> lavaDrop.slideNeighbors().filter { !drops.contains(it) }.filter { airDrop -> var freeAirDrops = airDrop.slideNeighbors().filter { !drops.contains(it) }.toSet() val visitedDrops = mutableSetOf<Point3>() do { visitedDrops.addAll(freeAirDrops) freeAirDrops = freeAirDrops.flatMap { it.slideNeighbors() }.filter { !drops.contains(it) && !visitedDrops.contains(it) }.toSet() val isTrapped = freeAirDrops.all { it.x in minX..maxX && it.y in minY..maxY && it.z in minZ..maxZ} } while (freeAirDrops.isNotEmpty() && isTrapped) freeAirDrops.isNotEmpty() }.size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) } data class Point3(val x: Int, val y: Int, val z: Int) fun Point3.slideNeighbors(): List<Point3> { val (x, y, z) = this return listOf(Point3(x - 1, y, z), Point3(x + 1, y, z), Point3(x, y - 1, z), Point3(x, y + 1, z), Point3(x, y, z - 1), Point3(x, y, z + 1)) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
2,158
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/nl/tiemenschut/aoc/y2023/day7.kt
tschut
723,391,380
false
{"Kotlin": 61206}
package nl.tiemenschut.aoc.y2023 import nl.tiemenschut.aoc.lib.dsl.aoc import nl.tiemenschut.aoc.lib.dsl.day import nl.tiemenschut.aoc.lib.dsl.parser.InputParser import kotlin.math.pow fun Char.toCardValue(jValue: Int): Int { return when (this) { 'T' -> 10 'J' -> jValue 'Q' -> 12 'K' -> 13 'A' -> 14 else -> this.digitToInt() } } data class Hand(val cards: List<Int>) { fun score(): Int = ("${typeScore()}" + cards.joinToString("") { it.toString(16) }).toInt(16) fun scoreWithJs(): Int { if (cards.none { it == 1 }) return score() val options = listOf(2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14) val current = MutableList(cards.count { it == 1 }) { 0 } current[current.size - 1] = -1 var max = typeScore() do { fun addOne(index: Int) { if (index == -1) return if (current[index] == options.size - 1) { current[index] = 0 addOne(index - 1) } current[index] ++ } addOne(current.size - 1) val newCards = cards.toMutableList() for (i in current.indices) { newCards[newCards.indexOfFirst { it == 1 }] = options[current[i]] } max = max.coerceAtLeast(Hand(newCards).typeScore()) } while (current.any { it != options.size - 1 }) return ("$max" + cards.joinToString("") { it.toString(16) }).toInt(16) } private fun typeScore() = if (grouped.size == 1) 6 else if (grouped.maxBy { it.value }.value == 4) 5 else if (grouped.size == 2 && grouped.values.sorted() == listOf(2, 3)) 4 else if (grouped.size == 3 && grouped.values.sorted() == listOf(1, 1, 3)) 3 else if (grouped.size == 3 && grouped.values.sorted() == listOf(1, 2, 2)) 2 else if (grouped.size == 4) 1 else 0 private val grouped: Map<Int, Int> by lazy { cards.groupingBy { it }.eachCount() } } class HandsParser(private val jValue: Int) : InputParser<List<Pair<Hand, Int>>> { override fun parse(input: String): List<Pair<Hand, Int>> = input.split("\n").map { line -> val (hand, bid) = line.split(" ") Hand(hand.map { it.toCardValue(jValue) }) to bid.toInt() } } fun main() { aoc { puzzle { 2023 day 7 } part1 { input -> HandsParser(11).parse(input) .sortedBy { it.first.score() } .foldIndexed(0) { index, acc, pair -> acc + (index + 1) * pair.second } } part2 { input -> HandsParser(1).parse(input) .sortedBy { it.first.scoreWithJs() } .foldIndexed(0) { index, acc, pair -> acc + (index + 1) * pair.second } } } }
0
Kotlin
0
1
a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3
2,875
aoc-2023
The Unlicense
src/com/kingsleyadio/adventofcode/y2023/Day11.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput import java.util.* fun main() { part1() part2() } private fun part1() = fastEvaluate(2) private fun part2() = fastEvaluate(1_000_000) private fun fastEvaluate(expansion: Int) { val (world, planets) = buildModel(expansion) var sumOfDistances = 0L for (i in planets.indices) { val planet = planets[i] for (k in i + 1..planets.lastIndex) sumOfDistances += planet.fastDistanceTo(planets[k], world) } println(sumOfDistances) } private fun Index.fastDistanceTo(to: Index, world: List<IntArray>): Int { val xDistance = (minOf(x, to.x) + 1..maxOf(x, to.x)).sumOf { xi -> world[minOf(y, to.y)][xi].coerceAtLeast(1) } val yDistance = (minOf(y, to.y) + 1..maxOf(y, to.y)).sumOf { yi -> world[yi][minOf(x, to.x)].coerceAtLeast(1) } return xDistance + yDistance } private fun evaluate(expansion: Int) { val (world, planets) = buildModel(expansion) var sumOfDistances = 0L for (i in planets.indices) { val planet = planets[i] val paths = shortestPath(world, planet) for (k in i + 1..planets.lastIndex) { val second = planets[k] sumOfDistances += paths[second.y][second.x] } } println(sumOfDistances) } private fun shortestPath(world: List<IntArray>, start: Index): List<IntArray> { val plane = List(world.size) { IntArray(world.size) { Int.MAX_VALUE } } val queue = PriorityQueue<Path> { a, b -> a.cost - b.cost } queue.offer(Path(start, 0)) while (queue.isNotEmpty()) { val current = queue.poll() val (to, cost) = current if (plane[to.y][to.x] != Int.MAX_VALUE) continue plane[to.y][to.x] = cost sequence { for (y in -1..1) for (x in -1..1) { if (y != 0 && x != 0) continue val point = Index(to.x + x, to.y + y) val cell = plane.getOrNull(point.y)?.getOrNull(point.x) ?: continue if (cell == Int.MAX_VALUE) yield(point) } }.forEach { point -> val move = world[point.y][point.x].coerceAtLeast(1) queue.add(Path(point, cost + move)) } } return plane } private fun buildModel(expansion: Int): Pair<List<IntArray>, List<Index>> { return readInput(2023, 11, false).useLines { sequence -> val world = arrayListOf<IntArray>() for (line in sequence) { val values = IntArray(line.length) var space = 0 for (i in line.indices) { val char = line[i] val value = if (char == '#') 0 else 1 values[i] = value if (value > 0) space++ } if (space == values.size) for (i in values.indices) values[i] += expansion - 1 world.add(values) } for (i in world[0].indices) { val allSpaces = world.all { it[i] > 0 } if (allSpaces) for (j in world.indices) world[j][i] += expansion - 1 } val planetIndices = arrayListOf<Index>() for (j in world.indices) { val row = world[j] for (i in row.indices) { val value = row[i] if (value == 0) planetIndices.add(Index(i, j)) } } world to planetIndices } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
3,393
adventofcode
Apache License 2.0
src/Day04.kt
ktrom
573,216,321
false
{"Kotlin": 19490, "Rich Text Format": 2301}
fun main() { fun part1(input: List<String>): Int { return input.map { line -> val intervals: List<IntRange> = transformIntoIntervals(line) isSubInterval(intervals[0], intervals[1]) || isSubInterval(intervals[1], intervals[0]) }.sumOf { var hasSubInterval = 0 if (it) { hasSubInterval = 1 } hasSubInterval } } fun part2(input: List<String>): Int { return input.map { line -> val intervals: List<IntRange> = transformIntoIntervals(line) overlap(intervals[0], intervals[1]) }.sumOf { var hasOverlap = 0 if (it) { hasOverlap = 1 } hasOverlap } } // test if implementation meets criteria from the description val testInput = readInput("Day04_test") println(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) println(part2(testInput) == 4) println(part2(input)) } // takes a string of the form "x1-y1, x2-y2" and returns list of corresponding // int ranges, e.g. [[x1, y1 + 1], [x2, y2 + 1]] fun transformIntoIntervals(line: String): List<IntRange> { val ranges: List<String> = line.split(",") val intervals: List<IntRange> = ranges.map { val endpoints: List<Int> = it.split("-").map { it.toInt() } endpoints[0] until endpoints[1] + 1 } return intervals } // returns true if candidateSubInterval is a contained in interval fun isSubInterval(candidateSubInterval: IntRange, interval: IntRange): Boolean { return interval.first <= candidateSubInterval.first && candidateSubInterval.last <= interval.last } // returns true if the two ranges overlap fun overlap(range: IntRange, other: IntRange): Boolean { if (range.first < other.first) { if (range.last >= other.first) { return true } } if (other.first < range.first) { if (other.last >= range.first) { return true } } return isSubInterval(range, other) || isSubInterval(other, range) }
0
Kotlin
0
0
6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd
1,882
kotlin-advent-of-code
Apache License 2.0
src/Day08.kt
kmes055
577,555,032
false
{"Kotlin": 35314}
import kotlin.math.max fun main() { fun List<Int>.determine(): List<Boolean> { var curMax = -1 val asc = this.map { (it > curMax).apply { curMax = max(it, curMax) } } curMax = -1 val desc = this.reversed().map { (it > curMax).apply { curMax = max(it, curMax) } }.reversed() return (asc zip desc).map { (a, b) -> a or b } } fun part1(input: List<String>): Int { return input.map { it.map { c -> c.digitToInt() } } .let { matrix -> val horizonal = matrix.map { it.determine() } val vertical = matrix.transposed().map { it.determine() }.transposed() (horizonal zip vertical).map { (la, lb) -> (la zip lb).map { (a, b) -> a or b } } }.sumOf { it.count { b -> b } } } fun List<Int>.countTrees(value: Int): Int { return if (this.isEmpty()) 0 else this.takeWhile { it < value }.size.let { if (it == this.size) it else it + 1 } } fun calcDistance(line: List<Int>, position: Int): Int = (line.take(position).reversed().countTrees(line[position])) * (line.drop(position + 1).countTrees(line[position])) fun part2(input: List<String>): Int { val matrix = input.map { it.map { c ->c.digitToInt() } } val transposed = matrix.transposed() return (matrix.indices).maxOf { i -> (matrix[0].indices).maxOf { j -> calcDistance(matrix[i], j) * calcDistance(transposed[j], i) } } } val input = readInput("Day08") part1(input).println() part2(input).println() }
0
Kotlin
0
0
84c2107fd70305353d953e9d8ba86a1a3d12fe49
1,650
advent-of-code-kotlin
Apache License 2.0
src/day11/Code.kt
fcolasuonno
221,697,249
false
null
package day11 private val test = false fun main() { val parsed = if (test) listOf( setOf<Portable>(Microchip('H'), Microchip('L')), setOf<Portable>(Generator('H')), setOf<Portable>(Generator('L')), setOf<Portable>() ) else listOf( setOf<Portable>(Generator('T'), Microchip('T'), Generator('P'), Generator('S')), setOf<Portable>(Microchip('P'), Microchip('S')), setOf<Portable>(Generator('p'), Microchip('p'), Generator('R'), Microchip('R')), setOf<Portable>() ) println("Part 1 = ${solve(parsed)}") println("Part 2 = ${solve(parsed.mapIndexed { index, set -> if (index == 0) (set + setOf(Generator('E'), Microchip('E'), Generator('D'), Microchip('D'))) else set } )}") } interface Portable { val element: Char } private val Set<Portable>.compatible: Boolean get() = if (size <= 1) true else { val microchips = filterIsInstance<Microchip>().map { it.element } val generators = filterIsInstance<Generator>().map { it.element } generators.isEmpty() || microchips.minus(generators).isEmpty() } data class Microchip(override val element: Char) : Portable { override fun toString() = element + "M" } data class Generator(override val element: Char) : Portable { override fun toString() = element + "G" } data class Plan(val elevator: Int, val step: Int, val status: List<Set<Portable>>, val priority: Int) { override fun toString() = status.toString() val hash: String get() { val elementMap = mutableMapOf<Char, Int>() val mapIndexed = status.mapIndexed { index: Int, set: Set<Portable> -> index.toString() + set.map { (if (it is Generator) "G" else "M") + elementMap.getOrPut(it.element) { elementMap.size + 1 } }.sorted() }.joinToString() return elevator.toString() + mapIndexed } } fun solve(input: List<Set<Portable>>): Int { val seen = mutableSetOf<String>() val totalPortables = input.sumBy { it.size } val toVisit = mutableListOf(Plan(0, 0, input, 0)).toSortedSet( compareByDescending<Plan> { it.priority }.thenBy { it.step }.thenBy { it.hash }) while (toVisit.isNotEmpty()) { val currentPlan = toVisit.first() toVisit.remove(currentPlan) seen.add(currentPlan.hash) if (currentPlan.status[3].size == totalPortables) { return currentPlan.step } else { val currentFloor = currentPlan.elevator val items = currentPlan.status[currentFloor] val up2 = items.flatMap { item -> items.filter { it != item }.map { setOf(it, item) } } .map { carried -> carried to items - carried } .filter { (_, left) -> left.compatible }.mapNotNull { (carried, left) -> currentPlan.status.getOrNull(currentFloor + 1)?.let { (it + carried).takeIf { it.compatible }?.let { new -> Plan(currentFloor + 1, currentPlan.step + 1, currentPlan.status.mapIndexed { index, set -> when (index) { currentFloor -> left currentFloor + 1 -> new else -> set } }, 3) } } }.filter { it.hash !in seen } val up = items.map { setOf(it) } .map { carried -> carried to items - carried } .filter { (_, left) -> left.compatible }.mapNotNull { (carried, left) -> currentPlan.status.getOrNull(currentFloor + 1)?.let { (it + carried).takeIf { it.compatible }?.let { new -> Plan(currentFloor + 1, currentPlan.step + 1, currentPlan.status.mapIndexed { index, set -> when (index) { currentFloor -> left currentFloor + 1 -> new else -> set } }, 2) } } }.filter { it.hash !in seen } val down = items.map { setOf(it) } .map { carried -> carried to items - carried } .filter { (_, left) -> left.compatible }.mapNotNull { (carried, left) -> currentPlan.status.getOrNull(currentFloor - 1)?.let { (it + carried).takeIf { it.compatible }?.let { new -> Plan(currentFloor - 1, currentPlan.step + 1, currentPlan.status.mapIndexed { index, set -> when (index) { currentFloor -> left currentFloor - 1 -> new else -> set } }, 1) } } }.filter { it.hash !in seen } val down2 = items.flatMap { item -> items.filter { it != item }.map { setOf(it, item) } } .map { carried -> carried to items - carried } .filter { (_, left) -> left.compatible }.mapNotNull { (carried, left) -> currentPlan.status.getOrNull(currentFloor - 1)?.let { (it + carried).takeIf { it.compatible }?.let { new -> Plan(currentFloor - 1, currentPlan.step + 1, currentPlan.status.mapIndexed { index, set -> when (index) { currentFloor -> left currentFloor - 1 -> new else -> set } }, 0) } } }.filter { it.hash !in seen } toVisit.addAll(up) toVisit.addAll(up2) down.takeIf { (0 until currentFloor).any { currentPlan.status[it].isNotEmpty() } }?.let { toVisit.addAll(it) } down2.takeIf { (0 until currentFloor).any { currentPlan.status[it].isNotEmpty() } }?.let { toVisit.addAll(it) } } } return Int.MAX_VALUE }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
6,709
AOC2016
MIT License
src/day13/Day13.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day13 import readInput fun main() { part1() part2() } data class Thing(val isInt: Boolean, val int: Int = -1, val list: List<Thing> = emptyList()) : Comparable<Thing> { override fun compareTo(other: Thing): Int { if (isInt && other.isInt) return int - other.int if (isInt) return Thing(false, list = listOf(Thing(true, int = int))).compareTo(other) if (other.isInt) return compareTo(Thing(false, list = listOf(Thing(true, int = other.int)))) for (i in 0..minOf(list.lastIndex, other.list.lastIndex)) { val compared = list[i].compareTo(other.list[i]) if (compared != 0) return compared } return list.size - other.list.size } } fun getTheListOfThings(from: String): List<Thing> { val asList = from.toMutableList() var bracketCount = 0 for ((i, c) in asList.withIndex()) { if (c == '[') bracketCount++ if (c == ']') bracketCount-- if (c == ',' && bracketCount == 1) asList[i] = '!' } return asList.joinToString("").removeSurrounding("[", "]").split("!").takeIf { !(it.size == 1 && it[0] == "") } ?.map { if (it.startsWith('[')) Thing(false, list = getTheListOfThings(it)) else Thing(true, int = it.toInt()) } ?: emptyList() } fun part1() { val input = readInput(13) val allTheThings = mutableListOf<List<Thing>>() for (line in input) if (line.isNotBlank()) allTheThings += getTheListOfThings(line) var total = 0 for (i in 0 until allTheThings.size / 2) { val thing1 = allTheThings[i * 2] val thing2 = allTheThings[i * 2 + 1] if (Thing(false, list = thing1) < Thing(false, list = thing2)) total += i + 1 } println(total) } fun part2() { val input = readInput(13) val allTheThings = mutableListOf( listOf(Thing(false, list = listOf(Thing(true, int = 2)))), listOf(Thing(false, list = listOf(Thing(true, int = 6)))) ) for (line in input) if (line.isNotBlank()) allTheThings += getTheListOfThings(line) var total = 1 allTheThings.map { Thing(false, list = it) }.sorted().forEachIndexed { index, thing -> if ("$thing" == "${Thing(false, list = listOf(Thing(false, list = listOf(Thing(true, int = 2)))))}" || "$thing" == "${Thing(false, list = listOf(Thing(false, list = listOf(Thing(true, int = 6)))))}" ) { total *= index + 1 } } println(total) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
2,450
advent-of-code-2022
Apache License 2.0
src/Day11.kt
zfz7
573,100,794
false
{"Kotlin": 53499}
fun main() { println(day11A(parseMonkeys(readFile("Day11")))) println(day11B(parseMonkeys(readFile("Day11")))) } fun parseMonkeys(input: String): List<Monkey> = input.split("\n\n").map { mk -> Monkey( items = mk.split("\n").filter{ it.contains("Starting items: ")}[0].split(" Starting items: ",", ").mapNotNull{it.toLongOrNull()}.toMutableList(), op = { item: Long -> val line = mk.split("\n").filter{ it.contains("Operation: new = ")}[0].split(" ") when(line[6]){ "+" -> item + (line[7].toLongOrNull() ?: item) "-" -> item - (line[7].toLongOrNull() ?: item) "/" -> item / (line[7].toLongOrNull() ?: item) "*" -> item * (line[7].toLongOrNull() ?: item) else -> throw Exception("help") } }, divider = mk.split("\n").filter{ it.contains("Test: divisible by ")}[0].split("Test: divisible by ")[1].toLong(), pass = mk.split("\n").filter{ it.contains("If true: throw to monkey ")}[0].split("If true: throw to monkey ")[1].toInt(), fail = mk.split("\n").filter{ it.contains("If false: throw to monkey ")}[0].split("If false: throw to monkey ")[1].toInt(), ) } fun day11A(monkeys: List<Monkey>): Long { repeat(20) { monkeys.forEach { it.inspectAll(monkeys) } } // monkeys.forEachIndexed { idx, monkey -> // println("Round 20 Monkey $idx items ${monkey.items} inspected ${monkey.count}") // } return monkeys.map { it.count }.sorted().reversed().take(2).fold(1L) { acc, it -> acc * it } } fun day11B(mkys: List<Monkey>): Long { val monkeys = mkys.map { it.copy(worry = true) } repeat(10000) { monkeys.forEach { it.inspectAll(monkeys) } } // monkeys.forEachIndexed { idx, monkey -> // println("Monkey $idx inspected ${monkey.count} ${monkey.items}") // } return monkeys.map { it.count }.sorted().reversed().take(2).fold(1L) { acc, it -> acc * it } } data class Monkey( val items: MutableList<Long>, private val op: (item: Long) -> Long, private val divider: Long, private val pass: Int, private val fail: Int, private val worry: Boolean = false ) { var count: Long = 0 fun inspectAll(monkeys: List<Monkey>) { items.forEach { item -> val x: Long = if (worry) op(item) % monkeys.map { it.divider }.reduce{ acc, crr -> acc * crr } else op(item) / 3L if (test(x)) { monkeys[pass].add(x) } else { monkeys[fail].add(x) } // println("item $item op ${x} test ${test(op(item))} true $pass false $fail") count++ } items.clear() } private fun add(item: Long) { items.add(item) } private fun test(x: Long): Boolean = ((x % divider) == 0L) }
0
Kotlin
0
0
c50a12b52127eba3f5706de775a350b1568127ae
2,973
AdventOfCode22
Apache License 2.0
day-09/src/main/kotlin/SmokeBasin2nd.kt
diogomr
433,940,168
false
{"Kotlin": 92651}
fun main() { println("Part One Solution: ${partOne()}") println("Part Two Solution: ${partTwo()}") } private fun partOne(): Int { val map = readMap() return map.keys .filter { it.isLowestOfSurroundingPoints(map) } .sumOf { map[it]!! + 1 } } private fun partTwo(): Long { val map = readMap() return map.keys.asSequence() .filter { it.isLowestOfSurroundingPoints(map) } .map { computeBasinSize(it, map, mutableSetOf()) } .sortedDescending() .take(3) .reduce { acc, it -> acc * it } } fun computeBasinSize(point: Point, map: Map<Point, Int>, visited: MutableSet<Point>): Long { if (!visited.add(point)) return 0 return 1 + point.findPointsInBasin(map).sumOf { computeBasinSize(it, map, visited) } } private fun readMap(): Map<Point, Int> { return readInputLines() .filter { it.isNotBlank() } .flatMapIndexed { column, line -> line.split("") .filter { it.isNotBlank() } .mapIndexed { row, value -> Pair(Point(row, column), value.toInt()) } } .toMap() } data class Point( val x: Int, val y: Int, ) { fun findPointsInBasin(map: Map<Point, Int>): Set<Point> { val pointValue = map[this]!! return getValidSurroundingPoints(map) .filter { map[it]!! > pointValue && map[it]!! != 9 } .toSet() } fun isLowestOfSurroundingPoints(map: Map<Point, Int>): Boolean { val pointValue = map[this]!! return getValidSurroundingPoints(map).all { map[it]!! > pointValue } } private fun getValidSurroundingPoints(map: Map<Point, Int>) = getSurroundingPoints() .filter { it.existsInMap(map) } .toSet() private fun existsInMap(map: Map<Point, Int>) = map[this] != null private fun getSurroundingPoints() = setOf( this.copy(x = x - 1), this.copy(x = x + 1), this.copy(y = y - 1), this.copy(y = y + 1), ) }
0
Kotlin
0
0
17af21b269739e04480cc2595f706254bc455008
2,096
aoc-2021
MIT License
src/Day13.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
import java.util.* fun main() { fun decode(input: String): List<Any> { var groupStack = Stack<Int>() var numberQueue: Queue<Int> = LinkedList<Int>() var parts = mutableListOf<String>() val inner = input.substring(1, input.length - 1) inner.forEachIndexed { i, ch -> if (ch == '[') { groupStack.add(i) } else if (ch == ']') { val j = groupStack.pop() if (groupStack.isEmpty()) { parts.add(inner.substring(j, i + 1)) return@forEachIndexed } } if (groupStack.isNotEmpty()) return@forEachIndexed if (ch != ',') numberQueue.add(i) if (ch == ',' || i == inner.length - 1) { if (numberQueue.isEmpty()) return@forEachIndexed val j = numberQueue.first() parts.add(inner.substring(j, if (ch == ',') i else i + 1)) numberQueue.clear() } } return parts.map { if (it[0] == '[') decode(it) else it.toInt() } } fun inRightOrder(pair: Pair<List<Any>, List<Any>>): Int { pair.first.forEachIndexed { i, left -> if (i >= pair.second.size) return -1 val right = pair.second[i] val res = when { left is Int && right is Int -> if (left < right) 1 else if (left > right) -1 else 0 left is List<*> && right is List<*> -> inRightOrder(Pair(left as List<Any>, right as List<Any>)) left is Int && right is List<*> -> inRightOrder(Pair(listOf(left), right as List<Any>)) left is List<*> && right is Int -> inRightOrder(Pair(left as List<Any>, listOf(right))) else -> 0 } if (res != 0) return res } return if (pair.first.size < pair.second.size) 1 else 0 } fun part1(input: List<String>): Int = input.chunkedBy { it == "" } .map { inRightOrder(Pair(decode(it[0]), decode(it[1]))) } .mapIndexed { i, v -> Pair(i + 1, v) } .filter { it.second == 1 } .sumOf { it.first } fun part2(input: List<String>) = input.filter { it != "" }.run { this + listOf("[[2]]", "[[6]]") }.map { Pair(it, decode(it)) } .sortedWith { left, right -> inRightOrder(Pair(left.second, right.second)) } .asReversed() .run { val a = this.indexOfFirst { it.first == "[[2]]" } + 1 var b = this.indexOfFirst { it.first == "[[6]]" } + 1 a * b } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") check(part1(input) == 5808) println(part1(input)) check(part2(input) == 22713) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
2,991
advent-of-code-kotlin-2022
Apache License 2.0
src/Day07.kt
timj11dude
572,900,585
false
{"Kotlin": 15953}
sealed class Node sealed class Container : Node() object Root : Container() data class Folder(val name: String, val container: Container) : Container() data class File(val size: Int) : Node() fun main() { fun Map<Container, List<Node>>.update(current: Container, node: Node) = (this + (current to ((this[current] ?: emptyList()) + node))) fun readInput(input: Collection<String>): Map<Container, List<Node>> { return input.fold(emptyMap<Container, List<Node>>() to emptyList<Container>()) { (reg, stack), entry -> when { entry == "$ cd /" -> reg to listOf(Root) entry.startsWith("$ cd ..") -> reg to (stack.dropLast(1)) entry.startsWith("$ cd") -> reg to (stack + Folder(entry.drop(5), stack.last())) entry.startsWith("$ ls") -> reg to stack entry.startsWith("dir ") -> reg.update(stack.last(), Folder(entry.drop(4), stack.last())) to stack else -> reg.update(stack.last(), File(entry.takeWhile { it.isDigit() }.toInt())) to stack } }.first } class FS(map: Map<Container, List<Node>>) { private val computedFolderSize: MutableMap<Container, Int> = mutableMapOf() init { var previousDiff = 0 while (computedFolderSize.size != map.size) { val newDiff = map.size - computedFolderSize.size if (newDiff == previousDiff) { throw IllegalStateException("Failed to reduce diff") } previousDiff = newDiff map.forEach { (k, v) -> if (!computedFolderSize.containsKey(k) && (v.all { it is File } || computedFolderSize.keys.containsAll(v.filterIsInstance<Folder>()))) { computedFolderSize[k] = v.sumOf { when (it) { is File -> it.size is Folder -> computedFolderSize[it]!! is Root -> throw IllegalArgumentException("Root is not contained by anything else") } } } } } } fun getFolderSizes() = computedFolderSize.toMap() } fun part1(input: Collection<String>): Int { val parsedInput = readInput(input) val fs = FS(parsedInput) val folderSizes = fs.getFolderSizes() return folderSizes.values.filter { it <= 100000 }.sum() } fun part2(input: Collection<String>): Int { val folderSizes = FS(readInput(input)).getFolderSizes() val totalSpace = 70000000 val spaceRequired = 30000000 val remainingSpace = totalSpace - folderSizes[Root]!! val needAdditional = spaceRequired - remainingSpace return folderSizes.values.filter { it >= needAdditional }.minOf { it } } // 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
28aa4518ea861bd1b60463b23def22e70b1ed481
3,212
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day12/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day12 import java.io.File import java.util.PriorityQueue data class Hill(val row: Int, val col: Int, val height: Int) class Terrain(private val hills: List<List<Hill>>, val start: Hill, val end: Hill) { companion object { fun parse(str: String): Terrain { lateinit var start: Hill lateinit var end: Hill val hills = str.split("\n").mapIndexed { rowIdx, row -> row.mapIndexed { colIdx, char -> val heightChar = if (char == 'S') 'a' else if (char == 'E') 'z' else char val hill = Hill(rowIdx, colIdx, heightMap.getValue(heightChar)) if (char == 'S') start = hill if (char == 'E') end = hill hill } } return Terrain(hills, start, end) } } fun possibleNeighbours(hill: Hill): List<Hill> { val (row, col, height) = hill return listOf( row - 1 to col, row + 1 to col, row to col - 1, row to col + 1 ).mapNotNull { (r, c) -> hills.getOrNull(r)?.getOrNull(c) } .filter { it.height <= height + 1 } } fun hillsOfHeight(height: Int): List<Hill> { return hills.flatten().filter { it.height == height } } } val heightMap = ('a'..'z').withIndex().associate { it.value to it.index + 1 } fun main() { val hills = File("src/main/kotlin/com/anahoret/aoc2022/day12/input.txt") .readText() .trim() .let(Terrain.Companion::parse) // Part 1 part1(hills) // Part 2 part2(hills) } private fun part1(terrain: Terrain) { println(shortestPathLength(terrain, terrain.start, terrain.end)) } private fun part2(terrain: Terrain) { terrain.hillsOfHeight(1) .mapNotNull { hill -> shortestPathLength(terrain, start = hill, end = terrain.end) } .min() .let(::println) } data class Path(private val hills: List<Hill>, val cost: Int) : Comparable<Path> { constructor(start: Hill) : this(listOf(start), 0) val end = hills.last() operator fun plus(hill: Hill): Path { return copy(hills = hills + hill, cost = cost + 1) } override fun compareTo(other: Path): Int { return cost.compareTo(other.cost) } } fun shortestPathLength(terrain: Terrain, start: Hill, end: Hill): Int? { val paths = PriorityQueue<Path>() paths += Path(start) val visited = mutableSetOf<Hill>() var path = paths.poll() while (path.end != end) { terrain.possibleNeighbours(path.end) .filterNot(visited::contains) .also(visited::addAll) .forEach { paths += path + it } if (paths.isEmpty()) break path = paths.poll() } if (path.end != end) return null return path.cost }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
2,883
advent-of-code-2022
Apache License 2.0
src/Day08.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
fun main() { fun parse(input: List<String>) = input.map { it.map(Char::digitToInt) } fun List<List<Int>>.top(colRow: Pair<Int, Int>) = (colRow.first - 1 downTo 0).map { this[it][colRow.second] } fun List<List<Int>>.bottom(colRow: Pair<Int, Int>) = (colRow.first + 1 .. lastIndex).map { this[it][colRow.second] } fun List<List<Int>>.left(colRow: Pair<Int, Int>) = (colRow.second - 1 downTo 0).map { this[colRow.first][it] } fun List<List<Int>>.right(colRow: Pair<Int, Int>) = (colRow.second + 1 .. this[colRow.first].lastIndex).map { this[colRow.first][it] } fun List<List<Int>>.isVisible(colRow: Pair<Int, Int>): Boolean { val height = this[colRow.first][colRow.second] return top(colRow).all { it < height } || bottom(colRow).all { it < height } || left(colRow).all { it < height } || right(colRow).all { it < height } } fun maxByDirection(height: Int, direction: List<Int>) = direction.indexOfFirst { it >= height }.let { if (it == -1) direction.size else it + 1 } fun List<List<Int>>.viewScore(colRow: Pair<Int, Int>): Int { val height = this[colRow.first][colRow.second] return maxByDirection(height, top(colRow)) * maxByDirection(height, bottom(colRow)) * maxByDirection(height, left(colRow)) * maxByDirection(height, right(colRow)) } fun List<List<Int>>.iterate() = (0..lastIndex).asSequence().flatMap { col -> (0..this[col].lastIndex).asSequence().map { row -> col to row } } fun part1(input: List<String>) = parse(input).let { trees -> trees.iterate().count(trees::isVisible) } fun part2(input: List<String>) = parse(input).let { trees -> trees.iterate().maxOf(trees::viewScore) } val input = readInput("day8") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
1,931
advent-of-code-2022
Apache License 2.0
src/twentytwo/Day04.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentytwo fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day04_test") println(part1(testInput)) check(part1(testInput) == 2) println(part2(testInput)) check(part2(testInput) == 4) println("---") val input = readInputLines("Day04_input") println(part1(input)) println(part2(input)) testAlternativeSolutions() } private fun part1(input: List<String>): Int { val pairContains = input.map { elfPair -> val (firstElf, secondElf) = elfPair.split(',') val (firstStart, firstEnd) = firstElf.split('-').map { it.toInt() } val (secondStart, secondEnd) = secondElf.split('-').map { it.toInt() } (firstStart <= secondStart && firstEnd >= secondEnd) || (secondStart <= firstStart && secondEnd >= firstEnd) } return pairContains.count { it } } private fun part2(input: List<String>): Int { val pairContains = input.map { elfPair -> val (firstElf, secondElf) = elfPair.split(',') val (firstStart, firstEnd) = firstElf.split('-').map { it.toInt() } val (secondStart, secondEnd) = secondElf.split('-').map { it.toInt() } secondStart in firstStart..firstEnd || secondEnd in firstStart .. firstEnd || firstStart in secondStart..secondEnd || firstEnd in secondStart .. secondEnd } return pairContains.count { it } } // ------------------------------------------------------------------------------------------------ private fun testAlternativeSolutions() { val testInput = readInputLines("Day04_test") check(part1AlternativeSolution(testInput) == 2) check(part2AlternativeSolution(testInput) == 4) println("Alternative Solutions:") val input = readInputLines("Day04_input") println(part1AlternativeSolution(input)) println(part2AlternativeSolution(input)) } private fun part1AlternativeSolution(input: List<String>): Int { return input .map { it.toRanges() } .map { it.first fullyContains it.second || it.second fullyContains it.first } .count { it } } private fun part2AlternativeSolution(input: List<String>): Int { return input .map { it.toRanges() } .map { it.first overlaps it.second } .count { it } } private fun String.toRanges(): Pair<IntRange, IntRange> { return this .let { it.substringBefore(",") to it.substringAfter(",") } .let { pair -> pair.onEach { val start = it.substringBefore("-").toInt() val end = it.substringAfter("-").toInt() IntRange(start, end) } } } private fun <T, R> Pair<T, T>.onEach(transform: (T) -> R): Pair<R, R> { return Pair(transform(this.first), transform(this.second)) } private infix fun IntRange.fullyContains(other: IntRange): Boolean { return this.all { it in other } } private infix fun IntRange.overlaps(other: IntRange): Boolean { return this.any { it in other } }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
3,030
advent-of-code-solutions
Apache License 2.0
src/main/kotlin/mkuhn/aoc/Day13.kt
mtkuhn
572,236,871
false
{"Kotlin": 53161}
package mkuhn.aoc import mkuhn.aoc.util.readInput import mkuhn.aoc.util.splitList fun main() { val input = readInput("Day13") println(day13part1(input)) println(day13part2(input)) } fun day13part1(input: List<String>): Int = input.splitList("").asSequence() .map { l -> l.map { parseNestedListsOfInt(it.drop(1).dropLast(1)) } } .map { p -> p[0].comparePacketOrder(p[1]) == -1 } .withIndex() .filter { it.value } .sumOf { it.index+1 } fun day13part2(input: List<String>): Int { val dividerPackets = listOf(listOf(listOf(2)), listOf(listOf(6))) return input.asSequence() .filter { it.isNotEmpty() } .map { l -> parseNestedListsOfInt(l.drop(1).dropLast(1)) } .plus(dividerPackets) .sortedWith(Any::comparePacketOrder) .withIndex() .filter { it.value in dividerPackets } .fold(1) { acc, i -> acc*(i.index+1) } } fun parseNestedListsOfInt(line: String): List<Any> { if (line.isEmpty()) return emptyList() var nestingLevel = 0 val nestingChars = line.map { c -> if (c == '[') nestingLevel++ else if (c == ']') nestingLevel-- c to nestingLevel } return nestingChars.splitList(',' to 0).map { p -> p.map { it.first } .joinToString("") .let { it.toIntOrNull() ?: parseNestedListsOfInt(it.drop(1).dropLast(1)) } } } fun Any.comparePacketOrder(right: Any) = if(this is Int && right is Int) { compareTo(right) } else if (this is List<*> && right is List<*>) { comparePacketListOrder(right) } else { this.listIfNotList().comparePacketListOrder(right.listIfNotList()) } fun Any.listIfNotList() = if(this is Int) listOf(this) else this as List<*> fun List<*>.comparePacketListOrder(right: List<*>): Int = this.zip(right) .map { it.first!!.comparePacketOrder(it.second!!) } //hold my beer .firstOrNull { it != 0 } ?:this.size.compareTo(right.size)
0
Kotlin
0
1
89138e33bb269f8e0ef99a4be2c029065b69bc5c
1,982
advent-of-code-2022
Apache License 2.0
src/main/day15/Part1.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day15 import common.Point import readInput import kotlin.math.abs fun main() { val sensors = parseInput(readInput("day15/input.txt")) val rowToCheck = 2000000 val beaconsInRow = sensors.map { it.beacon }.filter { it.y == rowToCheck }.distinct().count() val positionsWithNoBeacon = coveredRowPositions(sensors, rowToCheck) .sumOf { it.count() } - beaconsInRow println("Day 15 part 1. Positions with no beacons: $positionsWithNoBeacon") } fun coveredRowPositions(sensors: List<Sensor>, rowToCheck: Int): List<IntRange> { return sensors .map { it.rowCoverage(rowToCheck) } .filterNotNull() .fold(listOf()) { acc, rowCoverage -> merge(buildList { addAll(acc) add(rowCoverage) }) } } fun merge(ranges: List<IntRange>): List<IntRange> { if(ranges.size == 1) return ranges val toCheck = ranges.first() val overlapping = ranges.drop(1).filter { it.overlapsOrAdjoins(toCheck) } val notOverlapping = ranges.drop(1).filter { !it.overlapsOrAdjoins(toCheck) } return if(overlapping.isEmpty()) { listOf(listOf(toCheck), merge(ranges.drop(1))).flatten() } else { val merged = overlapping.fold(toCheck) { acc, value -> acc.merge(value) } return merge(listOf(listOf(merged), notOverlapping).flatten()) } } fun parseInput(input: List<String>): List<Sensor> { val pattern = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") return input .map{ pattern.find(it)!!.destructured } .map { (sensorX, sensorY, beaconX, beaconY) -> Sensor(Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt())) } } data class Sensor(val position: Point, val beacon: Point) { fun rowCoverage(yValue: Int): IntRange? { val horizontalReach = position.manhattanDistance(beacon) - abs(position.y - yValue) return if(horizontalReach > 0) { IntRange(position.x - horizontalReach, position.x + horizontalReach) } else { null } } } private infix fun IntRange.overlapsOrAdjoins(other: IntRange): Boolean = (first <= other.last && other.first <= last) || last + 1 == other.first || other.last + 1 == first private infix fun IntRange.merge(other: IntRange): IntRange { return IntRange(minOf(first, other.first), maxOf(last, other.last)) }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
2,433
aoc2022
Apache License 2.0
src/Day08.kt
WhatDo
572,393,865
false
{"Kotlin": 24776}
import kotlin.math.abs import kotlin.math.sign fun main() { val input = readInput("Day08") val grid = Grid.create(input) val visibleTrees = grid.map.entries.filter { entry -> entry.isVisibleIn(grid) } println("visible tree count ${visibleTrees.size}") val bestScenic = grid.map.entries.maxBy { it.scenicScore(grid) } val score = bestScenic.scenicScore(grid) println("best scenic tree is $bestScenic with score $score") } private fun TreeEntry.lookOut(grid: Grid): Array<List<Vec2>> { val (x, y) = key val left = (x - 1) downTo 1 val right = (x + 1)..grid.size.first val up = (y - 1) downTo 1 val down = (y + 1)..grid.size.second return arrayOf(left.map { it to y }, right.map { it to y }, up.map { x to it }, down.map { x to it }) } private fun TreeEntry.scenicScore(grid: Grid): Int { val directions = lookOut(grid) return directions.fold(1) { acc, direction -> var index = direction.indexOfFirst { vec -> grid.map[vec].let { tree -> tree == null || tree >= value } } if (index == -1) { index = if (direction.isNotEmpty()) { val (lastX, lastY) = direction.last() abs(lastX - key.first) + abs(lastY - key.second) } else { 0 } } else { index++ } acc * index } } private fun TreeEntry.isVisibleIn(grid: Grid): Boolean { val directions = lookOut(grid) val treeHeight = value return directions.any { trees -> trees.all { tree -> grid.map[tree].let { it == null || key == tree || it < treeHeight } } } } typealias TreeMap = Map<Vec2, Int> typealias TreeEntry = Map.Entry<Vec2, Int> private class Grid(val map: TreeMap, val size: Vec2) { companion object { fun create(input: List<String>): Grid { val map = input.withIndex().flatMap { row -> row.value.withIndex().map { col -> (col.index + 1 to row.index + 1) to col.value.digitToInt() } }.toMap() val height = input.size val width = input[0].length return Grid(map, width to height) } } }
0
Kotlin
0
0
94abea885a59d0aa3873645d4c5cefc2d36d27cf
2,173
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/com/dr206/2022/Day02.kt
dr206
572,377,838
false
{"Kotlin": 9200}
fun main() { fun part1(input: List<String>): Int { val strategyGuide = input .pairs<String>(" ") .map { Pair(it.first.toHand(), it.second.toHand()) } return strategyGuide.sumOf { getTotalPerHand(it) } } fun part2(input: List<String>): Int { val strategyGuide = input .pairs<String>(" ") .map { outcomeToHand(it) } return strategyGuide.sumOf { getTotalPerHand(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput).also { println("Test part 1: $it") } == 15) check(part2(testInput).also { println("Test part 2: $it") } == 12) val input = readInput("Day02") println("Part 1 ${part1(input)}") println("Part 2 ${part2(input)}") } enum class Hand(yours: String, val mine: String, val score: Int) { ROCK("X", "A", 1), PAPER("Y", "B", 2), SCISSORS("Z", "C", 3) } val beats = mapOf( Hand.ROCK to Hand.SCISSORS, Hand.PAPER to Hand.ROCK, Hand.SCISSORS to Hand.PAPER ) fun matchOutcome(mine: Hand, yours: Hand) = when (yours) { mine -> 0 beats[mine] -> 1 else -> -1 } fun getTotalPerHand(p: Pair<Hand, Hand>) = 3*(1 + matchOutcome(p.second, p.first)) + p.second.score fun String.toHand() = when(this) { "X", "A" -> Hand.ROCK "Y", "B" -> Hand.PAPER else -> Hand.SCISSORS } fun outcomeToHand(p: Pair<String, String>): Pair<Hand, Hand> = when(p.second) { // Lose "X" -> Pair(p.first.toHand(), beats[p.first.toHand()]!!) // Draw "Y" -> Pair(p.first.toHand(), p.first.toHand()) // Wim else -> Pair(p.first.toHand(), beats.entries.first { it.value == p.first.toHand() }.key) }
0
Kotlin
0
0
57b2e7227d992de87a51094a971e952b3774fd11
1,751
advent-of-code-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day08.kt
Kebaan
573,069,009
false
null
package days import days.Day08.Tree import utils.Day import utils.Point import utils.readInput import utils.takeUntil fun main() { Day08.solve() } private typealias Forest = List<List<Tree>> object Day08 : Day<Int>(2022, 8) { data class Tree(val location: Point, val height: Int) { fun visibleThrough(direction: List<Tree>) = direction.all { it.height < height } } private fun Forest.leftTrees(tree: Tree) = (tree.location.x - 1 downTo 0).map { x -> this[x][tree.location.y] } private fun Forest.rightTrees(tree: Tree) = (tree.location.x + 1 until this.size).map { x -> this[x][tree.location.y] } private fun Forest.topTrees(tree: Tree) = (tree.location.y - 1 downTo 0).map { y -> this[tree.location.x][y] } private fun Forest.bottomTrees(tree: Tree) = (tree.location.y + 1 until this[tree.location.x].size).map { y -> this[tree.location.x][y] } private fun Forest.isVisible(tree: Tree): Boolean { return when { tree.location.x == 0 || tree.location.x == this.size -> true tree.location.y == 0 || tree.location.y == this[tree.location.x].size -> true tree.visibleThrough(leftTrees(tree)) -> true tree.visibleThrough(rightTrees(tree)) -> true tree.visibleThrough(topTrees(tree)) -> true tree.visibleThrough(bottomTrees(tree)) -> true else -> return false } } private fun Forest.scenicScore(tree: Tree): Int { when { tree.location.x == 0 || tree.location.x == this.size - 1 -> return 0 tree.location.y == 0 || tree.location.y == this[tree.location.x].size - 1 -> return 0 } val visibleLeft = leftTrees(tree).takeUntil { it.height >= tree.height } val visibleRight = rightTrees(tree).takeUntil { it.height >= tree.height } val visibleUp = topTrees(tree).takeUntil { it.height >= tree.height } val visibleDown = bottomTrees(tree).takeUntil { it.height >= tree.height } return visibleLeft.size * visibleRight.size * visibleUp.size * visibleDown.size } private fun parseForest(input: List<String>) = input .mapIndexed { x, row -> row.mapIndexed { y, tree -> Tree(Point(x, y), tree.digitToInt()) } } override fun part1(input: List<String>): Int { val forest = parseForest(input) return forest.sumOf { row -> row.count { tree -> forest.isVisible(tree) } } } override fun part2(input: List<String>): Int { val forest = parseForest(input) val scores = forest.flatMap { row -> row.map { tree -> forest.scenicScore(tree) } } return scores.max() } override fun doSolve() { val input = readInput(2022, 8) part1(input).let { println(it) check(it == 1763) } part2(input).let { println(it) check(it == 671160) } } override val testInput = """ 30373 25512 65332 33549 35390""".trimIndent().lines() }
0
Kotlin
0
0
ef8bba36fedbcc93698f3335fbb5a69074b40da2
3,220
Advent-of-Code-2022
Apache License 2.0
src/Day08.kt
ekgame
573,100,811
false
{"Kotlin": 20661}
fun main() { data class Tree(val size: Int, var visible: Boolean = false) data class TreeGrid(val trees: Array<Array<Tree>>) { val height = trees.size val width = trees.first().size fun getHorizontalSequence(index: Int) = trees[index].toList() fun getVerticalSequence(index: Int) = (0 until height).map { trees[it][index] } fun processLineVisibility(sequence: Iterable<Tree>) { var currentSize = -1 sequence.forEach { if (it.size > currentSize) { it.visible = true currentSize = it.size } } } fun processVisibility() { repeat(height) { processLineVisibility(getHorizontalSequence(it)) processLineVisibility(getHorizontalSequence(it).reversed()) } repeat(width) { processLineVisibility(getVerticalSequence(it)) processLineVisibility(getVerticalSequence(it).reversed()) } } fun getScenicScore(tower: Tree, sequence: List<Tree>): Int { if (sequence.isEmpty()) return 0 val visibleTrees = sequence.takeWhile { it.size < tower.size }.count() return (visibleTrees + 1).coerceAtMost(sequence.size) } fun getScenicScoreAt(x: Int, y: Int): Int { if (x == 0 || y == 0 || x == width - 1 || y == height - 1) { return 0 } val tower = trees[y][x] val horizontal = getHorizontalSequence(y) val vertical = getVerticalSequence(x) val leftScore = getScenicScore(tower, horizontal.subList(0, x).reversed()) val rightScore = getScenicScore(tower, horizontal.subList(x + 1, width)) val upScore = getScenicScore(tower, vertical.subList(0, y).reversed()) val downScore = getScenicScore(tower, vertical.subList(y + 1, height)) return leftScore * rightScore * upScore * downScore } } fun parseTreeGrid(input: List<String>) = TreeGrid(Array(input.size) { line -> input[line].map { Tree(it.digitToInt()) }.toTypedArray() }) fun <T> cartesianSequence(first: List<T>, second: List<T>) = sequence { first.forEach { x -> second.forEach { y -> yield(x to y) } } } fun part1(input: List<String>): Int { val grid = parseTreeGrid(input) grid.processVisibility() return grid.trees.flatten().count { it.visible } } fun part2(input: List<String>): Int { val grid = parseTreeGrid(input) return cartesianSequence((0 until grid.width).toList(), (0 until grid.height).toList()) .maxOf { (x, y) -> grid.getScenicScoreAt(x, y) } } val testInput = readInput("08.test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
0c2a68cedfa5a0579292248aba8c73ad779430cd
3,029
advent-of-code-2022
Apache License 2.0
src/Day13.kt
azat-ismagilov
573,217,326
false
{"Kotlin": 75114}
sealed interface DistressSignal : Comparable<DistressSignal> { override operator fun compareTo(other: DistressSignal): Int companion object { fun of(string: String): DistressSignal = if (string.startsWith('[')) DistressList.of(string) else DistressInt.of(string) } } data class DistressList(val content: List<DistressSignal>) : DistressSignal { override operator fun compareTo(other: DistressSignal): Int = when (other) { is DistressInt -> this.compareTo(DistressList(listOf(other))) is DistressList -> this.content.compareTo(other.content) } companion object { fun of(string: String): DistressList { val lst = string.removePrefix("[").removeSuffix("]").splitSquares() return DistressList(lst.map { DistressSignal.of(it) }) } } } private fun String.splitSquares(): List<String> { val result = mutableListOf<String>() var currentString = "" var balance = 0 for (c in this) { balance += when (c) { '[' -> 1 ']' -> -1 else -> 0 } if (c == ',' && balance == 0) { result.add(currentString) currentString = "" } else currentString += c } if (currentString != "") result.add(currentString) return result } private fun List<DistressSignal>.compareTo(other: List<DistressSignal>): Int { for ((x, y) in this.zip(other)) { when (x.compareTo(y)) { -1 -> return -1 1 -> return 1 } } return this.size.compareTo(other.size) } data class DistressInt(val content: Int) : DistressSignal { override operator fun compareTo(other: DistressSignal): Int = when (other) { is DistressInt -> this.content.compareTo(other.content) is DistressList -> DistressList(listOf(this)).compareTo(other) } companion object { fun of(string: String): DistressInt = DistressInt(string.toInt()) } } fun main() { val day = 13 fun part1(input: List<String>): Int = input.chunked(3).mapIndexed { index, (first, second, _) -> if (DistressSignal.of(first) < DistressSignal.of(second)) index + 1 else 0 }.sum() val dividers = listOf( DistressSignal.of("[[2]]"), DistressSignal.of("[[6]]") ) fun part2(input: List<String>): Int = (dividers + input.filterIndexed { index, _ -> index % 3 < 2 }.map { DistressSignal.of(it) }) .sorted() .let { (it.indexOf(dividers[0]) + 1) * (it.indexOf(dividers[1]) + 1) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day}_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day${day}") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
abdd1b8d93b8afb3372cfed23547ec5a8b8298aa
2,893
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/dmc/advent2022/Day12.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
//--- Day 12: Hill Climbing Algorithm --- package com.dmc.advent2022 import java.util.* class Day12 : Day<Int> { override val index = 12 override fun part1(input: List<String>): Int { val heightmap = parseInput(input) return heightmap.shortestPath(heightmap.start, heightmap.end)!! } override fun part2(input: List<String>): Int { val heightmap = parseInput(input) val startPoints = heightmap.elevations.filter { it.value == 0 }.map { it.key } return startPoints.map{ heightmap.shortestPath(it, heightmap.end) }.filterNotNull().min() } class Heightmap(val elevations : Map<Point2D, Int>, val start: Point2D, val end: Point2D) { fun shortestPath(begin: Point2D, end: Point2D) : Int? { val queue = PriorityQueue<Path>().apply { add(Path(begin, 0)) } val explored = mutableSetOf<Point2D>() // BFS while (queue.isNotEmpty()) { val nextPoint = queue.poll() if(nextPoint.point !in explored) { explored.add(nextPoint.point) val neighbours = nextPoint.point.friendlyNeighbours() val nextCost = nextPoint.cost + 1 // If neighbour is goal then we are almost there if (neighbours.any { it == end }) return nextCost // Otherwise, keep on looking queue.addAll(neighbours.map { Path(it, nextCost) }) } } // No path found return null // throw IllegalStateException("No valid path from $start to $end") } fun canMove(from: Point2D, to: Point2D) : Boolean { return (elevations.getValue(to) - elevations.getValue(from)) <= 1 } private fun Point2D.friendlyNeighbours() : List<Point2D> { return this.cardinalNeighbors() .filter { it in elevations } .filter { canMove(this, it) } } fun getFriendlyNeighbours(point: Point2D) : List<Point2D> { return point.friendlyNeighbours() } } class Path(val point: Point2D, val cost: Int) : Comparable<Path> { override fun compareTo(other: Path): Int = this.cost.compareTo(other.cost) } fun parseInput(input: List<String>) : Heightmap { var start: Point2D? = null var end: Point2D? = null val elevations = input.flatMapIndexed { x, line -> line.mapIndexed{ y, elem -> val here = Point2D(x, y) here to when (elem) { 'S' -> 0.also { start = here } 'E' -> 25.also { end = here } else -> elem - 'a' } } }.toMap() return Heightmap(elevations, start!!, end!!) } } fun main() { val day = Day12() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 0) val input = readInput(day.index) day.part1(input).println() day.part2(testInput) day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
3,220
aoc-2022-kotlin
Apache License 2.0
src/main/day16/day16.kt
rolf-rosenbaum
572,864,107
false
{"Kotlin": 80772}
package day16 import kotlin.math.max import readInput const val START = "AA" val flowRegex = """(\d+)""".toRegex() val valveRegex = """[A-Z]{2}""".toRegex() var totalTime = 30 var maxPressureRelease = 0 var allValves: Map<String, Valve> = mapOf() var shortestPaths: MutableMap<String, MutableMap<String, Int>> = mutableMapOf() fun main() { val input = readInput("main/day16/Day16_test") println(part1(input)) println(part2(input)) } fun part1(input: List<String>): Int { prepareSearch(input) checkAllPaths(0, START, emptySet(), 0) return maxPressureRelease } fun part2(input: List<String>): Int { totalTime = 26 prepareSearch(input) checkAllPaths(0, START, emptySet(), 0, true) return maxPressureRelease } private fun prepareSearch(input: List<String>) { maxPressureRelease = 0 val valves = input.map { it.parse() } allValves = valves.associateBy { it.id } shortestPaths = shortestPathsFromEachTunnelToAllOtherTunnels( valves.associate { it.id to it.neighbouringValves.associateWith { 1 } .toMutableMap() }.toMutableMap() ) } private fun checkAllPaths(currentPressureRelease: Int, currentValveId: String, visited: Set<String>, time: Int, withElefant: Boolean = false) { maxPressureRelease = max(maxPressureRelease, currentPressureRelease) shortestPaths[currentValveId]!!.forEach { (valveId, distance) -> if (!visited.contains(valveId) && time + distance + 1 < totalTime) { checkAllPaths( currentPressureRelease = currentPressureRelease + (totalTime - time - distance - 1) * allValves[valveId]?.flow!!, currentValveId = valveId, visited = visited + valveId, time = time + distance + 1, withElefant = withElefant ) } } if (withElefant) { checkAllPaths(currentPressureRelease, START, visited, 0, false) } } private fun shortestPathsFromEachTunnelToAllOtherTunnels(shortestPaths: MutableMap<String, MutableMap<String, Int>>): MutableMap<String, MutableMap<String, Int>> { shortestPaths.keys.forEach { a -> shortestPaths.keys.forEach { b -> shortestPaths.keys.forEach { c -> val ab = shortestPaths[b]?.get(a) ?: 100 val ac = shortestPaths[a]?.get(c) ?: 100 val bc = shortestPaths[b]?.get(c) ?: 100 if (ab + ac < bc) shortestPaths[b]?.set(c, ab + ac) } } } shortestPaths.values.forEach { it.keys.mapNotNull { key -> if (allValves[key]?.flow == 0) key else null } .forEach { uselessValve -> it.remove(uselessValve) } } return shortestPaths } fun String.parse(): Valve { val valves = valveRegex.findAll(this).map { it.groupValues.first() }.toList() val flow = flowRegex.findAll(this).first().groupValues.first().toInt() val tunnels = valves.drop(1) return Valve(id = valves.first(), flow = flow, neighbouringValves = tunnels) } data class Valve(val id: String, val flow: Int, val neighbouringValves: List<String>)
0
Kotlin
0
2
59cd4265646e1a011d2a1b744c7b8b2afe482265
3,209
aoc-2022
Apache License 2.0
src/year2023/day07/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day07 import arrow.core.NonEmptyList import arrow.core.identity import arrow.core.nonEmptyListOf import arrow.core.toNonEmptyListOrNull import utils.ProblemPart import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 7) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(6440), algorithm = ::part1, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(5905), algorithm = ::part2, ), ) } private fun parse( input: List<String>, jValue: Int, type: (List<Int>) -> HandType, ): List<PokerHand> = input.map { line -> val (hand, bid) = line.split(' ') val cards = hand.map { when (it) { in '2'..'9' -> it - '2' + 2 'T' -> 10 'J' -> jValue 'Q' -> 12 'K' -> 13 else -> 14 } }.toNonEmptyListOrNull()!! PokerHand( cards, type(cards), bid.toLong(), ) } private fun part1(input: List<String>): Long = algorithm( input = input, jValue = 11, parseHandType = { it.groupingBy(::identity) .eachCount() .toHandType() }, ) private fun algorithm( input: List<String>, jValue: Int, parseHandType: (List<Int>) -> HandType, ): Long { return parse( input, jValue = jValue, type = parseHandType, ) .asSequence() .sortedWith( compareByDescending<PokerHand> { it.type } .thenComparator { a, b -> a.cards.asSequence() .zip(b.cards.asSequence()) { cardA, cardB -> cardA.compareTo(cardB) } .first { it != 0 } } ) .withIndex() .sumOf { (index, hand) -> (index + 1) * hand.bid } } private fun part2(input: List<String>): Long = algorithm( input = input, jValue = 1, parseHandType = { hand -> val cardCounts = hand.groupingBy(::identity).eachCount() val adjustedHand = cardCounts[1]?.let { jokerCount -> val bestCard = cardCounts.entries .filterNot { it.key == 1 } .maxByOrNull { it.value } ?.key if (bestCard == null) cardCounts else cardCounts.asSequence() .filterNot { it.key == 1 } .associate { (key, count) -> key to if (key == bestCard) count + jokerCount else count } } ?: cardCounts adjustedHand.toHandType() }, ) private fun Map<Int, Int>.toHandType() = when (size) { 1 -> HandType.Five 2 -> if (containsValue(4)) HandType.Four else HandType.FullHouse 3 -> if (containsValue(3)) HandType.Three else HandType.TwoPairs 4 -> HandType.OnePair else -> HandType.One } private data class PokerHand( val cards: NonEmptyList<Int>, val type: HandType, val bid: Long, ) enum class HandType { Five, Four, FullHouse, Three, TwoPairs, OnePair, One }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
3,169
Advent-of-Code
Apache License 2.0
src/main/kotlin/aoc2023/Day13.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 class Day13 { fun part1(input: String): Long = parseInput(input) .map { mirrorPattern -> calculateReflection(mirrorPattern.rows) to calculateReflection(mirrorPattern.cols) } .sumOf { (r, c) -> r * 100L + c } fun part2(input: String): Long = parseInput(input) .map { mirrorPattern -> calculateReflectionWithSmudge(mirrorPattern.rows) to calculateReflectionWithSmudge(mirrorPattern.cols) } .sumOf { (r, c) -> r * 100L + c } private fun calculateReflection(pattern: List<Long>): Int { val candidateIndexes = pattern.zipWithNext().withIndex() .filter { (_, pair) -> (pair.first xor pair.second) == 0L } .map { (idx, _) -> idx } candidates@ for (idx in candidateIndexes) { val iRange = idx - 1 downTo 0 val jRange = idx + 2..<pattern.size for ((i, j) in iRange.zip(jRange)) { if ((pattern[i] xor pattern[j]) > 0L) continue@candidates } return idx + 1 } return 0 } private fun calculateReflectionWithSmudge(pattern: List<Long>): Int { val candidates = pattern.zipWithNext() .map { (it.first xor it.second).countOneBits() } .withIndex() .filter { (_, diff) -> diff <= 1 } candidates@ for ((idx, diff) in candidates) { var hasSmudge = diff == 1 val iRange = idx - 1 downTo 0 val jRange = idx + 2..<pattern.size for ((i, j) in iRange.zip(jRange)) { val nextDiff = (pattern[i] xor pattern[j]).countOneBits() if ((nextDiff > 1) || (nextDiff == 1 && hasSmudge)) continue@candidates if (nextDiff == 1) hasSmudge = true } if (hasSmudge) { return idx + 1 } } return 0 } private fun parseInput(input: String): List<MirrorPattern> { val lines = (input + "\n").split('\n') val mirrorPatterns = mutableListOf<MirrorPattern>() var pattern = mutableListOf<String>() for (line in lines) { if (line.isNotEmpty()) { val binaryLine = line.replace('.', '0').replace('#', '1') pattern.add(binaryLine) } else if (pattern.isNotEmpty()) { mirrorPatterns.add(MirrorPattern(pattern)) pattern = mutableListOf() } } return mirrorPatterns } data class MirrorPattern(val pattern: List<String>) { val rows = pattern.map { it.toLong(2) } val cols = transpose().map { it.toLong(2) } private fun transpose(): List<String> { val rows = pattern.size val cols = pattern[0].length return List(cols) { j -> String(CharArray(rows) { i -> pattern[i][j] }) } } } } fun main() { val day13 = Day13() val input = readInputAsString("day13.txt") println("13, part 1: ${day13.part1(input)}") println("13, part 2: ${day13.part2(input)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
3,104
advent-of-code-2023
MIT License
src/day9/d9_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val edges = input.lines().map { parseEdge(it) }.flatMap { e -> listOf(e, Edge(e.to, e.from, e.distance)) } val nodes = edges.map { e -> e.from }.toSet() val nodeToIdx = nodes.toList().sorted().mapIndexed { i, n -> n to i }.toMap() val edgesMap = edges.groupBy { e -> nodeToIdx[e.from]!! } .mapValues() { (_, v) -> v.groupBy { e -> nodeToIdx[e.to]!!}.mapValues { (_, v2) -> v2[0].distance } } println(forEachPermutation(nodes.size) { arr -> computeLength(arr, edgesMap) }.min()) } data class Edge(val from: String, val to: String, val distance: Int) fun parseEdge(string: String): Edge = string.split(" ").let { Edge(it[0], it[2], it[4].toInt()) } fun computeLength(arr: Array<Int>, map: Map<Int, Map<Int, Int>>): Int { return arr.toList().windowed(2).map { it[0] to it[1] }.fold(0) { acc, (from, to) -> acc + map[from]!![to]!! } } fun <T> forEachPermutation(n: Int, f: (Array<Int>) -> T): List<T> { val arr = Array<Int>(n) { 0 } return genRecursive(arr, 0, (0 until n).toSet(), f) } fun <T> genRecursive(arr: Array<Int>, nextIdx: Int, options: Set<Int>, f: (Array<Int>) -> T): List<T> { if (nextIdx == arr.size) { return listOf(f(arr)) } val result = mutableListOf<T>() for (opt in options) { arr[nextIdx] = opt result.addAll(genRecursive(arr, nextIdx + 1, options - opt, f)) } return result }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,382
aoc2015
MIT License
src/day03/Day03.kt
martinhrvn
724,678,473
false
{"Kotlin": 27307, "Jupyter Notebook": 1336}
package day03 import println import readInput enum class Direction { BEFORE, AFTER } fun String.intVal(): Int { return this.toIntOrNull() ?: 0 } fun List<String>.sum(): Int { return this.sumOf { it.intVal() } } typealias Coordinates = Pair<Int, Int> typealias NumberMap = Map<Coordinates, Int> class PartParser(private val input: List<String>) { fun part1(): Int { return input .flatMapIndexed { x, row -> row.mapIndexed { y, c -> if (!c.isDigit() && c != '.') { getNumbersAround(x, y) } else { mapOf() } } } .sumOf { it.values.sum() } } fun part2(): Int { return input .flatMapIndexed { x, row -> row.mapIndexed { y, c -> if (!c.isDigit() && c != '.') { val partNumbers = getNumbersAround(x, y) if (partNumbers.size == 2) { partNumbers.entries.fold(1) { acc, e -> acc * e.value } } else { 0 } } else { 0 } } } .sum() } private fun getNumbersAround(x: Int, y: Int): NumberMap { val before = takeNumberAt(x, y, Direction.BEFORE) val after = takeNumberAt(x, y, Direction.AFTER) return mapOf( Pair(x, y - before.length) to before.intVal(), Pair(x, y + 1) to after.intVal(), ) .plus(takeVertically(x - 1, y)) .plus(takeVertically(x + 1, y)) .filter { (_, v) -> v != 0 } } private fun takeNumberAt(x: Int, y: Int, direction: Direction): String { return input[x] .let { row -> if (direction == Direction.BEFORE) { row.slice(0 ..< y).reversed() } else { row.slice((y + 1) ..< row.length) } } .takeWhile { ch -> ch.isDigit() } .let { if (direction == Direction.BEFORE) { it.reversed() } else { it } } } private fun takeVertically(x: Int, y: Int): NumberMap { if (x < 0 || x >= input.size) { return mapOf() } val before = takeNumberAt(x, y, Direction.BEFORE) val after = takeNumberAt(x, y, Direction.AFTER) return if (input[x][y].isDigit()) { mapOf(Pair(x, y - before.length) to before.plus(input.get(x)[y]).plus(after).intVal()) } else { mapOf(Pair(x, y - before.length) to before.intVal(), Pair(x, y + 1) to after.intVal()) } } } fun main() { val testInput = readInput("day03/Day03_test") println(PartParser(testInput).part1()) check(PartParser(testInput).part1() == 4361) check(PartParser(testInput).part2() == 467835) val cube = PartParser(readInput("day03/Day03")) cube.part1().println() cube.part2().println() }
0
Kotlin
0
0
59119fba430700e7e2f8379a7f8ecd3d6a975ab8
2,829
advent-of-code-2023-kotlin
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day04/day4.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day04 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val moves = readMoves(lines) val boards = readBoards(lines) val wonBoards = playBingo(moves, boards) println("First won board score: ${wonBoards.first().score}") println("Last won board score: ${wonBoards.last().score}") } fun playBingo(moves: List<Int>, boards: List<Board>): List<WonBoard> { val initial = Pair<List<Board>, List<WonBoard>>(boards, emptyList()) return moves.fold(initial) { (currentBoards, winningBoards), move -> val updatedBoards = currentBoards.map { it.mark(move) } val (boardsInProgress, boardsThatWon) = updatedBoards.partition { it.getFullyMarkedRowsOrColumns().isEmpty() } Pair(boardsInProgress, winningBoards + boardsThatWon.map { WonBoard(it, it.score(move)) }) }.second } fun readMoves(lines: List<String>): List<Int> = lines[0].split(',').map { it.toInt() } data class WonBoard(val board: Board, val score: Int) data class Board(val size: Int, val rows: List<BoardCells>) { val cols: List<BoardCells> get() = (0 until size).map { i -> BoardCells(cells = rows.map { it[i] }) } operator fun get(i: Int) = rows[i] fun mark(value: Int): Board = copy(rows = rows.map { it.mark(value) }) fun getFullyMarkedRowsOrColumns() = (rows + cols).filter { it.cells.all { cell -> cell.marked } } fun score(lastValueMarked: Int): Int { val unmarkedValues = rows.flatMap { row -> row.cells .filter { cell -> !cell.marked } .map { cell -> cell.value } } return unmarkedValues.sum() * lastValueMarked } } data class BoardCells(val cells: List<Cell>) { operator fun get(i: Int) = cells[i] fun mark(value: Int): BoardCells = copy(cells = cells.map { it.copy(marked = it.marked || it.value == value) }) } data class Cell(val value: Int, val marked: Boolean) fun readBoards(lines: List<String>): List<Board> { val boardSize = parseCells(lines[2]).size return lines .asSequence() .drop(2) .filter { it.isNotBlank() } .chunked(boardSize) .map { Board(size = boardSize, rows = parseRows(it)) } .toList() } private fun parseRows(lines: List<String>): List<BoardCells> = lines.asSequence() .map { BoardCells(cells = parseCells(it)) } .toList() private fun parseCells(line: String) = line.trim() .split(Regex(" +")) .map { Cell(it.toInt(), false) } .toList()
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,818
advent-of-code
MIT License
src/commonMain/kotlin/advent2020/day21/Day21Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day21 data class Food(val ingredients: List<String>, val allergens: List<String>) fun part1(input: String): String { val foods = foods(input) val ingredients = foods.map { it.ingredients }.flatten() val unsafe = matches(foods).values.reduce(Set<String>::plus) val safe = ingredients.filterNot { it in unsafe }.toSet() val result = ingredients.count { it in safe } return result.toString() } fun part2(input: String): String { val foods = foods(input) val matches = matches(foods).mapValues { it.value.toMutableSet() } var again = true while (again) { again = false val knownUnsafeIngredients = matches .mapNotNull { (allergen, ingredients) -> ingredients.singleOrNull()?.let { allergen to it } } knownUnsafeIngredients .forEach { (allergen, ingredient) -> matches.forEach { (a2, i2) -> if (a2 != allergen && ingredient in i2) i2 -= ingredient.also { again = true } } } } return matches.entries.sortedBy { it.key }.joinToString(",") { it.value.single() } } private fun matches(foods: List<Food>) = foods .map { (ingredients, allergens) -> allergens.map { it to ingredients.toSet() }.toMap() } .reduce { acc, next -> val keys = acc.keys + next.keys keys.associateWith { val s1 = acc[it] val s2 = next[it] when { s1 == null -> s2!! s2 == null -> s1 else -> s1.intersect(s2) } } } val regex by lazy { """((\w+ )+)\(contains ((\w+(, )?)+)\)""".toRegex() } private fun foods(input: String): List<Food> = input.trim().lines() .map { regex.matchEntire(it)?.destructured ?: error("`$it` doesn't match") } .map { (gr1, _, gr3) -> val ingredients = gr1.split(" ").filter { it.isNotBlank() } val allergens = gr3.split(", ").filter { it.isNotBlank() } Food(ingredients, allergens) }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,070
advent-of-code-2020
MIT License
src/Day08.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
fun main() { fun part1(input: List<String>): Int { var visibleTreesInside = (1 until input.lastIndex).sumOf { rowIndex -> val row = input[rowIndex] (1 until row.lastIndex).count { columnIndex -> val tree = row[columnIndex] when { (0 until columnIndex).all { tree > row[it] } -> true ((columnIndex + 1)..row.lastIndex).all { tree > row[it] } -> true (0 until rowIndex).all { tree > input[it][columnIndex] } -> true ((rowIndex + 1)..input.lastIndex).all { tree > input[it][columnIndex] } -> true else -> false } } } return visibleTreesInside + (input.size + input.first().length - 2) * 2 } fun part2(input: List<String>): Int { val insideWidth = input.size - 2 val insideHeight = input.first().length - 2 val totalTreesInside = insideWidth * insideHeight return (0 until totalTreesInside).maxOf { index -> val row = index / insideWidth + 1 val column = index % insideWidth + 1 val tree = input[row][column] val leftTrees = (1..column).firstNotNullOfOrNull { if (input[row][column - it] >= tree) it else null } ?: column val rightTrees = (1 until (input.first().length - column)).firstNotNullOfOrNull { if (input[row][column + it] >= tree) it else null } ?: (input.first().length - column - 1) val topTrees = (1..row).firstNotNullOfOrNull { if (input[row - it][column] >= tree) it else null } ?: row val bottomTrees = (1 until (input.size - row)).firstNotNullOfOrNull { if (input[row + it][column] >= tree) it else null } ?: (input.size - row - 1) // println("$row:$column $leftTrees, $rightTrees, $topTrees, $bottomTrees") // println(leftTrees * rightTrees * topTrees * bottomTrees) leftTrees * rightTrees * topTrees * bottomTrees } } 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
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
2,334
aoc-2022
Apache License 2.0
src/main/kotlin/aoc2023/Day12.kt
Ceridan
725,711,266
false
{"Kotlin": 110767, "Shell": 1955}
package aoc2023 class Day12 { fun part1(input: String): Long { val (rows, groups) = parseInput(input) return rows.zip(groups).sumOf { (r, c) -> calculateArrangements(r, c) } } fun part2(input: String): Long { val (rows, groups) = parseInput(input) val expandedRows = rows.map { "$it?".repeat(5).dropLast(1) } val expandedGroups = groups.map { group -> group.joinToString(separator = ",", postfix = ",").repeat(5).dropLast(1).split(',').map { it.toInt() } } return expandedRows.zip(expandedGroups).sumOf { (r, c) -> calculateArrangements(r, c) } } private fun calculateArrangements( pattern: String, groups: List<Int>, rowIdx: Int = 0, colIdx: Int = 0, cache: MutableMap<Pair<Int, Int>, Long> = mutableMapOf() ): Long { val hashIdx = pattern.drop(rowIdx).indexOf('#') if (colIdx == groups.size) { return if (hashIdx == -1) 1L else 0L } return pattern.drop(rowIdx).windowed(groups[colIdx], 1).withIndex() .filter { (i, window) -> if (window.any { it == '.' }) return@filter false if (hashIdx > -1 && i > hashIdx) return@filter false val leftIdx = rowIdx + i val leftDot = leftIdx == 0 || pattern[leftIdx - 1] == '.' || pattern[leftIdx - 1] == '?' val rightIdx = rowIdx + window.length + i val rightDot = (rightIdx == pattern.length) || pattern[rightIdx] == '.' || pattern[rightIdx] == '?' leftDot && rightDot } .sumOf { (i, window) -> val newRowIdx = rowIdx + window.length + i + 1 val newColIdx = colIdx + 1 cache.getOrPut(newRowIdx to newColIdx) { calculateArrangements( pattern, groups, newRowIdx, newColIdx, cache ) } } } private fun parseInput(input: String): Pair<List<String>, List<List<Int>>> { val rows = mutableListOf<String>() val groups = mutableListOf<List<Int>>() val lines = input.split('\n').filter { it.isNotEmpty() } for (line in lines) { val (rowString, groupString) = line.split(' ') rows.add(rowString) groups.add(groupString.split(',').map { it.toInt() }) } return rows to groups } } fun main() { val day12 = Day12() val input = readInputAsString("day12.txt") println("12, part 1: ${day12.part1(input)}") println("12, part 2: ${day12.part2(input)}") }
0
Kotlin
0
0
18b97d650f4a90219bd6a81a8cf4d445d56ea9e8
2,752
advent-of-code-2023
MIT License
src/Day08.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
data class Tree( val height: Int, val allToTheLeft: List<Int>, val allToTheTop: List<Int>, val allToTheRight: List<Int>, val allToTheBottom: List<Int>, ) { val isVisible: Boolean get() = listOf(allToTheLeft, allToTheTop, allToTheRight, allToTheBottom) .any { direction -> direction.all { it < height } || direction.isEmpty() } val scenicScore: Int get() = listOf(allToTheLeft, allToTheTop, allToTheRight, allToTheBottom) .map { direction -> direction.indexOfFirst { it >= height }.takeIf { it != -1 }?.let { it + 1 } ?: direction.size } .fold(1) { currentScore, direction -> currentScore * direction } } fun main() { fun parseInput(input: List<String>): List<Tree> { val map = input.map { it.toCharArray().map { it.digitToInt() } } val mapHeight = map.size val mapWidth = map[0].size // A kiss right on the eye return (0 until mapWidth).map { x -> (0 until mapHeight).map { y -> Tree( map[y][x], allToTheLeft = (0 until x).reversed().map { readX -> map[y][readX] }, allToTheRight = (x + 1 until mapWidth).map { readX -> map[y][readX] }, allToTheTop = (0 until y).reversed().map { readY -> map[readY][x] }, allToTheBottom = (y + 1 until mapHeight).map { readY -> map[readY][x] }, ) } }.flatten() } fun part1(input: List<String>): Int { return parseInput(input).filter { it.isVisible }.size } fun part2(input: List<String>): Int { return parseInput(input).maxOf { it.scenicScore } } // 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
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
2,015
advent-of-code-2022
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day8.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import twentytwentytwo.Structures.Point2d import kotlin.math.sqrt typealias Tree = Pair<Point2d, Int> fun main() { val input = {}.javaClass.getResource("input-8.txt")!!.readText().linesFiltered { it.isNotEmpty() }; val day = Day8(input) val columns = (0 until input[0].length).map { index -> input.map { it[index].digitToInt() } }.also { println(it) } val rows = (input.indices).map { index -> input[index].map { it.digitToInt() } }.also { println(it) } val size = sqrt(input.joinToString(separator = "") { it }.length.toDouble()).toInt() println(size) val trees = input.joinToString(separator = "") { it }.mapIndexed { index, c -> val x = index / size val y = index % size Tree(Point2d(x, y), c.digitToInt()) } trees.forEach { println("${it.first.x},${it.first.y} ${it.second}") } println(size) println(day.part1()) println(day.part2()) } class Day8(input: List<String>) { private val trees = input.mapIndexed { y, row -> row.mapIndexed { x, s -> Tree(Point2d(x, y), s.digitToInt()) } }.flatten() init { trees.forEach { (point) -> rows.computeIfAbsent(point.y) { trees.filter { it.first.sameRow(point) } } columns.computeIfAbsent(point.x) { trees.filter { it.first.sameColumn(point) } } } } fun part1() = trees.filter { it.visible() }.size fun part2() = trees.maxOf { it.sees() } companion object { private val rows = mutableMapOf<Int, List<Tree>>() private val columns = mutableMapOf<Int, List<Tree>>() fun Tree.sees(): Int { val (left, right, above, under) = getLines() return countVisibleTrees(left.reversed()) * countVisibleTrees(right) * countVisibleTrees(under) * countVisibleTrees( above.reversed() ) } fun Tree.visible() = edge() || getLines().any { isBiggest(it) } // check if we reached the end otherwise add 1. (should have a takeWhileInclusive or something) private fun Tree.countVisibleTrees(trees: List<Tree>) = trees.takeWhile { it.second < second }.count() .let { count -> if (count == trees.size) count else count + 1 } private fun Tree.getLines() = rows[first.y]!!.split(this.first.x) + columns[first.x]!!.split(this.first.y) private fun List<Tree>.split(number: Int) = listOf(take(number), takeLast(size - number - 1)) private fun Tree.isBiggest(trees: List<Tree>) = trees.all { it.second < second } private fun Tree.edge() = first.x == 0 || first.x == columns.size || first.y == 0 || first.y == rows.size } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
2,677
aoc202xkotlin
The Unlicense
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day08/Day08.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day08 import nerok.aoc.utils.Input import java.util.* import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun predictPairs(x: List<SortedSet<Char>>): MutableMap<SortedSet<Char>, Int> { val map = x.associateWith { -1 }.toMutableMap() map.forEach { when (it.key.size) { 2 -> { map[it.key] = 1 } 3 -> { map[it.key] = 7 } 4 -> { map[it.key] = 4 } 7 -> { map[it.key] = 8 } else -> { } } } map.filter { it.key.size == 6 }.forEach { if (it.key.containsAll(map.filterValues { it == 4 }.keys.first())) { map[it.key] = 9 } else if (it.key.containsAll(map.filterValues { it == 1 }.keys.first())) { map[it.key] = 0 } else { map[it.key] = 6 } } map.filter { it.value == -1 }.forEach { if (it.key.containsAll(map.filterValues { it == 7 }.keys.first())) { map[it.key] = 3 } else if (map.filterValues { it == 9 }.keys.first().containsAll(it.key)) { map[it.key] = 5 } else { map[it.key] = 2 } } return map } fun part1(input: List<String>): Long { val countArray = IntArray(8) { 0 } input.map { line -> line.split(" | ").map { it.split(" ") }.let { it.first() to it.last() } }.map { entry -> entry.first.groupBy { it.length } to entry.second.groupBy { it.length } }.map { it.second }.forEach { it.forEach { countArray[it.key] += it.value.size } } val countMap = countArray.mapIndexed { index, i -> index to i }.toMap() return countMap[2]!!.plus(countMap[3]!!).plus(countMap[4]!!).plus(countMap[7]!!).toLong() } fun part2(input: List<String>): Long = input.map { line -> line.split(" | ").map { it.split(" ") }.let { it.first().map { it.toSortedSet() } to it.last().map { it.toSortedSet() } } }.sumOf { val map = predictPairs(it.first) Integer.parseInt(it.second.map { map[it] }.joinToString("")) }.toLong() // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day08_test") check(part1(testInput) == 26L) check(part2(testInput) == 61229L) val input = Input.readInput("Day08") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
2,867
AOC
Apache License 2.0
src/Day04.kt
george-theocharis
573,013,076
false
{"Kotlin": 10656}
fun main() { fun part1(input: List<String>): Int = input .splitByLine() .mapToPairOfRanges() .sumOfPairsThatOverlapEntirely() fun part2(input: List<String>): Int = input .splitByLine() .mapToPairOfRanges() .sumOfPairsThatOverlap() val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun List<String>.splitByLine(): List<List<String>> = map { line -> line.split(',') } private fun List<List<String>>.mapToPairOfRanges(): List<Pair<IntRange, IntRange>> = map { elfGroup -> val elfARange = elfGroup[0].split('-') val elfBRange = elfGroup[1].split('-') (elfARange[0].toInt()..elfARange[1].toInt()) to (elfBRange[0].toInt()..elfBRange[1].toInt()) } private fun List<Pair<IntRange, IntRange>>.sumOfPairsThatOverlapEntirely() = sumOf { (elfARange, elfBRange) -> val addition: Int = if (elfARange.contains(elfBRange.first) && elfARange.contains(elfBRange.last) || elfBRange.contains( elfARange.first ) && elfBRange.contains(elfARange.last) ) 1 else 0 addition } private fun List<Pair<IntRange, IntRange>>.sumOfPairsThatOverlap() = sumOf { (elfARange, elfBRange) -> val addition: Int = if(elfARange.any { elfBRange.contains(it) } || elfBRange.any { elfARange.contains(it) }) 1 else 0 addition }
0
Kotlin
0
0
7971bea39439b363f230a44e252c7b9f05a9b764
1,369
aoc-2022
Apache License 2.0
Advent-of-Code-2023/src/Day02.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
private const val AOC_DAY = "Day02" private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1" private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2" private const val INPUT_FILE = AOC_DAY private const val MAX_COLORS = 3 private data class Cube(val value: Int, val color: String) private val maxCubes = mapOf("red" to 12, "green" to 13, "blue" to 14) /** * Finds the games that use a number of cubes from a specific color that is greater than the maximum cubes of that color * specified by the maxCubes map. * @return the gameID of the games that use a possible number of cubes for each color according to the maxCubes map. */ private fun part1(input: List<String>): Int { return input.sumOf { game -> val (gameId, cubes) = parseCubes(game) var isImpossible = false for (cube in cubes) { if (cube.value > maxCubes[cube.color]!!) { isImpossible = true break } } if (isImpossible) 0 else gameId } } private fun part1Improved(input: List<String>): Int { return input.filter { game -> val (_, cubes) = parseCubes(game) cubes.none { cube -> cube.value > maxCubes[cube.color]!! } // cubes.all { cube -> cube.value <= maxCubes[cube.color]!! } // alternative }.sumOf { it.split(":")[0].split(" ")[1].toInt() } } /** * Finds the maximum number of cubes by color used in a set of a game, multiplies them, and sums the result with the * results of the other games. * Obs: I sorted the array in hope of not needing to iterate through all cubes, an alternative easy approach would be * to instead of sorting the array, storing the max value and compare each cube value with the previous max * @return the sum of the product of the number of cubes for each color in each game */ private fun part2(input: List<String>): Int { return input.sumOf { game -> val (_, cubes) = parseCubes(game) val sortedCubes = cubes.sortedByDescending { cube -> cube.value } val cubesValues = HashMap<String, Int>() for (cube in sortedCubes) { cubesValues.putIfAbsent(cube.color, cube.value) if (cubesValues.size == MAX_COLORS) break } cubesValues.values.reduce(Int::times) } } private fun part2WithoutOrdering(input: List<String>): Int { return input.sumOf { game -> val (_, cubes) = parseCubes(game) val cubesValues = mutableMapOf("red" to 0, "blue" to 0, "green" to 0) for (cube in cubes) { if (cubesValues[cube.color]!! >= cube.value) continue cubesValues[cube.color] = cube.value } cubesValues.values.reduce(Int::times) } } /** * Auxiliary function to parse the cubes from each game. * @return a pair with the game id and its cubes. */ private fun parseCubes(game: String): Pair<Int, List<Cube>> { val (gameInfo, sets) = game.split(": ") return Pair( gameInfo.split(" ")[1].toInt(), sets .split(", ", "; ") .map { val cube = it.split(" ") Cube(cube[0].toInt(), cube[1]) }) } fun main() { val part1ExpectedRes = 8 val part1TestInput = readInputToList(PART1_TEST_FILE) println("---| TEST INPUT |---") println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes") println("+ PART 1: ${part1Improved(part1TestInput)}\t== $part1ExpectedRes") val part2ExpectedRes = 2286 val part2TestInput = readInputToList(PART2_TEST_FILE) println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = true println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t== 2879" else ""}") println("+ PART 1: ${part1Improved(input)}${if (improving) "\t== 2879" else ""}") println("* PART 2: ${part2(input)}${if (improving) "\t== 65122" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
3,981
Advent-of-Code-2023
Apache License 2.0
src/Day08.kt
Yasenia
575,276,480
false
{"Kotlin": 15232}
fun main() { fun part1(input: List<String>): Int { val treeMatrix = input.map { line -> line.toCharArray().map { it.digitToInt() } } var visibleCount = 0 for (i in 1 until treeMatrix.lastIndex) { for (j in 1 until treeMatrix[i].lastIndex) { val height = treeMatrix[i][j] if ( (0 until i).all { treeMatrix[it][j] < height } || (i + 1..treeMatrix.lastIndex).all { treeMatrix[it][j] < height } || (0 until j).all { treeMatrix[i][it] < height } || (j + 1..treeMatrix[i].lastIndex).all { treeMatrix[i][it] < height } ) visibleCount++ } } return visibleCount + treeMatrix.size * 2 + treeMatrix.first().size + treeMatrix.last().size - 4 } fun part2(input: List<String>): Int { val treeMatrix = input.map { line -> line.toCharArray().map { it.digitToInt() } } var maxScore = 0 for (i in 1 until treeMatrix.lastIndex) { for (j in 1 until treeMatrix[i].lastIndex) { val height = treeMatrix[i][j] val upScore = ((i - 1 downTo 0).takeWhile { treeMatrix[it][j] < height }.size + 1).coerceAtMost(i) val downScore = ((i + 1..treeMatrix.lastIndex).takeWhile { treeMatrix[it][j] < height }.size + 1).coerceAtMost(treeMatrix.lastIndex - i) val leftScore = ((j - 1 downTo 0).takeWhile { treeMatrix[i][it] < height }.size + 1).coerceAtMost(j) val rightScore = ((j + 1..treeMatrix[i].lastIndex).takeWhile { treeMatrix[i][it] < height }.size + 1).coerceAtMost(treeMatrix[i].lastIndex - j) maxScore = maxScore.coerceAtLeast(upScore * downScore * leftScore * rightScore) } } return maxScore } 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
0
0
9300236fa8697530a3c234e9cb39acfb81f913ba
2,041
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
kmakma
574,238,598
false
null
fun main() { fun neighborsOf(coord: Coord2D, map: Map<Coord2D, Int>): List<Coord2D> { val neighbors = mutableListOf<Coord2D>() if (coord.x > 0) { val newCoord = coord.moved(-1, 0) if (map[newCoord]!! - map[coord]!! <= 1) neighbors.add(newCoord) } if (coord.y > 0) { val newCoord = coord.moved(0, -1) if (map[newCoord]!! - map[coord]!! <= 1) neighbors.add(newCoord) } val newCoordX = coord.moved(1, 0) if (map.containsKey(newCoordX) && map[newCoordX]!! - map[coord]!! <= 1) neighbors.add(newCoordX) val newCoordY = coord.moved(0, 1) if (map.containsKey(newCoordY) && map[newCoordY]!! - map[coord]!! <= 1) neighbors.add(newCoordY) return neighbors } fun printDistanceMap(distances: Map<Coord2D, Int>) { val minX = distances.keys.minOf { it.x } val maxX = distances.keys.maxOf { it.x } val minY = distances.keys.minOf { it.y } val maxY = distances.keys.maxOf { it.y } for (x in minX..maxX) { for (y in minY..maxY) { val dStr = distances.getOrDefault(Coord2D(x, y), -1).toString().padStart(2, ' ') print("$dStr | ") } println() } } fun shortestPath(heights: Map<Coord2D, Int>, start: Coord2D, end: Coord2D): Int { val distances = mutableMapOf(start to 0) val queue = mutableListOf(start) while (queue.isNotEmpty()) { val current = queue.removeFirst() val distance = distances[current]!! if (current == end) { // printDistanceMap(distances) return distance } val newEntries = neighborsOf(current, heights).filter { !distances.containsKey(it) } queue.addAll(newEntries) distances.putAll(newEntries.map { it to distance + 1 }) } return -1 } fun buildHeightMap(input: List<String>): Triple<Coord2D, Coord2D, Map<Coord2D, Int>> { lateinit var start: Coord2D lateinit var end: Coord2D val heights = input.flatMapIndexed { x, line -> line.mapIndexed { y, c -> Coord2D(x, y) to when (c) { 'E' -> { end = Coord2D(x, y) 'z'.code - 97 } 'S' -> { start = Coord2D(x, y) 'a'.code - 97 } else -> c.code - 97 } } }.toMap() return Triple(start, end, heights) } fun part1(input: List<String>): Int { val (start, end, heights) = buildHeightMap(input) return shortestPath(heights, start, end) } fun part2(input: List<String>): Int { val (_, end, heights) = buildHeightMap(input) return heights.filterValues { it == 0 }.keys.map { shortestPath(heights, it, end) }.filter { it > 0 }.min() } // val testinput = readInput("Day12_test") // println(part1(testinput)) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
3,218
advent-of-kotlin-2022
Apache License 2.0
src/Day04.kt
hnuttin
572,601,761
false
{"Kotlin": 5036}
fun main() { val pairs = readInput("Day04_test") .map { rawPair -> rawPair.split(",") } .map { rawPair -> Pair(toRange(rawPair[0]), toRange(rawPair[1])) }; // part1(pairs) part2(pairs) // print(rangeOverlaps(Pair(2, 6), Pair(4, 8))); } fun part2(pairs: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>) { println(pairs .filter { pair -> rangeOverlaps(pair.first, pair.second) } .count()) } fun rangeOverlaps(first: Pair<Int, Int>, second: Pair<Int, Int>):Boolean { return (first.first >= second.first && first.first <= second.second) || (first.second >= second.first && first.second <= second.second) || (first.first < second.first && first.second > second.second) || (second.first < first.first && second.second > first.second); } private fun part1(pairs: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>) { println(pairs .filter { pair -> rangeContains(pair.first, pair.second) || rangeContains(pair.second, pair.first) } .count()) } fun rangeContains(first: Pair<Int, Int>, second: Pair<Int, Int>): Boolean { return first.first <= second.first && first.second >= second.second; } fun toRange(rawRange: String): Pair<Int, Int> { val startAndEnd = rawRange.split("-") return Pair(startAndEnd[0].toInt(), startAndEnd[1].toInt()); }
0
Kotlin
0
0
53975ed6acb42858be56c2150e573cdbf3deedc0
1,347
aoc-2022
Apache License 2.0
src/Day15.kt
chbirmes
572,675,727
false
{"Kotlin": 32114}
import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>, row: Int): Int { val sensors = input.map { Sensor.parse(it) } val beaconXs = sensors.map { it.closestBeaconPosition } .filter { (_, y) -> y == row } .map { (x, _) -> x } .toSet() val ranges = sensors.asSequence() .map { it.radiusIntersectionWithLine(row) } .filterNotNull() .union() return ranges.sumOf { it.size() } - beaconXs.size } fun part2(input: List<String>, max: Int): Long { val sensors = input.map { Sensor.parse(it) } val targetRange = 0..max return targetRange.asSequence() .map { row -> val intersections = sensors.asSequence() .map { it.radiusIntersectionWithLine(row) } .filterNotNull() .union() intersections.asSequence() .filter { it.last >= 0 && it.first <= max } .takeIf { it.count() == 2 } ?.minBy { it.first } ?.let { (it.last + 1) to row } } .filterNotNull() .first() .let { (x, y) -> x.toLong() * 4_000_000L + y } } val testInput = readInput("Day15_test") check(part1(testInput, row = 10) == 26) check(part2(testInput, max = 20) == 56_000_011L) val input = readInput("Day15") println(part1(input, row = 2_000_000)) println(part2(input, max = 4_000_000)) } fun positionIn(s: String): Pair<Int, Int> = s.substringAfter("x=").substringBefore(',').toInt() to s.substringAfter("y=").toInt() private data class Sensor(val ownPosition: Pair<Int, Int>, val closestBeaconPosition: Pair<Int, Int>) { val radius = ownPosition.distanceTo(closestBeaconPosition) fun radiusIntersectionWithLine(line: Int): IntRange? { val distance = (ownPosition.second - line).absoluteValue val halfIntersectionLength = radius - distance return if (halfIntersectionLength >= 0) (ownPosition.first - halfIntersectionLength)..(ownPosition.first + halfIntersectionLength) else null } companion object { fun parse(line: String): Sensor = line.split(":").let { (left, right) -> Sensor(positionIn(left), positionIn(right)) } } } private fun Pair<Int, Int>.distanceTo(other: Pair<Int, Int>) = (first - other.first).absoluteValue + (second - other.second).absoluteValue private fun IntRange.union(other: IntRange): List<IntRange> = if (isEmpty()) { listOf(other) } else if (other.isEmpty()) { listOf(this) } else if (contains(other.first)) { if (contains(other.last)) { listOf(this) } else { listOf(first..other.last) } } else if (contains(other.last)) { listOf(other.first..last) } else if (other.contains(first)) { listOf(other) } else if (other.first == last + 1) { listOf(first..other.last) } else if (first == other.last + 1) { listOf(other.first..last) } else { listOf(this, other) } private fun IntRange.size() = if (isEmpty()) 0 else (last - first + 1) private fun Sequence<IntRange>.union() = sortedBy { it.first }.fold(listOf(IntRange.EMPTY)) { rangeList, range -> rangeList.dropLast(1) + rangeList.last().union(range) }
0
Kotlin
0
0
db82954ee965238e19c9c917d5c278a274975f26
3,435
aoc-2022
Apache License 2.0
src/Day08.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { infix fun Int.taller(trees: List<Int>): Boolean{ return trees.all{ it < this} } infix fun Int.visibleTrees(trees: List<Int>): Int{ if (this taller trees) return trees.size return trees.indexOfFirst{ it >= this} + 1 } fun part1(input: List<String>): Int { val sideSize = input.size val forest = input.map { it.toList().map { tree -> tree.digitToInt() } } fun Int.ifVisible(row:Int, col:Int): Int{ if ((row == 0)||(col == 0)||(row == sideSize-1)||(col == sideSize-1)) { return 1 } else if ((this taller forest[row].slice(0..col-1)) ||(this taller forest[row].slice(col+1..sideSize-1)) ||(this taller forest.map { it[col] }.slice(0..row-1)) ||(this taller forest.map { it[col] }.slice(row+1..sideSize-1))){ return 1 } return 0 } var count = 0 forest.mapIndexed { rowId, row -> row.mapIndexed { colId, tree -> count += tree.ifVisible(rowId, colId) }} return count } fun part2(input: List<String>): Int { val sideSize = input.size val forest = input.map { it.toList().map { tree -> tree.digitToInt() } } fun Int.scenicScore(row:Int, col:Int): Int{ if ((row == 0)||(col == 0)||(row == sideSize-1)||(col == sideSize-1)) { return 0 } val left = this visibleTrees forest[row].slice(0..col-1).reversed() val right = this visibleTrees forest[row].slice(col+1..sideSize-1) val up = this visibleTrees forest.map { it[col] }.slice(0..row-1).reversed() val down = this visibleTrees forest.map { it[col] }.slice(row+1..sideSize-1) return left*right*up*down } val res = forest.mapIndexed { rowId, row -> row.mapIndexed { colId, tree -> tree.scenicScore(rowId, colId) }.max()}.max() return res } // 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
0
0
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
2,272
aoc22
Apache License 2.0
src/Day11.kt
xNakero
572,621,673
false
{"Kotlin": 23869}
object Day11 { fun part1() = solve(20) { level, _ -> level / 3} fun part2() = solve(10_000) {level, mod -> level % mod} private fun solve(rounds: Int, worryLevelStrategy: (Long, Long) -> (Long)): Long { val monkeys = parseInput() val modulus = monkeys.map { it.test.divisibleBy }.reduce(Long::times) repeat(rounds) { monkeys.forEach { monkey -> val (dividedByZero, notDividedByZero) = monkey.items .map { worryLevelStrategy(monkey.inspect(it), modulus) } .partition { (it % monkey.test.divisibleBy == 0L) } monkeys[monkey.test.monkeyTrue].items.addAll(dividedByZero) monkeys[monkey.test.monkeyFalse].items.addAll(notDividedByZero) monkey.items.clear() } } return monkeys.map { it.inspected.toLong() }.sortedDescending().let { it[0] * it[1] } } private fun parseInput(): List<Monkey> = readInput("day11") .windowed(6, 7) .map { Monkey.from(it) } } data class Monkey( val items: MutableList<Long>, val operation: Operation, val test: Test, var inspected: Int = 0 ) { fun inspect(item: Long): Long { inspected++ return if (operation.operationType == "+") { item + (operation.value ?: item) } else { item * (operation.value ?: item) } } companion object { fun from(monkey: List<String>): Monkey = Monkey( items = monkey[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList(), operation = monkey[2].substringAfter("= old ").split(" ") .let { Operation(it[0], it[1].toLongOrNull()) }, test = Test( monkey[3].substringAfter("Test: divisible by ").toLong(), monkey[4].substringAfter("If true: throw to monkey ").toInt(), monkey[5].substringAfter("If false: throw to monkey ").toInt() ) ) } } data class Operation(val operationType: String, val value: Long?) data class Test(val divisibleBy: Long, val monkeyTrue: Int, val monkeyFalse: Int) fun main() { println(Day11.part1()) println(Day11.part2()) }
0
Kotlin
0
0
c3eff4f4c52ded907f2af6352dd7b3532a2da8c5
2,296
advent-of-code-2022
Apache License 2.0
src/Day12.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
fun main() { operator fun List<CharArray>.get(point: Pair<Int, Int>) = this[point.first][point.second] fun neighbors( current: Pair<Int, Int>, input: List<CharArray>, validator: (Char, Char) -> Boolean, ) = listOf( current.copy(first = current.first - 1), current.copy(first = current.first + 1), current.copy(second = current.second - 1), current.copy(second = current.second + 1) ) .filter { val (i, j) = it if (i < 0 || j < 0 || i >= input.size || j >= input[0].size) false else validator(input[current], input[it]) } fun bfs( input: List<CharArray>, current: Pair<Int, Int>, visitor: (first: Char, second: Char) -> Boolean ): HashMap<Pair<Int, Int>, Int> { val results = hashMapOf(current to 0) val visit = ArrayDeque(listOf(current)) while (visit.isNotEmpty()) { val first = visit.removeFirst() for (neighbor in neighbors(first, input, visitor)) { if (results.containsKey(neighbor)) continue results[neighbor] = results[first]!! + 1 visit.add(neighbor) } } return results } val visitor = { first: Char, second: Char -> val end = first in 'y'..'z' && second == 'E' val start = first == 'S' && second in 'a'..'b' val validJump = first.isLowerCase() && second.isLowerCase() && first.code - second.code >= -1 end || start || validJump } fun part1(input: List<String>): Int { val x = input.filter(String::isNotBlank).map(String::toCharArray) val start = x.mapIndexed { index, c -> index to c.indexOf('S') }.first { (a, b) -> (a >= 0) and (b >= 0) } val finish = x.mapIndexed { index, c -> index to c.indexOf('E') }.first { (a, b) -> (a >= 0) and (b >= 0) } return bfs(x, start, visitor)[finish]!! } fun part2(input: List<String>): Int { val coords = arrayListOf<Pair<Int, Int>>() val x = input.filter(String::isNotBlank).map { it.replace('S', 'a').toCharArray() } for ((index, line) in x.withIndex()) { for ((charIndex, char) in line.withIndex()) { if (char == 'a') { coords.add(index to charIndex) } } } val finish = x.mapIndexed { index, c -> index to c.indexOf('E') }.first { (a, b) -> (a >= 0) and (b >= 0) } return coords.minOf { bfs(x, it, visitor)[finish] ?: Int.MAX_VALUE } } val testInput = readInput("Day12_test") val testPart1 = part1(testInput) check(testPart1 == 31) { "Actual result: $testPart1" } val input = readInput("Day12") println(part1(input)) val testPart2 = part2(testInput) check(testPart2 == 29) { "Actual result: $testPart2" } println(part2(input)) }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
2,916
aoc-2022
Apache License 2.0
src/Day08.kt
Cryosleeper
572,977,188
false
{"Kotlin": 43613}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { val numbers = input.toIntMatrix() return countTrees(numbers) } fun part2(input: List<String>): Int { val numbers = input.toIntMatrix() return countScenic(numbers) } // 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)) } private fun List<String>.toIntMatrix(): List<List<Int>> = this.map { line -> line.toList().map { tree -> tree.digitToInt() } } private fun countTrees(input: List<List<Int>>): Int { var result = 0 input.forEachIndexed { lineIndex, line -> line.forEachIndexed { columnIndex, tree -> if (input[lineIndex].subList(0, columnIndex+1).filter { it >= tree }.size == 1) result++ else if (input[lineIndex].subList(columnIndex, input[lineIndex].size).filter { it >= tree }.size == 1) result++ else if (input.subList(0, lineIndex+1).map { it[columnIndex] }.filter { it >= tree }.size == 1) result++ else if (input.subList(lineIndex, input.size).map { it[columnIndex] }.filter { it >= tree }.size == 1) result++ } } return result } private fun countScenic(input: List<List<Int>>): Int { fun viewDistance(distanceToHighTree: Int, distanceToEdge: Int) = if (distanceToHighTree == 0) distanceToEdge else min(distanceToHighTree, distanceToEdge) fun List<Int>.distanceToFirstAsHigh(height: Int) = indexOfFirst { it >= height } + 1 var maxScenic = 0 input.forEachIndexed { lineIndex, line -> line.forEachIndexed { columnIndex, tree -> val toLeft = input[lineIndex].subList(0, columnIndex).asReversed() val leftViewDistance = viewDistance(toLeft.distanceToFirstAsHigh(tree), toLeft.size) val toRight = input[lineIndex].subList(columnIndex+1, input[lineIndex].size) val rightViewDistance = viewDistance(toRight.distanceToFirstAsHigh(tree), toRight.size) val toTop = input.subList(0, lineIndex).asReversed().map { it[columnIndex] } val topViewDistance = viewDistance(toTop.distanceToFirstAsHigh(tree), toTop.size) val toBottom = input.subList(lineIndex+1, input.size).map { it[columnIndex] } val bottomViewDistance = viewDistance(toBottom.distanceToFirstAsHigh(tree), toBottom.size) maxScenic = max(maxScenic, leftViewDistance * rightViewDistance * topViewDistance * bottomViewDistance) } } return maxScenic }
0
Kotlin
0
0
a638356cda864b9e1799d72fa07d3482a5f2128e
2,717
aoc-2022
Apache License 2.0
src/Day08.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
fun Iterable<Int>.product() = fold(1) { acc, elt -> acc * elt } inline fun <T> Iterable<T>.productOf(selector: (T) -> Int) = fold(1) { acc, elt -> acc * selector(elt) } fun <T : List<U>, U> Iterable<T>.column(index: Int) = map { it[index] } inline fun <T : List<U>, U> Iterable<T>.columnOrElse(index: Int, defaultValue: (Int) -> U) = map { it.getOrElse(index, defaultValue) } private data class VantagePoint( val height: Int, val north: List<Int>, val east: List<Int>, val south: List<Int>, val west: List<Int>, ) { val directions = listOf(north, east, south, west) val isVisible = directions.any { it.isEmpty() || it.max() < height } private fun viewDistance(treeLine: List<Int>): Int { val idx = treeLine.indexOfFirst { it >= height } return if (idx == -1) { treeLine.size } else { idx + 1 } } val scenicScore = directions.productOf(::viewDistance) } fun main() { val trees = readInput("Day08").map { it.map(Char::digitToInt) } val vantagePoints = buildList { trees.forEachIndexed { i, row -> row.forEachIndexed { j, height -> val column = trees.column(j) val north = column.take(i).reversed() val east = row.drop(j + 1) val south = column.drop(i + 1) val west = row.take(j).reversed() add(VantagePoint(height, north, east, south, west)) } } } println(vantagePoints.count(VantagePoint::isVisible)) println(vantagePoints.maxOf(VantagePoint::scenicScore)) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
1,631
advent-of-code-2022
Apache License 2.0
src/poyea/aoc/mmxxii/day24/Day24.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day24 import poyea.aoc.utils.readInput data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) fun neighbours(): List<Point> { return listOf(1, 0, -1, 0, 1).zipWithNext().map { (dx, dy) -> Point(x + dx, y + dy) } } } data class Blizzard(val point: Point, val dir: Point) { fun moved(boundary: Point): Blizzard { val next = point + dir return copy( point = when { next.x == 0 -> Point(boundary.x - 1, next.y) next.y == 0 -> Point(next.x, boundary.y - 1) next.x == boundary.x -> Point(1, next.y) next.y == boundary.y -> Point(next.x, 1) else -> next } ) } } data class Valley(val blizzards: List<Blizzard>, val boundary: Point) { val unsafePoints = blizzards.map { it.point }.toSet() fun moved() = copy(blizzards = blizzards.map { it.moved(boundary) }) fun isSafe(point: Point): Boolean { return point !in unsafePoints && point.x >= 1 && point.x < boundary.x && point.y >= 1 && point.y < boundary.y } companion object { fun from(input: List<String>): Valley { return Valley( blizzards = input.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> when (char) { '^' -> Blizzard(Point(x, y), Point(0, -1)) 'v' -> Blizzard(Point(x, y), Point(0, 1)) '<' -> Blizzard(Point(x, y), Point(-1, 0)) '>' -> Blizzard(Point(x, y), Point(1, 0)) else -> null } } }, boundary = Point(input.last().lastIndex, input.lastIndex) ) } } } fun go(newValley: Valley, start: Point, end: Point): Pair<Int, Valley> { var minutes = 0 var valley = newValley var batch = setOf(start) while (true) { ++minutes valley = valley.moved() batch = buildSet { batch.forEach { current -> addAll( current .neighbours() .onEach { if (it == end) return minutes to valley } .filter(valley::isSafe) ) if (valley.isSafe(current) || current == start) add(current) } } } } fun part1(input: String): Int { val lines = input.lines() val valley = Valley.from(lines) val start = Point(lines.first().indexOf('.'), 0) val end = Point(lines.last().indexOf('.'), lines.lastIndex) return go(valley, start, end).first } fun part2(input: String): Int { val lines = input.lines() val valley = Valley.from(lines) val start = Point(lines.first().indexOf('.'), 0) val end = Point(lines.last().indexOf('.'), lines.lastIndex) val first = go(valley, start, end) val second = go(first.second, end, start) val third = go(second.second, start, end) return first.first + second.first + third.first } fun main() { println(part1(readInput("Day24"))) println(part2(readInput("Day24"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
3,443
aoc-mmxxii
MIT License
src/year_2023/day_11/Day11.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_11 import readInput import util.Point data class Universe( val galaxies: List<Point>, val horizontalExpansions: List<Int>, val verticalExpansions: List<Int> ) object Day11 { /** * */ fun distances(text: List<String>, age: Int): Long { val distances = mutableMapOf<Pair<Point, Point>, Long>() val universe = parseUniverse(text) universe.galaxies.forEach { galaxy -> universe.galaxies.filter { it != galaxy }.forEach { otherGalaxy -> if (!distances.containsKey(galaxy to otherGalaxy) && !distances.containsKey(otherGalaxy to galaxy)) { distances[galaxy to otherGalaxy] = calculateDistance(galaxy, otherGalaxy, universe, age) } } } return distances.values.sum() } private fun parseUniverse(text: List<String>): Universe { val galaxies = mutableListOf<Point>() val horizontalExpansions = mutableListOf<Int>() val verticalExpansions = mutableListOf<Int>() text.forEachIndexed { y, line -> line.forEachIndexed { x, char -> if (char == '#') { galaxies.add(x to y) } } } text.forEachIndexed { y, line -> if (line.all { it == '.' }) { verticalExpansions.add(y) } } for (x in text.first().indices) { if (text.all { it[x] == '.'} ) { horizontalExpansions.add(x) } } return Universe( galaxies = galaxies, horizontalExpansions = horizontalExpansions, verticalExpansions = verticalExpansions ) } private fun calculateDistance(pointA: Point, pointB: Point, universe: Universe, age: Int): Long { var hDiff = 0L val left = if (pointA.first < pointB.first) pointA.first else pointB.first val right = if (pointA.first > pointB.first) pointA.first else pointB.first for (x in left until right) { hDiff += 1 if (x in universe.horizontalExpansions) { hDiff += age - 1 } } var vDiff = 0L val top = if (pointA.second < pointB.second) pointA.second else pointB.second val bottom = if (pointA.second > pointB.second) pointA.second else pointB.second for (y in top until bottom) { vDiff += 1 if (y in universe.verticalExpansions) { vDiff += age - 1 } } return hDiff + vDiff } } fun main() { val text = readInput("year_2023/day_11/Day11.txt") val solutionOne = Day11.distances(text, 2) println("Solution 1: $solutionOne") val solutionTwo = Day11.distances(text, 1_000_000) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,883
advent_of_code
Apache License 2.0
2021/src/day13/Day13.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day13 import readInput data class Point(val x: Int, val y: Int) sealed class Fold { data class Up(val y: Int) : Fold() data class Left(val x: Int) : Fold() } fun List<String>.toPoints() = filter { !it.contains("fold") }.map { val x = it.split(",")[0] val y = it.split(",")[1] Point(x.toInt(), y.toInt()) } fun List<String>.toFolds() = filter { it.contains("fold") }.map { when { it.contains("y=") -> Fold.Up(it.substringAfter("y=").toInt()) it.contains("x=") -> Fold.Left(it.substringAfter("x=").toInt()) else -> null } }.filterNotNull() // transform the list of coordonnates to an Array<CharArray> containing '.' or '#' fun List<String>.toTable(): Array<CharArray>? { val points = this.toPoints() val maxX = points.maxByOrNull { it.x } ?: return null val maxY = points.maxByOrNull { it.y } ?: return null val table = Array(maxY.y + 1) { CharArray(maxX.x + 1) { '.' } } points.forEach { table[it.y][it.x] = '#' } return table } fun applyFold(table: Array<CharArray>, fold: Fold) : Array<CharArray> { val newMaxY = if (fold is Fold.Up) { fold.y } else { table.size } val newMaxX = if (fold is Fold.Left) { fold.x } else { table[0].size } val newTable = Array(newMaxY) { CharArray(newMaxX) { '.' } } // Apply folding for (y in 0 until table.size) { for (x in 0 until table[0].size) { if (y < newMaxY && x < newMaxX) { newTable[y][x] = table[y][x] } else if (y > newMaxY || x > newMaxX) { // if maxSize == 7, then 8 -> 6, 9 -> 5, 10 -> 4, 14 -> 0 val foldedY = if (y > newMaxY) { newMaxY - (((y / newMaxY - 1) * newMaxY) + y % newMaxY) } else { y } val foldedX = if (x > newMaxX) { newMaxX - (((x / newMaxX - 1) * newMaxX) + x % newMaxX) } else { x } if (table[y][x] == '#') { newTable[foldedY][foldedX] = table[y][x] } } } } return newTable } fun part1(lines: List<String>) : Int { val table = lines.toTable() ?: return -1 return applyFold(table, lines.toFolds().first()).toList().map { it.toList().count { it == '#' } }.sum() } fun part2(lines: List<String>) : Int { var table = lines.toTable() ?: return -1 for (fold in lines.toFolds()) { table = applyFold(table, fold) } for (l in table) println(l) // Just read the output in terminal :) return table.toList().map { it.toList().count { it == '#' } }.sum() } fun main() { val testInput = readInput("day13/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day13/input") println("part1(input) => " + part1(input)) println("part1(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,932
advent-of-code
Apache License 2.0
src/Day08.kt
SimoneStefani
572,915,832
false
{"Kotlin": 33918}
fun main() { class Forest(private val rows: List<List<Int>>) { private fun isVisible(r: Int, c: Int): Boolean = (0 until c).all { rows[r][it] < rows[r][c] } || (c + 1 until rows[0].size).all { rows[r][it] < rows[r][c] } || (0 until r).all { rows[it][c] < rows[r][c] } || (r + 1 until rows.size).all { rows[it][c] < rows[r][c] } private fun score(r: Int, c: Int): Int = (c - 1 downTo 0).takeWhile { rows[r][it] >= rows[r][c] }.size * (c + 1 until rows[0].size).takeWhile { rows[r][it] >= rows[r][c] }.size * (r - 1 downTo 0).takeWhile { rows[it][c] >= rows[r][c] }.size * (r + 1 until rows.size).takeWhile { rows[it][c] >= rows[r][c] }.size fun maxScenicScore(): Int = (1 until rows.size - 1).maxOf { r -> (1 until rows[0].size - 1).maxOf { c -> score(r, c) } } fun countVisible(): Int = (rows.indices).sumOf { r -> (0 until rows[r].size).count { c -> isVisible(r, c) } } } fun loadForest(lines: List<String>): Forest = Forest(lines.map { line -> line.map { it.code - '0'.code }.toList() }.toList()) fun part1(input: List<String>): Int { return loadForest(input).countVisible() } fun part2(input: List<String>): Int { return loadForest(input).maxScenicScore() } 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
0
0
b3244a6dfb8a1f0f4b47db2788cbb3d55426d018
1,622
aoc-2022
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day19/day19.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day19 import eu.janvdb.aocutil.kotlin.readGroupedLines //const val FILENAME = "input19-test.txt" const val FILENAME = "input19.txt" val VARIABLES = listOf("x", "m", "a", "s") const val MIN_VALUE = 1 const val MAX_VALUE = 4000 fun main() { val lines = readGroupedLines(2023, FILENAME) val rules = Rules.parse(lines[0]) val parts = lines[1].map(Part::parse) part1(parts, rules) part2(rules) } private fun part1(parts: List<Part>, rules: Rules) { val acceptedParts = parts.filter(rules::evaluate) println(acceptedParts.sumOf { it.rating }) } private fun part2(rules: Rules) { val ranges = VARIABLES.associateWith { MIN_VALUE..MAX_VALUE } val result = rules.countAccepted("in", ranges) println(result) } data class Rules(val rules: Map<String, Rule>) { fun evaluate(part: Part): Boolean { var current = "in" while (!current.isAccepted() && !current.isRejected()) { val rule = rules[current]!! current = rule.evaluate(part) } return current.isAccepted() } fun countAccepted(outcome: String, ranges: Map<String, IntRange>, index: Int = 0): Long { val spaces = (0..<index).joinToString("", "", "+-") { "| " } println("$spaces$ranges -> $outcome") if (outcome.isAccepted()) return 1L * ranges.values.fold(1L) { acc, range -> acc * (range.last - range.first + 1) } if (outcome.isRejected()) return 0L if (ranges.values.any { it.last < it.first }) return 0L val rule = rules[outcome]!! var currentRanges = ranges var sum = 0L rule.conditions.forEach { condition -> val currentRange = currentRanges[condition.variable]!! val newRange1 = if (condition.operation == Operation.LT) currentRange.first..<condition.value else condition.value + 1..currentRange.last val newRange2 = if (condition.operation == Operation.LT) condition.value..currentRange.last else currentRange.first..condition.value val newRanges = currentRanges + Pair(condition.variable, newRange1) sum += countAccepted(condition.outcome, newRanges, index + 1) currentRanges = currentRanges + Pair(condition.variable, newRange2) } sum += countAccepted(rule.defaultOutcome, currentRanges, index + 1) return sum } companion object { fun parse(lines: List<String>): Rules { val rules = lines.map(Rule::parse).associateBy { it.name } return Rules(rules) } } } data class Rule(val name: String, val conditions: List<Condition>, val defaultOutcome: String) { fun evaluate(part: Part): String { return conditions.find { it.matches(part) }?.outcome ?: defaultOutcome } companion object { fun parse(line: String): Rule { val parts = line.split("{") val name = parts[0] val parts2 = parts[1].substring(0, parts[1].length - 1).split(",") val conditions = parts2.subList(0, parts2.size - 1).map(Condition::parse) val defaultOutcome = parts2.last() return Rule(name, conditions, defaultOutcome) } } } data class Condition(val variable: String, val operation: Operation, val value: Int, val outcome: String) { fun matches(part: Part): Boolean { val partValue = part.values[variable]!! return operation.evaluate(partValue, value) } companion object { private val REGEX = Regex("(\\w+)([<>])(\\d+):(\\w+)") fun parse(value: String): Condition { val matchResult = REGEX.matchEntire(value)!! return Condition( matchResult.groupValues[1], Operation.parse(matchResult.groupValues[2]), matchResult.groupValues[3].toInt(), matchResult.groupValues[4] ) } } } enum class Operation(val text: String) { GT(">"), LT("<"); fun evaluate(x: Int, y: Int) = when (this) { LT -> x < y GT -> x > y } companion object { fun parse(value: String) = entries.find { it.text == value }!! } } fun String.isAccepted() = equals("A") fun String.isRejected() = equals("R") data class Part(val values: Map<String, Int>) { val rating = VARIABLES.sumOf { values.getOrDefault(it, 0) } companion object { private val REGEX = Regex("(\\w+)=(\\d+)") fun parse(value: String): Part { val values = REGEX.findAll(value).associate { Pair(it.groupValues[1], it.groupValues[2].toInt()) } return Part(values) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
4,730
advent-of-code
Apache License 2.0
src/twentytwentythree/day07/Day07.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentythree.day07 import readInput import kotlin.math.max enum class HandType(val value: Int) { FIVE_OF_A_KIND(7), FOUR_OF_A_KIND(6), FULL_HOUSE(5), THREE_OF_A_KIND(4), TWO_PAIR(3), ONE_PAIR(2), HIGH_CARD(1), } class Card(private val value: Char) : Comparable<Card> { override fun compareTo(other: Card): Int { return ORDER.indexOf(this.value) - ORDER.indexOf(other.value) } companion object { // Define the order of cards from highest to lowest private val ORDER = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') } } fun main() { class Hand(val value: String) : Comparable<Hand> { val cardsMap = value.toList().groupBy { it } override fun compareTo(other: Hand): Int { val thisType = determineHandType(this) val otherType = determineHandType(other) val typeComparison = thisType.compareTo(otherType) if (typeComparison != 0) { return typeComparison } // If both hands have the same type, compare them card by card for (i in value.indices) { val thisCard = Card(value[i]) val otherCard = Card(other.value[i]) val cardComparison = thisCard.compareTo(otherCard) if (cardComparison != 0) { return cardComparison } } return 0 // Both hands are equal } private fun determineHandType(hand: Hand): HandType { val maxCount = hand.cardsMap.values.maxOfOrNull { it.size } ?: 0 val maxCard = hand.cardsMap.entries.maxByOrNull { it.value.size }!!.key val tempHand = hand.cardsMap.toMutableMap() tempHand.remove(maxCard) val secondMaxCount = tempHand.values.maxOfOrNull { if (it.size <= maxCount) it.size else 0 } ?: 0 return when { maxCount == 5 -> HandType.FIVE_OF_A_KIND maxCount == 4 -> HandType.FOUR_OF_A_KIND maxCount == 3 && secondMaxCount == 2 -> HandType.FULL_HOUSE maxCount == 3 -> HandType.THREE_OF_A_KIND maxCount == 2 && secondMaxCount == 2 -> HandType.TWO_PAIR maxCount == 2 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } } fun part1(input: List<String>): Long { var index = 1 val sorted = input.sortedByDescending { line -> Hand(line.split(" ")[0]) } return sorted.sumOf { line -> line.split(" ")[1].toLong() * index++ } } fun part2(input: List<String>): Int { return 0 } val input = readInput("twentytwentythree/day07", "Day07_input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
2,583
advent-of-code
Apache License 2.0
src/day13/Day13_functional.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day13 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. */ sealed class PacketV2 : Comparable<PacketV2> { companion object { fun of(input: String): PacketV2 = of( input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex()) // split the string on any of "[" or "]" or "," but keep them in the output .filter { it.isNotBlank() } // filter out "" .filter { it != "," } // filter out "," .iterator() // "[1,1,3,1,1]" is now ["[", "1", "1", "3", "1", "1", "]"] ) private fun of(input: Iterator<String>): PacketV2 { val packets = mutableListOf<PacketV2>() while (input.hasNext()) { when (val symbol = input.next()) { "]" -> return ListPacket(packets) "[" -> packets.add(of(input)) else -> packets.add(IntPacket(symbol.toInt())) } } return ListPacket(packets) } } } private class IntPacket(val amount: Int) : PacketV2() { fun asList(): PacketV2 = ListPacket(listOf(this)) override fun compareTo(other: PacketV2): Int = when (other) { is IntPacket -> amount.compareTo(other.amount) is ListPacket -> asList().compareTo(other) } } private class ListPacket(val subPackets: List<PacketV2>) : PacketV2() { override fun compareTo(other: PacketV2): Int = when (other) { is IntPacket -> compareTo(other.asList()) is ListPacket -> subPackets.zip(other.subPackets) // zip will pair together what it can, if list length isn't even those elements are left out .map { it.first.compareTo(it.second) } // compare values within pairs .firstOrNull { it != 0 } ?: subPackets.size.compareTo(other.subPackets.size) // if condition isn't found, compare list length } } private fun part1(input: List<String>): Int { val packets = input.filter { it.isNotBlank() }.map { PacketV2.of(it) } return packets.chunked(2).mapIndexed { index, pair -> // compare two packets at a time if (pair.first() < pair.last()) index + 1 else 0 // if first < second, add index+1 to sum result }.sum() } private fun part2(input: List<String>): Int { val packets = input.filter { it.isNotBlank() }.map { PacketV2.of(it) } val dividerPacket1 = PacketV2.of("[[2]]") val dividerPacket2 = PacketV2.of("[[6]]") val ordered = (packets + dividerPacket1 + dividerPacket2).sorted() return (ordered.indexOf(dividerPacket1) + 1) * (ordered.indexOf(dividerPacket2) + 1) } fun main() { println(part1(readLines("day13/test"))) println(part2(readLines("day13/test"))) println(part1(readLines("day13/input"))) println(part2(readLines("day13/input"))) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
3,055
aoc2022
Apache License 2.0
src/Day08.kt
dmarcato
576,511,169
false
{"Kotlin": 36664}
data class Pos(val x: Int, val y: Int) fun main() { fun List<String>.atPos(pos: Pos): Int = this[pos.y][pos.x].digitToInt() fun visible(input: List<String>, pos: Pos, maxX: Int, maxY: Int): Boolean { val tree = input.atPos(pos) return (pos.x - 1 downTo 0).all { tree > input.atPos(Pos(it, pos.y)) } || (pos.x + 1 until maxX).all { tree > input.atPos(Pos(it, pos.y)) } || (pos.y - 1 downTo 0).all { tree > input.atPos(Pos(pos.x, it)) } || (pos.y + 1 until maxY).all { tree > input.atPos(Pos(pos.x, it)) } } fun Iterable<Int>.countWhileMatchOrEnd(condition: (Int) -> Boolean): Int { var count = 0 this.asSequence().forEach { i -> count++ if (!condition(i)) { return count } } return count } fun scenicScore(input: List<String>, pos: Pos, maxX: Int, maxY: Int): Int { val tree = input.atPos(pos) val left = (pos.x - 1 downTo 0).countWhileMatchOrEnd { tree > input.atPos(Pos(it, pos.y)) } val right = (pos.x + 1 until maxX).countWhileMatchOrEnd { tree > input.atPos(Pos(it, pos.y)) } val top = (pos.y - 1 downTo 0).countWhileMatchOrEnd { tree > input.atPos(Pos(pos.x, it)) } val bottom = (pos.y + 1 until maxY).countWhileMatchOrEnd { tree > input.atPos(Pos(pos.x, it)) } return left * right * top * bottom } fun part1(input: List<String>): Int { val maxX = input.first().length val maxY = input.size val extras = (1 until maxY - 1).sumOf { y -> (1 until maxX - 1).count { x -> visible(input, Pos(x, y), maxX, maxY) } } return (maxX * 2 + maxY * 2 - 4) + extras } fun part2(input: List<String>): Int { val maxX = input.first().length val maxY = input.size val max = (1 until maxY - 1).maxOf { y -> (1 until maxX - 1).maxOf { x -> scenicScore(input, Pos(x, y), maxX, maxY) } } return max } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") check(part1(testInput) == 21) { "part1 check failed" } check(part2(testInput) == 8) { "part2 check failed" } val input = readInput("Day08") part1(input).println() part2(input).println() }
0
Kotlin
0
0
6abd8ca89a1acce49ecc0ca8a51acd3969979464
2,362
aoc2022
Apache License 2.0
advent-of-code-2023/src/Day08.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
private const val DAY = "Day08" fun main() { fun input() = readInput(DAY) "Part 1" { fun testInput0() = readInput("${DAY}_test0") fun testInput1() = readInput("${DAY}_test1") part1(testInput0()) shouldBe 2 part1(testInput1()) shouldBe 6 measureAnswer { part1(input()) } } "Part 2" { fun testInput() = readInput("${DAY}_test2") part2(testInput()) shouldBe 6 measureAnswer { part2(input()) } } } private fun part1(input: DessertMap): Int = input.countCycles(fromNode = "AAA") { it == "ZZZ" } * input.stepsInCycle private fun part2(input: DessertMap): Long { // Assumption is that number of cycles for each node is a prime number. return input.nodes.keys.filter { it.endsWith("A") } .map { startNode -> input.countCycles(startNode) { it.endsWith("Z") }.toLong() } .reduce(Long::times) * input.stepsInCycle } private fun readInput(name: String): DessertMap { val (instructions, rawNodes) = readText(name).split("\n\n") return DessertMap( instructions = instructions, nodes = rawNodes.lineSequence().associate { line -> val (nodeId, directions) = line.split(" = ") val (leftNode, rightNode) = directions.trim('(', ')').split(", ") nodeId to MapNode(leftNode, rightNode) }, ) } private data class DessertMap( val instructions: String, val nodes: Map<String, MapNode> ) { val stepsInCycle = instructions.length fun countCycles(fromNode: String, predicate: (String) -> Boolean): Int { var steps = 0 var currentNode = fromNode fun instruction() = instructions[(steps - 1) % stepsInCycle] while (steps % stepsInCycle != 0 || !predicate(currentNode)) { steps++ currentNode = nodes.getValue(currentNode).nextNode(instruction()) } return steps / stepsInCycle } } private data class MapNode(val leftNode: String, val rightNode: String) { fun nextNode(instruction: Char) = when (instruction) { 'L' -> leftNode 'R' -> rightNode else -> error("Unexpected instruction: $instruction") } }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,189
advent-of-code
Apache License 2.0
src/day15/Day15.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day15 import readInput import kotlin.math.abs fun dist(fst: Pair<Int, Int>, snd: Pair<Int, Int>): Int = abs(fst.first - snd.first) + abs(fst.second - snd.second) fun Pair<Int, Int>.add(x: Pair<Int, Int>) = Pair(this.first + x.first, this.second + x.second) fun Pair<Int, Int>.multiplyPairwise(x: Pair<Int, Int>) = Pair(this.first * x.first, this.second * x.second) fun main() { fun getBeaconsAtRow( input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>, row: Int, ): Set<Pair<Int, Int>> { val reachable = mutableSetOf<Pair<Int, Int>>() input.forEach { val dist = dist(it.first, it.second) var offset = 0 var added = true while (added) { added = false val p1 = Pair(it.first.first + offset, row) val p2 = Pair(it.first.first - offset, row) if (dist(it.first, p1) <= dist) { reachable.add(p1) added = true } if (dist(it.first, p2) <= dist) { reachable.add(p2) added = true } offset++ } } reachable.removeAll(input.map { it.second }.toSet()) return reachable } fun part1(input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>, row: Int): Int { val reachable = getBeaconsAtRow(input, row) return reachable.size } fun part2(input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>, maxCoordinate: Int): Long { input.forEach { inputEntry -> val (sensor, beacon) = inputEntry val dist = dist(sensor, beacon) for (xOffset in 0..dist) { val yOffset = dist - xOffset + 1 val candidates = listOf(Pair(1, 1), Pair(1, -1), Pair(-1, 1), Pair(-1, -1)) .map { it.multiplyPairwise(Pair(xOffset, yOffset)).add(sensor) } .filter { it.first in 0..maxCoordinate && it.second in 0..maxCoordinate } for (candidate in candidates) { if (input.all { dist(it.first, candidate) > dist(it.first, it.second) }) { return candidate.first.toLong() * 4000000L + candidate.second.toLong() } } } } throw IllegalStateException("No Solution") } fun preprocess(input: List<String>): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> = input.map { val split = it.split(" ") Pair( Pair( split[2].removePrefix("x=").removeSuffix(",").toInt(), split[3].removePrefix("y=").removeSuffix(":").toInt() ), Pair( split[8].removePrefix("x=").removeSuffix(",").toInt(), split[9].removePrefix("y=").toInt() ) ) } // test if implementation meets criteria from the description, like: val testInput = readInput(15, true) check(part1(preprocess(testInput), 10) == 26) val input = readInput(15) println(part1(preprocess(input), 2000000)) check(part2(preprocess(testInput), 20) == 56000011L) println(part2(preprocess(input), 4000000)) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
3,262
advent-of-code-2022
Apache License 2.0
2021/src/day14/Day14.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day14 import readInput fun List<String>.toPairInsertions() : Map<String, String> { val map = mutableMapOf<String, String>() filter { it.contains("->") }.forEach { map[it.substringBefore("->").trim()] = it.substringAfter("->").trim() } return map } fun applyStep(start: String, pairs: Map<String, String>) : String { val newStr = StringBuilder() for (i in start.indices) { newStr.append(start[i]) if (i + 1 < start.length) { val key = "${start[i]}${start[i + 1]}" if (pairs.contains(key)) { newStr.append(pairs[key]) } } } return newStr.toString() } fun part1(lines: List<String>) : Int { var polymerTemplate = lines.first() val pairInsertions = lines.toPairInsertions() val numberOfSteps = 10 for (i in 0 until numberOfSteps) { polymerTemplate = applyStep(polymerTemplate, pairInsertions) } val lettersToOccurrences = polymerTemplate.toList().groupingBy { it }.eachCount() val maxLetter = lettersToOccurrences.maxOfOrNull { it.value } ?: return -1 val minLetter = lettersToOccurrences.minOfOrNull { it.value } ?: return -1 return maxLetter - minLetter } fun part2(lines: List<String>) : Long { val polymerTemplate = lines.first() val pairInsertions = lines.toPairInsertions() val numberOfSteps = 40 val pairs = mutableMapOf<String, Long>() for (i in polymerTemplate.indices) { // NNCB => {NN=1, NC=1, CB=1} if (i + 1 < polymerTemplate.length) { val key = "${polymerTemplate[i]}${polymerTemplate[i + 1]}" pairs[key] = pairs.getOrDefault(key, 0) + 1 } } // Applying the steps by pairs => [NN] becomes [NC] & [CN] for (i in 0 until numberOfSteps) { val tmp = mutableMapOf<String, Long>() for ((key, value) in pairs) { pairInsertions[key]?.let { replacement -> val firstKey = ""+key.first() + replacement.first() val secondKey = ""+replacement.first() + key.last() tmp[firstKey] = tmp.getOrDefault(firstKey, 0) + value tmp[secondKey] = tmp.getOrDefault(secondKey, 0) + value } } pairs.clear() pairs.putAll(tmp) } // Calculate the totals val totals = mutableMapOf<Char, Long>() totals[polymerTemplate.first()] = 1 for ((k, v) in pairs) { totals[k.last()] = totals.getOrDefault(k.last(), 0) + v } val sorted = totals.toList().map { it.second }.sortedDescending() return sorted.first() - sorted.last() } fun main() { val testInput = readInput("day14/test") println("part1(testInput) => " + part1(testInput)) println("part2(testInput) => " + part2(testInput)) val input = readInput("day14/input") println("part1(input) => " + part1(input)) println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,924
advent-of-code
Apache License 2.0
src/main/kotlin/com/hopkins/aoc/day2/main.kt
edenrox
726,934,488
false
{"Kotlin": 88215}
package com.hopkins.aoc.day2 import java.io.File const val debug = false const val part = 2 val maxCubes = CubeInfo(red = 12, green = 13, blue = 14) /** Advent of Code 2023: Day 2 */ fun main() { val inputFile = File("input/input2.txt") if (debug) { println("Max Cubes: $maxCubes") } // Extract the GameInfo from each line val gameInfoList: List<GameInfo> = inputFile.readLines().map { line -> parseGame(line) } if (debug) { gameInfoList.take(5).map { println("Game: ${it.id} isValid: ${it.isValid(maxCubes)}") } } if (part == 1) { // Sum the Game IDs where the game is valid given the max number of cubes val gameIdSum: Int = gameInfoList.filter { it.isValid(maxCubes) }.map { it.id }.sum() println("gameIdSum: $gameIdSum") // 2771 } else { val powerSum: Int = gameInfoList.sumOf { game -> val minCubes = findMinCubes(game.cubes) minCubes.red * minCubes.green * minCubes.blue } println("Power Sum: $powerSum") // 70924 } } /** Returns the minimum number of cubes of each color required to play the specified set of games. */ fun findMinCubes(cubes: List<CubeInfo>): CubeInfo = CubeInfo( cubes.maxOf { it.red }, cubes.maxOf { it.green }, cubes.maxOf { it.blue } ) /** Parse a [GameInfo] from a line of input. */ fun parseGame(line: String): GameInfo { // Example line: // Game <Id>: <CubeInfo>; <CubeInfo>; ... val parts = line.split(":", ";") val id = parts[0].substring(startIndex = 5).toInt() return GameInfo(id, parts.drop(1).map { parseCubeInfo(it) }) } /** Parse a [CubeInfo] from a single draw. */ fun parseCubeInfo(cubeInfo: String): CubeInfo { // Example draw: // <X> red, <Y> green, <Z> blue val parts = cubeInfo.split(",") var (red, green, blue) = listOf(0, 0, 0) parts.map { parseCube(it) }.forEach { (color, num) -> when (color) { "red" -> red += num "green" -> green += num "blue" -> blue += num } } return CubeInfo(red, green, blue) } /** Parse the color and count of cubes drawn. */ fun parseCube(cube: String): Pair<String, Int> { // Example cube val parts = cube.trim().split(" ") return Pair(parts[1], parts[0].toInt()) } class GameInfo(val id: Int, val cubes: List<CubeInfo>) { /** Returns `true` if the cube draws of this game are valid given the specifed [maxCubes]. */ fun isValid(maxCubes: CubeInfo): Boolean = !cubes.any { it.isAnyGreaterThan(maxCubes) } override fun toString(): String = "GameInfo id=${id} cubes=${cubes}" } class CubeInfo(val red: Int, val green: Int, val blue: Int) { /** Returns `true` if any of the draws are greater than the specified max number of cubes. */ fun isAnyGreaterThan(max: CubeInfo): Boolean = red > max.red || green > max.green || blue > max.blue override fun toString(): String = "r=${red} g=${green} b=${blue}" }
0
Kotlin
0
0
45dce3d76bf3bf140d7336c4767e74971e827c35
2,995
aoc2023
MIT License
src/main/kotlin/solutions/day24/Day24.kt
Dr-Horv
112,381,975
false
null
package solutions.day24 import solutions.Solver data class Component(val port1: Int, val port2: Int) { override fun toString(): String { return "$port1/$port2" } } fun List<Component>.strength(): Int = this.sumBy { it.port1 + it.port2 } class Day24: Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val components = input.map { val (port1, port2) = it.split("/") Component(port1.toInt(), port2.toInt()) } var maxStrength = Int.MIN_VALUE var strongestLongest = listOf<Component>() components.filter { it.port1 == 0 || it.port2 == 0 } .forEach { val isPort1 = it.port1 == 0 val bridges = doBridge(it, isPort1, components.filter { c -> c != it }) bridges.forEach { val strength = it.strength() if(strength > maxStrength) { maxStrength = strength } } if(partTwo) { val sortedBy = bridges.sortedBy(List<Component>::size).reversed() println(sortedBy.first().size) val candidate = sortedBy.filter { it.size == sortedBy.first().size } .reduce { acc, list -> if (list.strength() > acc.strength()) { list } else { acc } } when { candidate.size > strongestLongest.size -> strongestLongest = candidate candidate.size == strongestLongest.size && candidate.strength() > strongestLongest.strength() -> strongestLongest = candidate } } } return if(!partTwo) { maxStrength.toString() } else { strongestLongest.strength().toString() } } private fun doBridge(start: Component, isPort1: Boolean, rest: List<Component>, currentBridge: List<Component> = listOf()): List<List<Component>> { val bridges = mutableListOf<List<Component>>() val newCurrentBridge = currentBridge.toMutableList() newCurrentBridge.add(start) bridges.add(newCurrentBridge) val filterRule = if(isPort1) { {c: Component -> c.port1 == start.port2 || c.port2 == start.port2 } } else { {c: Component -> c.port1 == start.port1 || c.port2 == start.port1 } } val possibleComponents = rest.filter(filterRule) possibleComponents.forEach { val newIsPort1 = if(isPort1) { it.port1 == start.port2 } else { it.port1 == start.port1 } val newBridges = doBridge(it, newIsPort1, rest.filter { c -> c != it }, newCurrentBridge) bridges.addAll(newBridges) } return bridges } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
3,167
Advent-of-Code-2017
MIT License
lib/src/main/kotlin/com/bloidonia/advent/day12/Day12.kt
timyates
433,372,884
false
{"Kotlin": 48604, "Groovy": 33934}
package com.bloidonia.advent.day12 import com.bloidonia.advent.readList fun String.isUpper() = this.first().isUpperCase() fun String.isLower() = this.first().isLowerCase() class CaveSystem(private val routes: Map<String, List<String>>) { fun next(path: List<String>, check: (List<String>, String) -> Boolean) = routes[path.last()] ?.filter { cave -> check(path, cave) } ?.filter { cave -> cave != "start" } ?.map { path + it } ?: listOf() val part1Check = { path: List<String>, cave: String -> cave.isUpper() || path.count { it == cave } < 1 } val part2Check = { path: List<String>, cave: String -> part1Check(path, cave) || !path.filter { it.isLower() }.groupingBy { it }.eachCount().any { it.value > 1 } } fun allRoutes(check: (List<String>, String) -> Boolean): List<List<String>> { var listRoutes = listOf(listOf("start")) val result = mutableListOf<List<String>>() while (listRoutes.isNotEmpty()) { listRoutes = listRoutes.flatMap { next(it, check) } result += listRoutes.filter { it.contains("end") } listRoutes = listRoutes.filter { !it.contains("end") } } return result.distinct() } private fun mustPassASmallCave(route: List<String>) = route.any { it.isLower() && it != "end" } fun part1(): Int = allRoutes(part1Check).filter(::mustPassASmallCave).size fun part2() = allRoutes(part2Check).filter(::mustPassASmallCave).size } fun List<String>.parseCaves() = CaveSystem(this.map { it.split("-", limit = 2) }.let { splits -> splits.flatten().distinct().fold(mutableMapOf()) { acc, s -> acc[s] = splits.filter { it.contains(s) }.flatten().distinct().minus(s); acc } }) fun main() { println(readList("/day12input.txt").parseCaves().part1()) println(readList("/day12input.txt").parseCaves().part2()) }
0
Kotlin
0
1
9714e5b2c6a57db1b06e5ee6526eb30d587b94b4
1,941
advent-of-kotlin-2021
MIT License
src/Day04.kt
astrofyz
572,802,282
false
{"Kotlin": 124466}
fun main() { fun part1(input: List<String>): Int { return input.map {elves -> elves.replace(',', '-').split('-').map { it.toInt() } } .count{edges -> (((edges[2] >= edges[0]) and (edges[1] >= edges[3] )) or ((edges[0] >= edges[2]) and (edges[3] >= edges[1] )))} // learned about .count in stream // .sumOf { edges -> // (((edges[2] >= edges[0]) and (edges[1] >= edges[3] )) // or ((edges[0] >= edges[2]) and (edges[3] >= edges[1] ))).compareTo(false) } } fun part2(input: List<String>): Int { return input.map {elves -> elves.replace(',', '-').split('-').map { it.toInt() } } .count { edges -> ((edges[2] <= edges[1]) and (edges[0] <= edges[3]))} // learned short way to compare, felt a bit ashamed and amazed // (((edges[2] >= edges[0]) and (edges[3] >= edges[1] ) and (edges[1] >= edges[2])) // or ((edges[0] >= edges[2]) and (edges[1] >= edges[3]) and (edges[3] >= edges[0])) // or ((edges[2] >= edges[0]) and (edges[1] >= edges[3] )) // or ((edges[0] >= edges[2]) and (edges[3] >= edges[1] ))) // .compareTo(false) } } // 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
a0bc190b391585ce3bb6fe2ba092fa1f437491a6
1,532
aoc22
Apache License 2.0
src/main/kotlin/dev/tasso/adventofcode/_2021/day09/Day09.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2021.day09 import dev.tasso.adventofcode.Solution class Day09 : Solution<Int> { override fun part1(input: List<String>): Int { val heightMap = input.map{ row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray() return getLowPointCoordinates(heightMap).sumOf { (rowIndex, colIndex) -> heightMap[rowIndex][colIndex] + 1 } } override fun part2(input: List<String>): Int { val heightMap = input.map{ row -> row.toCharArray().map { it.digitToInt() }.toTypedArray() }.toTypedArray() return getLowPointCoordinates(heightMap).map{ lowPointCoords -> getBasinSize(heightMap, lowPointCoords) } .sorted() .takeLast(3) .reduce { acc, i -> acc * i } } } fun getLowPointCoordinates(heightMap : Array<Array<Int>>): List<Pair<Int, Int>> { val lowPointCoordinates = mutableListOf<Pair<Int,Int>>() heightMap.forEachIndexed { rowIndex, row -> row.forEachIndexed { colIndex, height -> val adjacentCoordinate = getAdjacentCoordinates(heightMap, rowIndex, colIndex) if(adjacentCoordinate.all{ (col,row) -> heightMap[col][row] > height}) { lowPointCoordinates.add(Pair(rowIndex,colIndex)) } } } return lowPointCoordinates.toList() } fun getAdjacentCoordinates(heightMap : Array<Array<Int>>, rowIndex : Int, colIndex : Int): List<Pair<Int,Int>> { return listOfNotNull( //North if(rowIndex > 0) Pair(rowIndex-1,colIndex) else null, //South if(rowIndex < heightMap.size-1) Pair(rowIndex+1,colIndex) else null, //West if(colIndex > 0) Pair(rowIndex,colIndex-1) else null, //East if(colIndex < heightMap[0].size-1) Pair(rowIndex, colIndex+1) else null ) } fun getBasinSize(heightMap : Array<Array<Int>>, coords : Pair<Int,Int>, visitedSet : MutableSet<Pair<Int, Int>> = mutableSetOf()) : Int { return if(heightMap[coords.first][coords.second] == 9 || visitedSet.contains(coords)) { 0 } else { visitedSet.add(coords) 1 + getAdjacentCoordinates(heightMap, coords.first, coords.second).sumOf { adjacentCoordinate -> getBasinSize(heightMap, adjacentCoordinate, visitedSet)} } }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,499
advent-of-code
MIT License
src/Day07.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
fun main() { val input = readInput("Day07") fun String.parse(): Triple<Map<Char, Int>, Long, String> { val (hand, bid) = split(" ").let { it[0] to it[1].toLong() } val h = mutableMapOf<Char, Int>() for (c in hand) { h[c] = 1 + (h[c] ?: 0) } return Triple(h, bid, this) } fun List<Int>.rank(): Int { return when (this) { listOf(5) -> 1 listOf(1, 4) -> 2 listOf(2, 3) -> 3 listOf(1, 1, 3) -> 4 listOf(1, 2, 2) -> 5 listOf(1, 1, 1, 2) -> 6 else -> 7 } } fun Map<Char, Int>.score() = this.values.sorted().rank() fun Char.score(): Int { return when (this) { 'A' -> 1 'K' -> 2 'Q' -> 3 'J' -> 4 'T' -> 5 else -> 10 - this.digitToInt() + 5 } } val compareHands = Comparator<Triple<Map<Char, Int>, Long, String>> { h1, h2 -> if (h1.first.score() != h2.first.score()) return@Comparator h1.first.score() - h2.first.score() (0..4).forEach { val p1 = h1.third[it] val p2 = h2.third[it] if (p1 != p2) return@Comparator p1.score() - p2.score() } error("this should never happen") } fun Map<Char, Int>.score2(): Int { val h = this.values.sorted().toMutableList() //.also { it.println() } val countJ = this['J'] ?: 0 val i = h.lastIndexOf(countJ) if (i >= 0) h.removeAt(i) if (h.size == 0) h.add(5) else h[h.size - 1] += countJ return h.rank() } fun Char.score2(): Int { return when (this) { 'A' -> 1 'K' -> 2 'Q' -> 3 'J' -> 15 // J gets dwarfed 'T' -> 5 else -> 10 - this.digitToInt() + 5 } } val compareHands2 = Comparator<Triple<Map<Char, Int>, Long, String>> { h1, h2 -> if (h1.first.score2() != h2.first.score2()) return@Comparator h1.first.score2() - h2.first.score2() (0..4).forEach { val p1 = h1.third[it] val p2 = h2.third[it] if (p1 != p2) return@Comparator p1.score2() - p2.score2() } error("this should never happen") } fun part1(input: List<String>): Long { return input.map { it.parse() } .sortedWith(compareHands) .reversed() .mapIndexed { i, v -> (i + 1) * v.second } .sum() } fun part2(input: List<String>): Long { return input.map { it.parse() } .sortedWith(compareHands2) .reversed() .mapIndexed { i, v -> (i + 1) * v.second } .sum() } part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
3,051
aoc-2023
Apache License 2.0
src/day13/Day13.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day13 import readInput fun main() { println(solve1(parse(readInput("day13/test")))) println(solve1(parse(readInput("day13/input")))) println(solve2(parse(readInput("day13/test")))) println(solve2(parse(readInput("day13/input")))) } fun compare(left: Element, right: Element): Int { fun compareComp(left: Composite, right: Composite): Int { val lc = left.children val rc = right.children for (i in lc.indices) { if (i >= rc.size) return 1 val r = compare(lc[i], rc[i]) if (r != 0) return r } return if (lc.size == rc.size) 0 else -1 } return if (left is Leaf) { if (right is Leaf) left.v - right.v else compare(Composite(left), right) } else { if (right is Leaf) compare(left, Composite(right)) else compareComp( left as Composite, right as Composite ) } } fun solve2(input: List<Element>): Int { val toSort = (input + parse(listOf("[[2]]", "[[6]]"))) val sorted = toSort.sortedWith { a, b -> compare(a, b) } val f = sorted.indexOfFirst { it.toString() == "[[2]]" } + 1 val s = sorted.indexOfFirst { it.toString() == "[[6]]" } + 1 return f * s } fun solve1(input: List<Element>): Int { val results = input.chunked(2).mapIndexed { idx, (l, r) -> idx + 1 to (compare(l, r) < 0) } return results.filter { it.second }.sumOf { it.first } } sealed class Element() class Leaf(val v: Int) : Element() { override fun toString(): String { return "$v" } } class Composite(val children: List<Element>) : Element() { constructor(e: Element) : this(listOf(e)) override fun toString(): String { return children.joinToString(",", "[", "]") } } fun List<Char>.toInt() = this.joinToString("").toInt() fun parse(i: Iterator<Char>): Element { val elem = mutableListOf<Element>() val number = mutableListOf<Char>() while (i.hasNext()) { val c = i.next() when (c) { ']' -> { if (number.isNotEmpty()) { val t = number.joinToString(separator = "") elem.add(Leaf(t.toInt())) number.clear() } return Composite(elem) } '[' -> elem.add(parse(i)) else -> if (c.isDigit()) { number += c } else { if (number.isNotEmpty()) { elem.add(Leaf(number.toInt())) number.clear() } } } } return elem[0] } fun parse(input: List<String>): List<Element> { return input .filter { it.isNotBlank() } .map { parse(it.iterator()) } }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
2,787
aoc-2022
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2018/Day7.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2018 object Day7 { val dependency = """Step (\w) must be finished before step (\w) can begin\.""".toRegex() data class Requirement(val prereq: Char, val downstream: Char) fun part1(requirements: List<String>): String { val reqAsMap = parseReq(requirements) return findPath(reqAsMap) } fun part2(workers: Int = 5, requirements: List<String>): Int { val allPairs = allPairs(requirements) val dependedOn = generateDependencies(allPairs.map { it.second to it.first }) val dependedBy = generateDependencies(allPairs) val allKeys = dependedBy.keys.union(dependedOn.keys) val ready = allKeys.filterNot { it in dependedOn }.map { it to it.toTime() }.toMutableList() val done = mutableListOf<Char>() var time = 0 while (ready.isNotEmpty()) { ready.take(workers).forEachIndexed { idx, work -> ready[idx] = Pair(work.first, work.second - 1) } ready.filter { it.second == 0 }.forEach { workItem -> done.add(workItem.first) dependedBy[workItem.first]?.let { maybeReadyS -> ready.addAll( maybeReadyS.filter { maybeReady -> dependedOn.getValue(maybeReady).all { it in done || it == workItem.first } }.map { it to it.toTime() }.sortedBy { it.first } ) } } ready.removeIf { it.second == 0 } time++ } return time } fun findNext(requirements: Map<Char, Set<Char>>, soFar: String): List<Char> { return requirements.filterNot { soFar.contains(it.key) }.filter { it.value.all { v -> soFar.contains(v) } }.map { it.key } } fun Char.toTime(): Int { return this.code - 4 } tailrec fun findPath(requirements: Map<Char, Set<Char>>, soFar: String = ""): String { val next = nextStep(requirements, soFar) return if (next == null) soFar else findPath(requirements, soFar + next) } private fun nextStep(requirements: Map<Char, Set<Char>>, soFar: String): Char? { return findNext(requirements, soFar).minOrNull() } private fun allPairs(requirements: List<String>): List<Pair<Char, Char>> = requirements.map { row -> row.split(" ").run { this[1].first() to this[7].first() } } private fun generateDependencies(input: List<Pair<Char, Char>>): Map<Char, Set<Char>> { return input.groupBy { it.first }.mapValues { (_, value) -> value.map { it.second }.toSet() } } private fun parseReq(requirements: List<String>): Map<Char, Set<Char>> { val dependencies = requirements.asSequence().mapNotNull(dependency::matchEntire) .map { it.groupValues } .map { Requirement(it[1][0], it[2][0]) } .groupBy { it.downstream } .mapValues { it.value.fold(setOf<Char>()) { acc, dep -> acc + dep.prereq } } val steps = dependencies.values.flatten().union(dependencies.keys) return steps.map { Pair(it, dependencies[it] ?: emptySet()) }.toMap() } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
3,344
adventofcode
MIT License
src/day16/Day16.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day16 import readInput import readTestInput private data class Valve( val flowRate: Long, val tunnelsTo: Set<String>, ) private typealias Valves = Map<String, Valve> private fun List<String>.toValves(): Valves { val regex = """Valve (\w+) has flow rate=(\d+);.*valves? (\w+(, \w+)*)""".toRegex() return associate { line -> val (name, rate, tunnels) = checkNotNull(regex.matchEntire(line)).destructured name to Valve(flowRate = rate.toLong(), tunnelsTo = tunnels.split(", ").toSet()) } } private fun Valves.findShortestRoutes(): Map<String, Map<String, Int>> { val valves = this var shortestRoutes: Map<String, Map<String, Int>> = mapValues { (_, valve) -> valve.tunnelsTo.associateWith { 1 } } repeat(valves.size) { shortestRoutes = shortestRoutes.mapValues { (_, routesFromValve) -> val allRoutes = routesFromValve .flatMap { existingRoute -> val (middleTarget, cost) = existingRoute shortestRoutes.getValue(middleTarget).map { (subTarget, subCost) -> subTarget to cost + subCost } } + routesFromValve.map { it.key to it.value } allRoutes .groupBy { it.first } .mapValues { (_, costs) -> costs.minOf { it.second } } .toMap() } if (shortestRoutes.all { routes -> routes.value.size == valves.size }) { return shortestRoutes } } return shortestRoutes } private data class PossibleMove( val position: String, val valvesOpened: Set<String>, val releasedPressureAtEnd: Long, val timeLeft: Int, ) private fun findPossibleTargets( shortestRoutes: Map<String, Map<String, Int>>, valves: Valves, position: String, timeLeft: Int, valvesOpened: Set<String> ) = shortestRoutes.getValue(position) .filterNot { (valveName, moveCost) -> val possibleTargetValve = valves.getValue(valveName) val cannotOpen = timeLeft < (moveCost + 2) valveName in valvesOpened || possibleTargetValve.flowRate == 0L || cannotOpen } private fun PossibleMove.availableMoves( valves: Valves, shortestRoutes: Map<String, Map<String, Int>> ): List<PossibleMove> { val move = this val possibleTargets = findPossibleTargets( shortestRoutes = shortestRoutes, valves = valves, position = move.position, timeLeft = move.timeLeft, valvesOpened = move.valvesOpened ) if (move.timeLeft <= 0 || possibleTargets.isEmpty()) { return listOf(move) } return possibleTargets.flatMap { (targetValveName, moveCost) -> val targetValve = valves.getValue(targetValveName) val openCost = moveCost + 1 val releasedPressureFromValveAtEnd = (move.timeLeft - openCost) * targetValve.flowRate PossibleMove( position = targetValveName, valvesOpened = move.valvesOpened + targetValveName, releasedPressureAtEnd = move.releasedPressureAtEnd + releasedPressureFromValveAtEnd, timeLeft = move.timeLeft - openCost ).availableMoves(valves, shortestRoutes) } + move } private fun part1(input: List<String>): Long { val valves = input.toValves() val shortestRoutes = valves.findShortestRoutes() .filterKeys { valveName -> valveName == "AA" || valves.getValue(valveName).flowRate > 0 } val initialMove = PossibleMove( position = "AA", valvesOpened = emptySet(), releasedPressureAtEnd = 0L, timeLeft = 30, ) val possibleMoves: List<PossibleMove> = listOf(initialMove) .flatMap { move -> move.availableMoves(valves, shortestRoutes) } return possibleMoves.maxOf { move -> move.releasedPressureAtEnd } } private fun part2(input: List<String>): Long { val valves = input.toValves() val shortestRoutes = valves.findShortestRoutes() .filterKeys { valveName -> valveName == "AA" || valves.getValue(valveName).flowRate > 0 } val initialMove = PossibleMove( position = "AA", valvesOpened = emptySet(), releasedPressureAtEnd = 0L, timeLeft = 26, ) val possibleMoves: List<PossibleMove> = listOf(initialMove) .flatMap { move -> move.availableMoves(valves, shortestRoutes) } var maximumPressureRelease = 0L for (i in possibleMoves.indices) { val myMove = possibleMoves[i] val myOpenedValves = myMove.valvesOpened val myPressureRelease = myMove.releasedPressureAtEnd for (j in i..possibleMoves.lastIndex) { val elephantMove = possibleMoves[j] val elephantOpenedValves = elephantMove.valvesOpened val elephantPressureRelease = elephantMove.releasedPressureAtEnd val combinedPressureRelease = myPressureRelease + elephantPressureRelease if (maximumPressureRelease < combinedPressureRelease && myOpenedValves.none { myValve -> myValve in elephantOpenedValves }) { maximumPressureRelease = combinedPressureRelease } } } return maximumPressureRelease } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day16") check(part1(testInput) == 1651L) check(part2(testInput) == 1707L) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
5,533
advent-of-code-kotlin-2022
Apache License 2.0
src/day8/Day08.kt
francoisadam
573,453,961
false
{"Kotlin": 20236}
package day8 import readInput fun main() { fun part1(input: List<String>): Int { val matrix = input.toMatrix() var visibleTreesCount = 0 val visibleTrees = mutableListOf<String>() matrix.forEachIndexed { i, line -> line.forEachIndexed { j, tree -> val column = matrix.getColumnAtIndex(j) val visible = line.subList(0, j).all { it < tree } || line.subList(j + 1, line.size).all { it < tree } || column.subList(0, i).all { it < tree } || column.subList(i + 1, column.size).all { it < tree } if (visible) { visibleTreesCount++ visibleTrees.add("tree ligne $i & colonne $j") } } } return visibleTreesCount } fun part2(input: List<String>): Int { val matrix = input.toMatrix() val treesMap = mutableListOf<TreeView>() matrix.forEachIndexed { i, line -> line.forEachIndexed { j, tree -> val column = matrix.getColumnAtIndex(j) treesMap.add( TreeView( upTrees = column.subList(0, i).reversed().countVisibleTrees(tree), downTrees = column.subList(i + 1, column.size).countVisibleTrees(tree), leftTrees = line.subList(0, j).reversed().countVisibleTrees(tree), rightTrees = line.subList(j + 1, line.size).countVisibleTrees(tree), ) ) } } return treesMap.maxOfOrNull { it.scenicScore() } ?: 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("day8/Day08_test") val testPart1 = part1(testInput) println("testPart1: $testPart1") val testPart2 = part2(testInput) println("testPart2: $testPart2") check(testPart1 == 21) check(testPart2 == 8) val input = readInput("day8/Day08") println("part1 : ${part1(input)}") println("part2 : ${part2(input)}") } private fun List<String>.toMatrix(): List<List<Int>> = this.map { line -> line.toCharArray().map { it.digitToInt() } } private fun List<List<Int>>.getColumnAtIndex(index: Int): List<Int> = this.map { line -> line[index] } private data class TreeView( val upTrees: Int, val downTrees: Int, val leftTrees: Int, val rightTrees: Int, ) { fun scenicScore(): Int = upTrees * downTrees * leftTrees * rightTrees } private fun Iterable<Int>.countVisibleTrees(maxHeight: Int): Int = this.withIndex().takeWhile { it.index == 0 || this.toList()[it.index - 1] < maxHeight }.count()
0
Kotlin
0
0
e400c2410db4a8343c056252e8c8a93ce19564e7
2,748
AdventOfCode2022
Apache License 2.0
src/year2022/day15/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day15 import io.kotest.matchers.shouldBe import kotlin.math.max import utils.Point import utils.manhattanDistanceTo import utils.plusOrMinus import utils.readInput import utils.size fun main() { val testEmptySpots = readInput("15", "test_input").toSensors().computeEmptySpots() val emptySpots = readInput("15", "input").toSensors().computeEmptySpots() testEmptySpots.getValue(10) .sumOf { it.size } .also(::println) shouldBe 26 emptySpots.getValue(2000000) .sumOf { it.size } .let(::println) testEmptySpots.asSequence() .first { it.key in 0..20 && it.value.size > 1 } .let { (y, confirmedX) -> Point(confirmedX.first().last + 1, y) } .let { it.x * 4000000 + it.y } .also(::println) shouldBe 56000011 emptySpots.asSequence() .first { it.key in 0..4000000 && it.value.size > 1 } .let { (y, confirmedX) -> Point(confirmedX.first().last + 1, y) } .let { it.x * 4000000L + it.y } .let(::println) } private fun List<String>.toSensors(): List<Sensor> { return asSequence() .mapNotNull(parsingRegex::matchEntire) .map { it.groupValues } .mapTo(mutableListOf()) { (_, sensorX, sensorY, beaconX, beaconY) -> Sensor( Point(sensorX.toInt(), sensorY.toInt()), Point(beaconX.toInt(), beaconY.toInt()), ) } } private val parsingRegex = "Sensor at x=(\\d+), y=(\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() private data class Sensor( val position: Point, val closestBeacon: Point, ) { val distance = position manhattanDistanceTo closestBeacon val emptySpotsConfirmed: Map<Int, IntRange> = (0..2 * distance).associate { row -> Pair( position.y - distance + row, if (row <= distance) position.x plusOrMinus row else position.x.plusOrMinus(2 * distance - row) ) } } private fun List<Sensor>.computeEmptySpots(): Map<Int, List<IntRange>> { return asSequence() .map { it.emptySpotsConfirmed } .flatMap { it.entries } .groupBy { it.key } .mapValues { (_, ranges) -> ranges.asSequence() .map { it.value } .simplifyRanges() } } private fun Sequence<IntRange>.simplifyRanges(): List<IntRange> = sortedBy { it.first }.fold(mutableListOf()) { rangeAccumulator, range -> val lastRange = rangeAccumulator.lastOrNull() when { lastRange == null || lastRange.last < range.first - 1 -> rangeAccumulator.add(range) else -> rangeAccumulator[rangeAccumulator.lastIndex] = IntRange( lastRange.first, max(range.last, lastRange.last) ) } rangeAccumulator }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,798
Advent-of-Code
Apache License 2.0
src/year2023/Day13.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import Grid import readLines fun main() { val input = parseInput(readLines("2023", "day13")) val testInput = parseInput(readLines("2023", "day13_test")) check(part1(testInput) == 405) println("Part 1:" + part1(input)) check(part2(testInput) == 400) println("Part 2:" + part2(input)) } private fun parseInput(input: List<String>): List<Grid<Char>> { var input = input val patterns = mutableListOf<Grid<Char>>() while (input.isNotEmpty()) { val patternLength = input.takeWhile { it != "" }.size patterns.add(Grid(input.take(patternLength).map { it.toCharArray().toList() })) input = input.drop(patternLength + 1) } return patterns } private fun part1(patterns: List<Grid<Char>>): Int { val x = patterns.map { pattern -> (isHorizontallyMirrored(pattern).firstOrNull()?.let { it * 100 }) ?: isVerticallyMirrored(pattern).first() } return x.sum() } private fun part2(patterns: List<Grid<Char>>): Int { return patterns.map { pattern -> val initialHorizontalMirrors = isHorizontallyMirrored(pattern).toSet() val initialVerticalMirrors = isVerticallyMirrored(pattern).toSet() pattern.allFlips().mapNotNull { flippedPattern -> val horizontalMirrors = isHorizontallyMirrored(flippedPattern).minus(initialHorizontalMirrors) val verticalMirrors = isVerticallyMirrored(flippedPattern).minus(initialVerticalMirrors) if (horizontalMirrors.isNotEmpty() || verticalMirrors.isNotEmpty()) { horizontalMirrors.firstOrNull()?.let { it * 100 } ?: verticalMirrors.first() } else { null } }.first() }.sum() return 0 } private fun isHorizontallyMirrored(pattern: Grid<Char>): List<Int> { return (1..<pattern.rows).filter { mirror -> (1..mirror).all { row -> val mirroredRow = 2 * mirror - row + 1 mirroredRow > pattern.rows || pattern.nthRow(row - 1) == pattern.nthRow(mirroredRow - 1) } } } private fun isVerticallyMirrored(pattern: Grid<Char>): List<Int> { return (1..<pattern.cols).filter { mirror -> (1..mirror).all { col -> val mirroredCol = 2 * mirror - col + 1 mirroredCol > pattern.cols || pattern.nthCol(col - 1) == pattern.nthCol(mirroredCol - 1) } } } private fun Grid<Char>.allFlips(): List<Grid<Char>> { return (1..rows).map { row -> (1..cols).map { col -> this.flip(row, col) } }.flatten() } private fun Grid<Char>.flip( col: Int, row: Int, ): Grid<Char> { val newData = data.mapIndexed { y, chars -> if (y == row - 1) { chars.mapIndexed { x, char -> if (x == col - 1) { if (char == '.') '#' else '.' } else { char } } } else { chars } } return Grid(newData) }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
3,098
advent_of_code
MIT License
src/day24/d24_1.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val list = input.lines().map { it.toInt() } val groupSize = list.sum() / 3 val firstGroup = solve(list, groupSize) // order by quantum entanglement and find smallest one for which // the rest of packages can be divided in two groups of the same weight val candidates = firstGroup.map { it.map(Int::toLong).reduce(Long::times) to it }.sortedBy { it.first } for (candidate in candidates) { if (solve(list - candidate.second, groupSize).isNotEmpty()) { println(candidate.first) break } } } fun solve(packages: List<Int>, target: Int): List<List<Int>> { // dp[i][j] == set of the smallest subsets of the first i elements that sum to j val dp = Array(packages.size + 1) { Array(target + 1) { if (it == 0) 0 to listOf(emptyList<Int>()) else packages.size to emptyList<List<Int>>() } } packages.forEachIndexed { i0, n -> val i = i0 + 1 for (j in 1 .. target) { dp[i][j] = dp[i - 1][j] if (j >= n) { val prevRow = dp[i - 1][j - n] if (prevRow.first + 1 < dp[i][j].first) { dp[i][j] = prevRow.first + 1 to prevRow.second.map { it -> it + n } } else if (prevRow.first + 1 == dp[i][j].first) { dp[i][j] = dp[i][j].first to dp[i][j].second + prevRow.second.map { it -> it + n } } } } } return dp[packages.size][target].second }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,416
aoc2015
MIT License
src/Day12.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
fun main() { fun parseInput(input: List<String>): List<List<Tile>> = input .map { line -> line.map { it } } .let { map -> map.mapIndexed { rowIndex, row -> row.mapIndexed { index, char -> Tile( x = index, y = rowIndex, char = char, isStart = char == 'S', isEnd = char == 'E', ) } } } fun grow( initialTile: Tile, grid: List<List<Tile>>, ): Pair<Int, Boolean> { var currentPaths = listOf(initialTile) var iteration = 0 val seenTiles = mutableSetOf<Tile>() while (!currentPaths.any { it.isEnd } && currentPaths.isNotEmpty()) { currentPaths = currentPaths .flatMap { visited -> seenTiles.add(visited) val tileToLeft = if (visited.x != 0) grid[visited.y][visited.x - 1] else null val tileToTop = if (visited.y != 0) grid[visited.y - 1][visited.x] else null val tileToRight = if (visited.x != grid[0].lastIndex) grid[visited.y][visited.x + 1] else null val tileToBottom = if (visited.y != grid.lastIndex) grid[visited.y + 1][visited.x] else null return@flatMap listOfNotNull(tileToLeft, tileToTop, tileToRight, tileToBottom) .filter { (it.height - visited.height) <= 1 } // legit to go there } .distinct() .filter { it !in seenTiles } iteration++ } return iteration to currentPaths.any { it.isEnd } } fun part1(input: List<String>): Int { val grid = parseInput(input) return grow(grid.flatten().first { it.isStart }, grid).first } fun part2(input: List<String>): Int { val grid = parseInput(input) return grid.flatten().filter { it.char == 'a' } .map { grow(it, grid) } .filter { it.second } .minOf { it.first } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") val input = readInput("Day12") check(part1(testInput) == 31) println(part1(input)) check(part2(testInput) == 29) println(part2(input)) } private data class Tile( val x: Int, val y: Int, val char: Char, val isStart: Boolean, val isEnd: Boolean, ) { val height = when (char) { 'S' -> 'a' 'E' -> 'z' else -> char }.code }
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
2,665
advent-of-code-2022
Apache License 2.0
src/day15/Day15.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day15 import readInput import kotlin.math.abs private const val DAY_ID = "15" private data class Point( val x: Int, val y: Int ) { companion object { fun fromString(s: String): Point { // example: x=-2, y=15 val (x, y) = s.split(", ").map { it.substringAfter("=").toInt() } return Point(x, y) } } } private data class Data( val sensor: Point, val beacon: Point ) private data class Interval( var start: Int, var end: Int ) { fun overlapsWith(that: Interval): Boolean = that.end >= start && that.start <= end operator fun contains(x: Int): Boolean = x in start..end } fun main() { fun parseInput(input: List<String>): List<Data> = input.map { line -> val (sensor, closestBeacon) = line.split(": ").asSequence() .map { it.substringAfter("at ") } .map { Point.fromString(it) } .toList() Data(sensor, closestBeacon) } fun part1(input: List<String>, y: Int): Int { val data = parseInput(input) val beacons = mutableSetOf<Point>() val intervals = mutableListOf<Interval>() for ((sensor, beacon) in data) { if (beacon.y == y) { beacons += beacon } val dx = abs(sensor.x - beacon.x) val dy = abs(sensor.y - beacon.y) val dist = dx + dy // (S, B) pair defines a square with S being in the middle, where other beacons can't possibly exist // for each such (S, B) pair, find an intersection with row Y: // |x - S[i].x| + |Y - S[i].y| = dist // |x - S[i].x| = dist - |Y - S[i].y| // let D = dist - |Y - S[i].y|, then // x - S[i].x = ±D // <=> // x = S[i].x - D <- start of the interval // x = S[i].x + D <- end of the interval val d = dist - abs(y - sensor.y) if (d <= 0) { continue } intervals += Interval(sensor.x - d, sensor.x + d) } // merge potentially overlapping intervals intervals.sortBy { it.start } val union = mutableListOf<Interval>() for (interval in intervals) { if (union.isEmpty() || !union.last().overlapsWith(interval)) { union += interval } else { val last = union.last() last.end = maxOf(last.end, interval.end) } } return union.fold(0) { acc, interval -> var total = interval.end - interval.start + 1 for (beacon in beacons) { if (beacon.x in interval) { total-- } } acc + total } } fun part2(input: List<String>): Int { TODO() } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput, 10).also { println(it) } == 26) //check(part2(testInput) == 42) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input, 2000000)) //println(part2(input)) }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
3,251
aoc-2022-in-kotlin
Apache License 2.0
src/Day12.kt
jordan-thirus
573,476,470
false
{"Kotlin": 41711}
import java.util.PriorityQueue fun main() { val startChar = 'S' val endChar = 'E' fun getHeight(height: Char) = when(height){ endChar -> 'z' startChar -> 'a' else -> height } fun shortestPathToEnd(priorityQueue: PriorityQueue<Step>, input: List<String>): Int { val visited = mutableSetOf<Point>() while (priorityQueue.any()) { val step = priorityQueue.remove() //if we've been here, don't process again if (!visited.contains(step.point)) { //if it's the end, return if (step.height == endChar) { return step.distanceTraveled } //mark as visited visited.add(step.point) val nextDistance = step.distanceTraveled + 1 for (n in step.neighbors().filter { it.isInBounds(input.indices, input[0].indices) }) { val nextHeight = input[n.y][n.x] if (getHeight(step.height) - getHeight(nextHeight) >= -1) { priorityQueue.add(Step(n, nextHeight, nextDistance)) } } } } return Int.MAX_VALUE } fun part1(input: List<String>): Int { val priorityQueue = PriorityQueue<Step>() input.forEachIndexed { index, chars -> if (chars.contains(startChar)){ priorityQueue.add(Step.build(index, chars.indexOf(startChar), startChar, 0)) } } return shortestPathToEnd(priorityQueue, input) } fun part2(input: List<String>): Int { val priorityQueue = PriorityQueue<Step>() input.forEachIndexed { index, chars -> chars.forEachIndexed { i, c -> if(getHeight(c) == 'a'){ priorityQueue.add(Step.build(index, i, c, 0)) } } } return shortestPathToEnd(priorityQueue, input) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) } data class Step(val point: Point, val height: Char, val distanceTraveled: Int): Comparable<Step> { fun neighbors(): Set<Point> = point.neighbors() companion object { fun build(y: Int, x: Int, height: Char, distanceTraveled: Int): Step = Step(Point(y, x), height, distanceTraveled) } override fun compareTo(other: Step): Int { return distanceTraveled - other.distanceTraveled } }
0
Kotlin
0
0
59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e
2,709
advent-of-code-2022
Apache License 2.0
src/Day08.kt
ShuffleZZZ
572,630,279
false
{"Kotlin": 29686}
private fun getGrid(input: List<String>) = input.map { it.map(Char::digitToInt).toTypedArray() }.toTypedArray() private fun observeLines(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntRange, rowInds: IntProgression) { val maxRowInd = if (rowInds.isRange()) 0 else grid.first().size - 1 for (i in lineInds) { var max = grid[i + 1][maxRowInd] for (j in rowInds) { if (grid[i + 1][j + 1] > max) { res[i][j] = true max = grid[i + 1][j + 1] } } } if (rowInds.isRange()) observeLines(grid, res, lineInds, rowInds.reversed()) } private fun observeRows(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntProgression, rowInds: IntRange) { val maxLineInd = if (lineInds.isRange()) 0 else grid.size - 1 for (j in rowInds) { var max = grid[maxLineInd][j + 1] for (i in lineInds) { if (grid[i + 1][j + 1] > max) { res[i][j] = true max = grid[i + 1][j + 1] } } } if (lineInds.isRange()) observeRows(grid, res, lineInds.reversed(), rowInds) } private fun scenicScore(grid: Array<Array<Int>>, spot: Pair<Int, Int>) = neighbours().map { observeTree(grid, spot, it) }.reduce(Int::times) private fun observeTree(grid: Array<Array<Int>>, spot: Pair<Int, Int>, shift: Pair<Int, Int>): Int { var dist = 0 var indexes = spot + shift while (indexes.first in grid.indices && indexes.second in grid.first().indices) { dist++ if (grid[indexes.first][indexes.second] >= grid[spot.first][spot.second]) break indexes += shift } return dist } fun main() { fun part1(input: List<String>): Int { val grid = getGrid(input) val n = grid.size val m = grid.first().size val res = Array(n - 2) { BooleanArray(m - 2) { false } } observeLines(grid, res, res.indices, res.first().indices) observeRows(grid, res, res.indices, res.first().indices) return res.sumOf { it.count { e -> e } } + 2 * (n + m - 2) } fun part2(input: List<String>): Int { val grid = getGrid(input) val res = Array(grid.size - 2) { IntArray(grid.first().size - 2) { 0 } } for (i in res.indices) { for (j in res.indices) { res[i][j] = scenicScore(grid, i + 1 to j + 1) } } return res.maxOf { it.max() } } // 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
0
0
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
2,750
advent-of-code-kotlin
Apache License 2.0
src/Day15.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
import lib.Coordinates import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min fun IntRange.clamp(minimum: Int, maximum: Int) = max(minimum, first)..min(maximum, last) fun Set<IntRange>.consolidate(): Set<IntRange> { var result = this var lastCount: Int do { lastCount = result.size result = result.fold(setOf()) { acc, incoming -> if (acc.isEmpty()) { setOf(incoming) } else { buildSet { var hasConsolidated = false for (range in acc) { val isIncomingInThis = incoming.first - 1 in range || incoming.last + 1 in range val isThisInIncoming = range.first - 1 in incoming || range.last + 1 in incoming if (isIncomingInThis || isThisInIncoming) { add(IntRange(min(range.first, incoming.first), max(range.last, incoming.last))) hasConsolidated = true } else { add(range) } } if (!hasConsolidated) add(incoming) } } } } while (result.size != lastCount && result.size > 1) return result } data class Sensor(val coordinates: Coordinates, val closestBeacon: Coordinates) { private val distance = coordinates.manhattanDistanceTo(closestBeacon) fun positionsWithNoBeacon(y: Int): IntRange? { val yDistanceFromSensor = (coordinates.y - y).absoluteValue if (yDistanceFromSensor > distance) return null val xDistance = (distance - yDistanceFromSensor).absoluteValue val left = coordinates.x - xDistance val right = coordinates.x + xDistance return if (right - left > 0) left..right else null } } private fun parse(input: List<String>): Set<Sensor> { val pattern = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)") return buildSet { input.forEach { line -> pattern.find(line)?.run { add(Sensor(Coordinates(groupValues[1].toInt(), groupValues[2].toInt()), Coordinates(groupValues[3].toInt(), groupValues[4].toInt()))) } } } } fun main() { fun part1(input: List<String>, row: Int): Int { val sensors = parse(input) val reports = sensors.mapNotNull { it.positionsWithNoBeacon(row) } val merged = reports.toSet().consolidate() val noBeaconPositionCount = merged.sumOf { it.count() } val sensorsAndBeaconsOnRow = sensors .flatMap { listOf(it.coordinates, it.closestBeacon) } .distinct() .filter { it.y == row } .filter { occupiedCoordinate -> merged.any { occupiedCoordinate.x in it } } return noBeaconPositionCount - sensorsAndBeaconsOnRow.count() } fun part2(input: List<String>, range: IntRange): Long { val sensors = parse(input) val coordinates = range .map { y -> sensors .mapNotNull { it.positionsWithNoBeacon(y) } .map { it.clamp(range.first, range.last) } .toSet() .consolidate() } .mapIndexedNotNull { index, ranges -> if (ranges.count() == 2) { Coordinates(ranges.toList().first().last + 1, index) } else null } .single() return (coordinates.x * 4000000L) + coordinates.y } val testInput = readInput("Day15_test") println(part1(testInput, 10)) println(part2(testInput, 0..20)) val input = readInput("Day15") println(part1(input, 2_000_000)) println(part2(input, 0..4_000_000)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
3,857
advent-of-code-in-kotlin-2022
Apache License 2.0
src/day15/Day15.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day15 import java.io.File import kotlin.math.abs fun main() { val regexp = Regex("Sensor at x=(-?\\d*), y=(-?\\d*): closest beacon is at x=(-?\\d*), y=(-?\\d*)") val sensors = File("src/day15/input.txt").readLines() .map { regexp.matchEntire(it)!!.groupValues } .map { values -> Sensor(Pair(values[1].toInt(), values[2].toInt()), Pair(values[3].toInt(), values[4].toInt())) }.toSet() val row = 2000000 // 10 println(sensors.map { it.excludes(row) }.reduce().sumOf { it.last - it.first }) val max = 4000000 // 20 // Part 2 using the fact everything must be excluded by a single range in every other row for (row in 0 .. max) { val exclusions = sensors.map { sensor -> sensor.excludes(row) }.reduce() if (exclusions.size > 1) { val column = (0..max).firstOrNull { exclusions.none { exclusion -> exclusion.contains(it) } } ?: continue println(column * 4000000L + row) break } } // Part 2 using the fact that the beacon must be just outside a sensor's exclusion range for (row in 0 .. max) { val exclusions = sensors.map { sensor -> sensor.excludes(row) } val options = exclusions.map { range -> listOf(range.first - 1, range.last + 1) }.flatten().filter { it in 0..max } val column = options.firstOrNull { option -> exclusions.none { exclusion -> exclusion.contains(option) } } if (column != null) { println(column * 4000000L + row) break } } } fun List<IntRange>.reduce(): List<IntRange> { if (size < 2) return this for (i in 0 until size - 1) { for (j in i + 1 until size) { if (this[i].overlap(this[j]) || this[i].adjacent(this[j])) { val result = this.subList(0, i).toMutableList() result.addAll(this.subList(i + 1, j)) result.addAll(this.subList(j + 1, size)) result.addAll(this[i].merge(this[j])) return result.reduce() } } } return this } fun IntRange.overlap(other: IntRange): Boolean { return first <= other.last && last >= other.first } fun IntRange.adjacent(other: IntRange): Boolean { return first == other.last + 1 || last == other.first - 1 } fun IntRange.merge(other: IntRange): List<IntRange> { return if (overlap(other) || adjacent(other)) listOf(IntRange(kotlin.math.min(first, other.first), kotlin.math.max(last, other.last))) else listOf(this, other) } data class Sensor(val sensor: Pair<Int, Int>, val beacon: Pair<Int, Int>) { private val distance = abs(sensor.first - beacon.first) + abs(sensor.second - beacon.second) fun excludes(row: Int): IntRange { val distanceFromRow = abs(sensor.second - row) val difference = distance - distanceFromRow if (difference < 0) return IntRange.EMPTY return (sensor.first - difference .. sensor.first + difference) } }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
2,989
advent-of-code-2022
MIT License
src/year2020/day05/Day05.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day05 import util.assertTrue import util.read2020DayInput import kotlin.math.roundToInt fun main() { val input = read2020DayInput("Day05") assertTrue(task01(input) == 801) assertTrue(task02(input) == 597) } private fun task02(input: List<String>): Int { val sortedSeats = input.map { calculateRow(it, Range(0, 127), 0) * 8 + calculateColumn(it, Range(0, 7), 7) }.sorted() sortedSeats.forEachIndexed { i, s -> if (sortedSeats[i + 1] - s != 1) return s + 1 } return 0 } private fun task01(input: List<String>): Int { return input.maxOf { calculateRow(it, Range(0, 127), 0) * 8 + calculateColumn(it, Range(0, 7), 7) } } private fun calculateRow(characters: String, range: Range, count: Int): Int { return if (count == 7) { val half = ((range.max.toDouble() - range.min.toDouble()) / 2) + range.min if (characters[count] == 'B') half.roundToInt() else half.toInt() } else { val half = ((range.max.toDouble() - range.min.toDouble()) / 2) + range.min if (characters[count] == 'B') calculateRow(characters, Range(half.roundToInt(), range.max), count + 1) else calculateRow(characters, Range(range.min, half.toInt()), count + 1) } } private fun calculateColumn(characters: String, range: Range, count: Int): Int { return if (count == 9) { val half = ((range.max.toDouble() - range.min.toDouble()) / 2) + range.min if (characters[count] == 'R') half.roundToInt() else half.toInt() } else { val half = ((range.max.toDouble() - range.min.toDouble()) / 2) + range.min if (characters[count] == 'R') calculateColumn(characters, Range(half.roundToInt(), range.max), count + 1) else calculateColumn(characters, Range(range.min, half.toInt()), count + 1) } } private data class Range(val min: Int, val max: Int)
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
1,871
advent-of-code-kotlin-template
Apache License 2.0
src/Day08.kt
flex3r
572,653,526
false
{"Kotlin": 63192}
import kotlin.math.max fun main() { val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { val trees = parseTrees(input) val runningMaxSides = listOf( trees.runningMaxStart(), trees.runningMaxEnd(), trees.runningMaxTop(), trees.runningMaxBottom(), ) return trees.withIndex().sumOf { (i, row) -> row.withIndex().count { (j, tree) -> runningMaxSides.any { it[i][j] < tree } } } } private fun part2(input: List<String>): Int { val trees = parseTrees(input) val scenicValues = listOf( trees.scenicValuesStart(), trees.scenicValuesEnd(), trees.scenicValuesTop(), trees.scenicValuesBottom(), ) return trees.withIndex().flatMap { (i, row) -> row.withIndex().map { (j, _) -> scenicValues .map { it[i][j] } .reduce { acc, it -> acc * it } } }.max() } private fun parseTrees(input: List<String>): List<List<Int>> = input.map { row -> row.map { it.digitToInt() } } private fun List<List<Int>>.runningMaxStart(): List<List<Int>> = map { row -> row.dropLast(1) .runningFold(-1) { acc, tree -> max(acc, tree) } } private fun List<List<Int>>.runningMaxEnd(): List<List<Int>> = map { row -> row.drop(1) .reversed() .runningFold(-1) { acc, tree -> max(acc, tree) } .reversed() } private fun List<List<Int>>.runningMaxTop(): List<List<Int>> = transpose().runningMaxStart().transpose() private fun List<List<Int>>.runningMaxBottom(): List<List<Int>> = transpose().runningMaxEnd().transpose() private fun List<List<Int>>.scenicValuesStart(): List<List<Int>> = map { it.scenicDistances() } private fun List<List<Int>>.scenicValuesEnd(): List<List<Int>> = map { it.reversed().scenicDistances().reversed() } private fun List<List<Int>>.scenicValuesTop(): List<List<Int>> = transpose().scenicValuesStart().transpose() private fun List<List<Int>>.scenicValuesBottom(): List<List<Int>> = transpose().scenicValuesEnd().transpose() private fun List<Int>.scenicDistances(): List<Int> { return mapIndexed { idx, tree -> slice(idx + 1..lastIndex) .indexOfFirst { it >= tree } .takeIf { it != -1 } ?.inc() ?: (lastIndex - idx) } }
0
Kotlin
0
0
8604ce3c0c3b56e2e49df641d5bf1e498f445ff9
2,474
aoc-22
Apache License 2.0
src/Day13.kt
jinie
572,223,871
false
{"Kotlin": 76283}
class Day13 { private fun ordered(l: MutableList<Char>, r: MutableList<Char>): Boolean { fun MutableList<Char>.addBrackets(len: Int) = apply { add(len, ']'); add(0, '[') } fun List<Char>.num(): Int? = if (!this.first().isDigit()) null else this.takeWhile { it.isDigit() }.joinToString("").toInt() if (l.first() == '[' && r.num() != null) r.addBrackets(r.num().toString().length) if (r.first() == '[' && l.num() != null) l.addBrackets(l.num().toString().length) return when { l[0] == ']' && r[0] != ']' -> true l[0] != ']' && r[0] == ']' -> false l.num() == (r.num() ?: -1) -> ordered( l.subList(l.num().toString().length, l.size), r.subList(r.num().toString().length, r.size) ) l.num() != null && r.num() != null -> l.num()!! < r.num()!! else -> ordered(l.subList(1, l.size), r.subList(1, r.size)) } } val comparePackets: (String, String) -> Int = { s1: String, s2: String -> if (ordered(s1.toMutableList(), s2.toMutableList())) -1 else 1 } fun part1(input: List<String>): Int { return (input.windowed(2, 3) .mapIndexed { i, packets -> if (comparePackets(packets.first(), packets.last()) != 1) i + 1 else 0 }.sum()) } fun part2(input: List<String>): Int { val sorted = (input.windowed(2, 3).flatten() + "[[2]]" + "[[6]]").sortedWith(comparePackets) return ((1 + sorted.indexOf("[[2]]")) * (1 + sorted.indexOf("[[6]]"))) } } fun main() { val testInput = readInput("Day13_test") check(Day13().part1(testInput) == 13) check(Day13().part2(testInput) == 140) measureTimeMillisPrint { val input = readInput("Day13") println(Day13().part1(input)) println(Day13().part2(input)) } }
0
Kotlin
0
0
4b994515004705505ac63152835249b4bc7b601a
1,862
aoc-22-kotlin
Apache License 2.0
src/main/kotlin/advent/of/code/day06/Solution.kt
brunorene
160,263,437
false
null
package advent.of.code.day06 import java.io.File import kotlin.math.abs data class Point(val x: Int, val y: Int) { fun distance(b: Point) = abs(x - b.x) + abs(y - b.y) } val input: List<Point> = File("day06.txt").readLines().map { val parts = it.split(",") Point(parts[0].trim().toInt(), parts[1].trim().toInt()) } fun part1(): Int { val topLeftBig = Point( input.map { it.x }.min()!! - 10, input.map { it.y }.min()!! - 10 ) val topLeft = Point( input.map { it.x }.min()!!, input.map { it.y }.min()!! ) val bottomRightBig = Point( input.map { it.x }.max()!! + 10, input.map { it.y }.max()!! + 10 ) val bottomRight = Point( input.map { it.x }.max()!!, input.map { it.y }.max()!! ) val areas = mutableMapOf<Point, Int>() for (x in (topLeft.x..bottomRight.x)) for (y in (topLeft.y..bottomRight.y)) { val current = Point(x, y) val distances = input.sortedBy { current.distance(it) }.map { Pair(it, it.distance(current)) } if (distances[0].second != distances[1].second) areas.compute(distances[0].first) { _, a -> (a ?: 0) + 1 } } val areasBig = mutableMapOf<Point, Int>() for (x in (topLeftBig.x..bottomRightBig.x)) for (y in (topLeftBig.y..bottomRightBig.y)) { val current = Point(x, y) val distances = input.sortedBy { current.distance(it) }.map { Pair(it, it.distance(current)) } if (distances[0].second != distances[1].second) areasBig.compute(distances[0].first) { _, a -> (a ?: 0) + 1 } } return areas.filter { areasBig[it.key] == it.value }.values.max()!! } fun part2(): Int { val topLeft = Point( input.map { it.x }.min()!!, input.map { it.y }.min()!! ) val bottomRight = Point( input.map { it.x }.max()!!, input.map { it.y }.max()!! ) var area = 0 for (x in (topLeft.x..bottomRight.x)) for (y in (topLeft.y..bottomRight.y)) { val current = Point(x, y) val allDists = input.map { it.distance(current) }.sum() if (allDists <= 10000) area++ } return area }
0
Kotlin
0
0
0cb6814b91038a1ab99c276a33bf248157a88939
2,267
advent_of_code_2018
The Unlicense
src/Day08.kt
aneroid
572,802,061
false
{"Kotlin": 27313}
class Day08(private val input: List<String>) { private val forest = parseInput(input) private fun isVisible(x: Int, y: Int, height: Int): Boolean = requiredIndices(x, y) .any { pairs -> pairs.all { (cx, cy) -> forest[cy][cx] < height } } private fun scenicScore(x: Int, y: Int, height: Int): Int = requiredIndices(x, y) .map { pairs -> val treesInPath = pairs.map { (cx, cy) -> forest[cy][cx] } val shorter = treesInPath.takeWhile { it < height } shorter.size + if (shorter.size < treesInPath.size) 1 else 0 }.reduce { acc, i -> acc * i } private fun requiredIndices(x: Int, y: Int): Sequence<List<Pair<Int, Int>>> { return sequenceOf( (0 until x).reversed().map { it to y }, (x + 1 until forest[0].size).map { it to y }, (0 until y).reversed().map { x to it }, (y + 1 until forest.size).map { x to it }, ) } private fun treesVisibleAtEdge(): Int = forest.size * 2 + forest[0].size * 2 - 4 private fun isAtEdge(x: Int, y: Int) = x == 0 || y == 0 || x == forest[0].indices.last || y == forest.indices.last fun partOne(): Int = treesVisibleAtEdge() + forest.flatMapIndexed { y: Int, rows: List<Int> -> rows.mapIndexed { x: Int, height: Int -> !isAtEdge(x, y) && isVisible(x, y, height) } }.count { it } fun partTwo(): Int = forest.flatMapIndexed { y: Int, rows: List<Int> -> rows.mapIndexed { x: Int, height: Int -> if (isAtEdge(x, y)) 0 else scenicScore(x, y, height) } }.max() private companion object { fun parseInput(input: List<String>) = input .map { line -> line.map { char -> char.toString().toInt() } } } } fun main() { val testInput = readInput("Day08_test") val input = readInput("Day08") println("part One:") assertThat(Day08(testInput).partOne()).isEqualTo(21) println("actual: ${Day08(input).partOne()}\n") println("part Two:") // uncomment when ready assertThat(Day08(testInput).partTwo()).isEqualTo(8) println("actual: ${Day08(input).partTwo()}\n") }
0
Kotlin
0
0
cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd
2,341
advent-of-code-2022-kotlin
Apache License 2.0
src/Day12.kt
Excape
572,551,865
false
{"Kotlin": 36421}
import util.UnweightedGraph fun main() { val directions = listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1)) fun inBounds(input: List<String>, p: Point) = p.x >= 0 && p.y >= 0 && p.y <= input.lastIndex && p.x <= input[p.y].lastIndex fun getElevation(input: List<String>, point: Point): Char { return when (val elevation = input[point.y][point.x]) { 'S' -> 'a' 'E' -> 'z' else -> elevation } } fun parseGraph(input: List<String>): UnweightedGraph<Point> { val vertices = input.indices.flatMap { y -> input[y].indices.map { x -> Point(x, y) } } val edges = vertices.associateWith { v -> val elevation = getElevation(input, v) directions .map { Point(v.x + it.first, v.y + it.second) } .filter { inBounds(input, it) } .filter { getElevation(input, it) <= elevation.inc() }.toSet() } return UnweightedGraph(vertices, edges) } fun getStartPoint(graph: UnweightedGraph<Point>, input: List<String>) = graph.vertices.find { p -> input[p.y][p.x] == 'S' } ?: throw IllegalStateException("start point not found") fun getEndPoint(graph: UnweightedGraph<Point>, input: List<String>) = graph.vertices.find { p -> input[p.y][p.x] == 'E' } ?: throw IllegalStateException("end point not found") fun part1(input: List<String>): Int { val graph = parseGraph(input) val startPoint = getStartPoint(graph, input) val endPoint = getEndPoint(graph, input) return graph.findShortestPathLength(startPoint, endPoint) ?: throw IllegalStateException("no shortest path found") } fun part2(input: List<String>): Int { val graph = parseGraph(input) val endPoint = getEndPoint(graph, input) val startPoints = graph.vertices.filter { getElevation(input, it) == 'a' } return startPoints.mapNotNull { startPoint -> graph.findShortestPathLength(startPoint, endPoint) }.min() } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") val part1Answer = part1(input) val part2Answer = part2(input) println("part 1: $part1Answer") println("part 2: $part2Answer") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
2,376
advent-of-code-2022
Apache License 2.0
src/Day13.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import utils.Tree import java.util.Stack import kotlin.math.min import kotlin.math.sign fun buildTree(input: String): Tree<Int> { val stack = Stack<Tree<Int>>() val root = Tree<Int>() var currentValue = 0 var hasValue = false var currentNode = root for (c in input) { when (c) { '[' -> { stack.push(currentNode) currentNode = Tree() // first children } ']' -> { currentNode.value = if (hasValue) currentValue else null stack.peek().children += currentNode currentNode = stack.pop() // go back to parent currentValue = 0 hasValue = false } ',' -> { currentNode.value = if (hasValue) currentValue else null stack.peek().children += currentNode currentNode = Tree() // next children currentValue = 0 hasValue = false } in '0'..'9' -> { currentValue = currentValue * 10 + c.digitToInt() hasValue = true } } } return root } fun compare(a: Tree<Int>, b: Tree<Int>): Int { if (a.isLeaf() && a.hasValue() && b.isLeaf() && b.hasValue()) return (a.value!! - b.value!!).sign val childrenA = if (a.isLeaf() && a.hasValue()) mutableListOf(Tree(a.value)) else a.children val childrenB = if (b.isLeaf() && b.hasValue()) mutableListOf(Tree(b.value)) else b.children for(i in 0 until min(childrenA.size, childrenB.size)) { when (compare(childrenA[i], childrenB[i])) { -1 -> return -1 1 -> return 1 0 -> {} //do nothing } } return (childrenA.size - childrenB.size).sign } fun main() { fun part1(input: List<String>): Int { var result = 0 var counter = 1 for (i in input.indices step 3) { val leftTree = buildTree(input[i]) val rightTree = buildTree(input[i + 1]) val sign = compare(leftTree, rightTree) if (sign <= 0) { result += counter } counter++ } return result } fun part2(input: List<String>): Int { val decoders = arrayOf( Tree<Int>(), Tree() ) decoders[0].children += Tree(2) decoders[1].children += Tree(6) val trees = mutableListOf(*decoders) for (line in input) { if (line.isEmpty()) continue trees += buildTree(line) } trees.sortWith { a, b -> compare(a, b) } return decoders.map { trees.indexOf(it) + 1 }.reduce { acc, i -> acc * i } } val test = readInput("Day13_test") println(part1(test)) println(part2(test)) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
2,941
Advent-Of-Code-2022
Apache License 2.0
src/aoc2018/kot/Day18.kt
Tandrial
47,354,790
false
null
package aoc2018.kot import java.io.File object Day18 { fun partOne(input: List<String>): Int { var grid = parse(input) repeat(10) { grid = nextGeneration(grid) } return grid.sumBy { it.count { it == '|' } } * grid.sumBy { it.count { it == '#' } } } fun partTwo(input: List<String>): Int { var current = parse(input) val old = mutableListOf(current) repeat(1000000000) { current = nextGeneration(current) val find = old.withIndex().filter { (_, arr) -> arr contentDeepEquals current } if (find.isNotEmpty()) { val idxCycle = (1000000000 - it) % (old.size - find.first().index) current = old[idxCycle + find.first().index - 1] return current.sumBy { it.count { it == '|' } } * current.sumBy { it.count { it == '#' } } } old.add(current) } return current.sumBy { it.count { it == '|' } } * current.sumBy { it.count { it == '#' } } } private fun parse(input: List<String>) = input.map { it.toCharArray() }.toTypedArray() private fun nextGeneration(current: Array<CharArray>): Array<CharArray> { val next = Array(current.size) { CharArray(current[0].size) } current.forEachIndexed { y, line -> line.forEachIndexed { x, c -> val surroudings = countNeighbours(x, y, current) next[y][x] = when (c) { '.' -> if (surroudings['|']!! >= 3) '|' else c '|' -> if (surroudings['#']!! >= 3) '#' else c '#' -> if (surroudings['#']!! >= 1 && surroudings['|']!! >= 1) '#' else '.' else -> c } } } return next } private fun countNeighbours(x: Int, y: Int, grid: Array<CharArray>): MutableMap<Char, Int> { val counts = mutableMapOf('.' to 0, '|' to 0, '#' to 0) for (currX in (x - 1..x + 1)) { for (currY in (y - 1..y + 1)) { if (currX != x || currY != y) { if (currX in (0 until grid[0].size) && currY in (0 until grid.size)) counts.replace(grid[currY][currX], counts[grid[currY][currX]]!! + 1) } } } return counts } } fun main(args: Array<String>) { val input = File("./input/2018/Day18_input.txt").readLines() println("Part One = ${Day18.partOne(input)}") println("Part Two = ${Day18.partTwo(input)}") }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
2,272
Advent_of_Code
MIT License
src/Day08.kt
paulbonugli
574,065,510
false
{"Kotlin": 13681}
class Forest(private val trees : List<List<Int>>) { private val maxX : Int = trees.first().size-1 private val maxY : Int = trees.size-1 private fun getSurroundings(x : Int, y : Int) : Array<List<Int>> { val left = trees[y].slice(0 until x).reversed() val right = trees[y].slice((x + 1)..maxX) val up = trees.map { it[x] }.slice(0 until y).reversed() val below = trees.map { it[x] }.slice((y+1) .. maxY) return arrayOf(left,right,up,below) } private fun isPositionVisible(x : Int, y : Int) : Boolean { val tree = trees[y][x] return getSurroundings(x,y).any{ direction -> direction.all { it < tree }} } private fun getScenicScore(x : Int, y : Int) : Int { val tree = trees[y][x] return getSurroundings(x, y) .map { direction -> direction.takeWhileInclusive { it < tree }.count() } .reduce { multiple, item -> multiple * item } } fun getMostScenicScore() : Int { return allPositions().map { (x,y) -> getScenicScore(x, y) }.max() } private fun allPositions() : List<Pair<Int,Int>> { return (0..maxY).flatMap { y -> (0..maxX).map { x -> x to y } } } fun countVisible() : Int { return allPositions().map { (x,y) -> isPositionVisible(x, y)}.count { (it) } } fun printVisible() { print((0..maxY).joinToString("") { y -> (0..maxX).map { x -> isPositionVisible(x, y) }.joinToString("") { if (it) "🎄" else "🟦" } + "\n" }) } } fun main() { val input = readInput("Day08").map { it.toList().map(Char::digitToInt) } val forest = Forest(input) println() forest.printVisible() println("${forest.countVisible()} trees visible \uD83C\uDF84") println("Most scenic score: ${forest.getMostScenicScore()}") } fun <T> Iterable<T>.takeWhileInclusive(predicate: (T) -> Boolean): List<T> { val list = ArrayList<T>() for (item in this) { list.add(item) // moved below list.add vs. takeWhile implementation if (!predicate(item)) break } return list }
0
Kotlin
0
0
d2d7952c75001632da6fd95b8463a1d8e5c34880
2,162
aoc-2022-kotlin
Apache License 2.0
advent-of-code-2022/src/Day15.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import kotlin.math.abs fun main() { val testInput = readInput("Day15_test") val input = readInput("Day15") "Part 1" { part1(testInput, targetY = 10) shouldBe 26 answer(part1(input, targetY = 2_000_000)) } "Part 2" { part2(testInput, max = 20) shouldBe 56000011 answer(part2(input, max = 4_000_000)) } } private fun part1(input: List<List<Int>>, targetY: Int): Int { val notABeacon = mutableListOf<IntRange>() val beacons = mutableSetOf<Int>() for ((sensorX, sensorY, beaconX, beaconY) in input) { val beaconDistance = abs(beaconX - sensorX) + abs((beaconY - sensorY)) val targetDistance = abs(sensorY - targetY) if (beaconY == targetY) beacons += beaconX if (targetDistance < beaconDistance) { val diff = beaconDistance - targetDistance notABeacon += (sensorX - diff)..(sensorX + diff) } } return notABeacon.flatten().distinct().filterNot { it in beacons }.count() } private const val TUNING_X = 4_000_000L private fun part2(input: List<List<Int>>, max: Int): Long { fun checkSolution(x: Int, y: Int): Boolean { if (x !in 0..max || y !in 0..max) return false return input.all { (sensorX, sensorY, beaconX, beaconY) -> val beaconDistance = abs(beaconX - sensorX) + abs(beaconY - sensorY) val pointDistance = abs(x - sensorX) + abs(y - sensorY) pointDistance > beaconDistance } } var counter = 0 for ((sensorX, sensorY, beaconX, beaconY) in input) { println(counter++) val targetDistance = abs(beaconX - sensorX) + abs(beaconY - sensorY) + 1 for (yDiff in 0..targetDistance) { val xDiff = targetDistance - yDiff if (checkSolution(sensorX + xDiff, sensorY + yDiff)) return (sensorX + xDiff) * TUNING_X + (sensorY + yDiff) if (checkSolution(sensorX - xDiff, sensorY + yDiff)) return (sensorX - xDiff) * TUNING_X + (sensorY + yDiff) if (checkSolution(sensorX + xDiff, sensorY - yDiff)) return (sensorX + xDiff) * TUNING_X + (sensorY - yDiff) if (checkSolution(sensorX - xDiff, sensorY - yDiff)) return (sensorX - xDiff) * TUNING_X + (sensorY - yDiff) } } error("There no answer?") } private fun readInput(name: String) = readLines(name).map { line -> line.replace(Regex("[^\\d-]+"), " ").trim().splitInts(" ") }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,440
advent-of-code
Apache License 2.0
src/year2023/day05/Day.kt
tiagoabrito
573,609,974
false
{"Kotlin": 73752}
package year2023.day05 import java.util.stream.LongStream import year2023.solveIt fun main() { val day = "05" val expectedTest1 = 35L val expectedTest2 = 46L fun part1(input: List<String>): Long { val map = input.joinToString("\n").split("\n\n").map { it.split("\n") } val seeds = Regex("\\d+").findAll(map[0][0]).map { it.value.toLong() } val map1 = map.stream().skip(1).map { it.stream().skip(1).map { line -> val (dest, src, sz) = line.split(" ").map { it.toLong() } LongRange(src,src + sz-1) to dest-src }.toList() }.toList() val map2 = seeds.map { seed -> map1.fold(seed) { curr, m -> curr + (m.firstOrNull { it.first.contains(curr) }?.second?:0) } }.toList() return map2.min() } fun part2(input: List<String>): Long { val items = input.joinToString("\n").split("\n\n").map { it.split("\n") } val seeds = Regex("\\d+").findAll(items[0][0]).map { it.value.toLong() }.chunked(2).sortedBy { it[0] }.map { LongStream.range(it[0], it[0] + it[1] - 1) } val ranges = items.drop(1).map { it.drop(1).map { line -> val (dest, src, sz) = line.split(" ").map { it.toLong() } LongRange(src, src + sz - 1) to dest - src }.sortedBy { it.first.first }.toList() }.toList() val map2 = Regex("\\d+").findAll(items[0][0]).map { it.value.toLong() }.chunked(2).sortedBy { it[0] } .mapNotNull { LongStream.range(it[0], it[0] + it[1] - 1).parallel().map { seed -> ranges.fold(seed) { curr, range -> curr + (range.firstOrNull { it.first.contains(curr) }?.second ?: 0) } }.min() }.map{it.asLong }.min() return map2 } solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2) }
0
Kotlin
0
0
1f9becde3cbf5dcb345659a23cf9ff52718bbaf9
1,902
adventOfCode
Apache License 2.0
src/day02/Day02.kt
martinhrvn
724,678,473
false
{"Kotlin": 27307, "Jupyter Notebook": 1336}
package day02 import kotlin.math.max import println import readInput data class Colors(val red: Int, val green: Int, val blue: Int) { fun product(): Int { return red * green * blue } } data class Game(val id: Int, val rounds: List<Colors>) val limit = Colors(12, 13, 14) class CubeConundrum(val input: List<String>) { fun part1(): Int { return input .map(::readGame) .filter { game -> game.rounds.all { round -> limit.red >= round.red && limit.blue >= round.blue && limit.green >= round.green } } .sumOf { it.id } } fun part2(): Int { return input.sumOf { row -> val game = readGame(row) game.rounds .fold(Colors(0, 0, 0)) { acc, round -> Colors(max(acc.red, round.red), max(acc.green, round.green), max(acc.blue, round.blue)) } .product() } } private fun readGame(row: String): Game { val (gameLabel, rounds) = row.split(": ", limit = 2) val gameId = gameLabel.replace("Game ", "").toInt() val gameRounds = rounds.split(";").map { round -> val rs = round .trim() .split(", ") .map { cube -> val (num, color) = cube.split(" ") color to num.toInt() } .groupBy { it.first } .mapValues { (_, nums) -> nums.sumOf { it.second } } Colors(rs.getOrDefault("red", 0), rs.getOrDefault("green", 0), rs.getOrDefault("blue", 0)) } return Game(gameId, gameRounds) } } fun main() { val testInput = readInput("day02/Day02_test") check(CubeConundrum(testInput).part1() == 8) check(CubeConundrum(testInput).part2() == 2286) val cube = CubeConundrum(readInput("day02/Day02")) cube.part1().println() cube.part2().println() }
0
Kotlin
0
0
59119fba430700e7e2f8379a7f8ecd3d6a975ab8
1,890
advent-of-code-2023-kotlin
Apache License 2.0
src/Day16.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import java.util.PriorityQueue interface Graph<T> { fun neighbors(node: T): List<Pair<Int, T>> } interface FiniteGraph<V> : Graph<V> { val nodes: Set<V> } fun <T> dijkstra( graph: Graph<T>, start: Collection<T>, goal: (T) -> Boolean, ): Pair<Int, List<T>>? { val visited = mutableSetOf<T>() val frontier = PriorityQueue<Pair<Int, List<T>>>(start.size) { a, b -> compareValuesBy(a, b) { it.first } } frontier.addAll(start.map { 0 to listOf(it) }) while(frontier.isNotEmpty()) { val (cost, path) = frontier.remove() val next = path.last() if (goal(next)) { return cost to path } if (!visited.add(next)) { continue } graph.neighbors(next).forEach { (edgeCost, neighbor) -> val newCost = cost + edgeCost val newPath = path + neighbor frontier.add(newCost to newPath) } } return null } class MapGraph<T>(private val map: Map<T, List<Pair<Int, T>>>) : FiniteGraph<T> { override val nodes = map.keys override fun neighbors(node: T): List<Pair<Int, T>> = map[node] ?: emptyList() } fun <T> floydWarshall(graph: FiniteGraph<T>): FiniteGraph<T>? { val nodes = graph.nodes.toList() val nodeIndices = nodes.withIndex().associate { it.value to it.index } val distances = Array(nodes.size) { from -> IntArray(nodes.size) { to -> if (from == to) { 0 } else { Int.MAX_VALUE } } } nodes.forEachIndexed { index, node -> graph.neighbors(node).forEach { (cost, neighbor) -> val neighborIndex = nodeIndices.getValue(neighbor) distances[index][neighborIndex] = minOf(distances[index][neighborIndex], cost) } } for (k in nodes.indices) { for (i in nodes.indices) { for (j in nodes.indices) { if (distances[i][k] == Int.MAX_VALUE || distances[k][j] == Int.MAX_VALUE) { continue } val cost = distances[i][k] + distances[k][j] if (i == j && cost < 0) { // Negative cycle detected return null } distances[i][j] = minOf(distances[i][j], cost) } } } val nodeMap = distances.withIndex().associate { val node = nodes[it.index] val edges = it.value .mapIndexed { index, cost -> cost to nodes[index] } .filter { edge -> edge.first < Int.MAX_VALUE } node to edges } return MapGraph(nodeMap) } data class Valve(val name: String, val flow: Int) { val isUseful = flow > 0 } data class CaveNode(val location: Valve, val minute: Int, val openValves: Set<Valve>) { val flow = openValves.sumOf(Valve::flow) } class CaveGraph(val tunnels: FiniteGraph<Valve>) : Graph<CaveNode> { private val maxFlow = tunnels.nodes.sumOf(Valve::flow) override fun neighbors(node: CaveNode): List<Pair<Int, CaveNode>> { if (node.minute >= TIME_LIMIT) { return emptyList() } val adjustedFlow = maxFlow - node.flow val remainingTime = TIME_LIMIT - node.minute return buildList { tunnels.neighbors(node.location) .forEach { (travelTime, valve) -> val totalTime = travelTime + 1 if (valve.isUseful && valve !in node.openValves && totalTime < remainingTime) { val neighbor = CaveNode(valve, node.minute + totalTime, node.openValves + valve) add(totalTime * adjustedFlow to neighbor) } } }.takeUnless { it.isEmpty() } ?: listOf(remainingTime * adjustedFlow to node.copy(minute = TIME_LIMIT)) } fun convertCost(cost: Int) = TIME_LIMIT * maxFlow - cost companion object { const val TIME_LIMIT = 30 } } data class Destination(val valve: Valve, val travelTime: Int) data class ElephantNode( val human: Destination, val elephant: Destination, val minute: Int, val openValves: Set<Valve> ) class ElephantGraph(val tunnels: FiniteGraph<Valve>) : Graph<ElephantNode> { private val maxFlow = tunnels.nodes.sumOf(Valve::flow) override fun neighbors(node: ElephantNode): List<Pair<Int, ElephantNode>> { if (node.minute >= TIME_LIMIT) { return emptyList() } val remainingTime = TIME_LIMIT - node.minute return if (node.human.travelTime == 0) { val openValves = node.openValves + node.human.valve val adjustedFlow = maxFlow - openValves.sumOf(Valve::flow) buildList { tunnels.neighbors(node.human.valve) .forEach { (travelTime, valve) -> val totalTime = travelTime + 1 if (valve.isUseful && valve !in openValves && totalTime < remainingTime) { add(Destination(valve, totalTime)) } } if (size < 2) { add(Destination(node.human.valve, remainingTime)) } }.map { destination -> adjustedFlow * node.elephant.travelTime to ElephantNode( human = Destination(destination.valve, destination.travelTime - node.elephant.travelTime), elephant = Destination(node.elephant.valve, 0), minute = node.minute + node.elephant.travelTime, openValves = openValves, ) } } else { val openValves = node.openValves + node.elephant.valve val adjustedFlow = maxFlow - openValves.sumOf(Valve::flow) buildList { tunnels.neighbors(node.elephant.valve) .forEach { (travelTime, valve) -> val totalTime = travelTime + 1 if (valve.isUseful && valve !in openValves && totalTime < remainingTime) { add(Destination(valve, totalTime)) } } if (size < 2) { add(Destination(node.elephant.valve, remainingTime)) } }.map { destination -> adjustedFlow * node.human.travelTime to ElephantNode( human = Destination(node.human.valve, 0), elephant = Destination(destination.valve, destination.travelTime - node.human.travelTime), minute = node.minute + node.human.travelTime, openValves = openValves, ) } } } fun convertCost(cost: Int) = TIME_LIMIT * maxFlow - cost companion object { const val TIME_LIMIT = 26 } } fun main() { val regex = Regex("""Valve ([A-Z]{2}) has flow rate=(\d+); tunnels? leads? to valves? ([A-Z]{2}(?:, [A-Z]{2})*)""") val input = readInput("Day16") .associate { line -> val (name, flow, tunnels) = regex.matchEntire(line)!!.destructured val valve = Valve(name, flow.toInt()) name to (valve to tunnels.split(", ")) } var tunnels: FiniteGraph<Valve> = MapGraph(input.values.associate { (valve, names) -> valve to names.mapNotNull { name -> input[name]?.let { 1 to it.first } } }) tunnels = floydWarshall(tunnels)!! val cave = CaveGraph(tunnels) val start = listOf(CaveNode(input["AA"]!!.first, 0, setOf())) dijkstra(cave, start) { it.minute == CaveGraph.TIME_LIMIT }?.let { (cost, _) -> println(cave.convertCost(cost)) } val elephantCave = ElephantGraph(tunnels) val elephantStart = listOf(ElephantNode( human = Destination(input["AA"]!!.first, 0), elephant = Destination(input["AA"]!!.first, 0), minute = 0, openValves = emptySet(), )) dijkstra(elephantCave, elephantStart) { it.minute == ElephantGraph.TIME_LIMIT }?.let { (cost, _) -> println(elephantCave.convertCost(cost)) } }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
8,317
advent-of-code-2022
Apache License 2.0
src/day16/Day16.kt
ayukatawago
572,742,437
false
{"Kotlin": 58880}
package day16 import readInput import kotlin.math.max fun main() { val testInput = readInput("day16/test") val regex = """Valve ([A-Z]+) has flow rate=(\d+); tunnels* leads* to valves* ([A-Z\s,]+)""".toRegex() val valveDataMap = HashMap<String, Valve>() testInput.forEach { val result = regex.matchEntire(it) ?: return@forEach val name = result.groupValues[1] val flowRate = result.groupValues[2].toInt() val valves = result.groupValues[3].split(", ").toSet() valveDataMap.put(name, Valve(flowRate, valves)) } println(part1(valveDataMap)) println(part2(valveDataMap)) } private fun part1(valveMap: Map<String, Valve>): Int { val totalTime = 30 val dp = Array(totalTime + 1) { hashMapOf<Status, Int>() } updateDp(dp, 0, Status("AA", emptySet()), 0) (0 until totalTime).forEach { time -> dp[time].forEach { (status, pressure) -> val valve = valveMap[status.valveName]!! if (valve.flowRate > 0 && status.valveName !in status.openedValves) { val newStatus = Status(status.valveName, status.openedValves + status.valveName) updateDp(dp, time + 1, newStatus, pressure + (totalTime - time - 1) * valve.flowRate) } valve.leadsTo.forEach { val newStatus = Status(it, status.openedValves) updateDp(dp, time + 1, newStatus, pressure) } } } return dp[totalTime].values.max() } private fun part2(valveMap: Map<String, Valve>): Int { val totalTime = 26 val dp = Array(totalTime + 1) { hashMapOf<Status, Int>() } updateDp(dp, 0, Status("AA", emptySet()), 0) (0 until totalTime).forEach { time -> dp[time].forEach { (status, pressure) -> val valve = valveMap[status.valveName]!! if (valve.flowRate > 0 && status.valveName !in status.openedValves) { val newStatus = Status(status.valveName, status.openedValves + status.valveName) updateDp(dp, time + 1, newStatus, pressure + (totalTime - time - 1) * valve.flowRate) } valve.leadsTo.forEach { val newStatus = Status(it, status.openedValves) updateDp(dp, time + 1, newStatus, pressure) } } } val bm = dp[totalTime].toList().groupingBy { it.first.openedValves }.fold(0) { a, e -> maxOf(a, e.second) } val effectiveValveSet = valveMap.filter { it.value.flowRate > 0 }.map { it.key }.toSet() var maxPressure = 0 effectiveValveSet.toRepeatedCombination().forEach { elf -> val elfPressure = bm[elf] ?: return@forEach val remaining = effectiveValveSet.toSet() - elf remaining.toRepeatedCombination().forEach { val pressure = bm[it] ?: return@forEach maxPressure = max(maxPressure, elfPressure + pressure) } } return maxPressure } private fun Set<String>.toRepeatedCombination(): List<Set<String>> { return if (size == 1) { listOf(emptySet(), setOf(first())) } else { val remainingList = drop(1).toSet().toRepeatedCombination() remainingList + remainingList.map { it + first() } } } private fun updateDp(dp: Array<HashMap<Status, Int>>, time: Int, status: Status, pressure: Int) { val currentPressure = dp[time][status] if (currentPressure == null || pressure > currentPressure) { dp[time][status] = pressure } } private data class Valve(val flowRate: Int, val leadsTo: Set<String>) private data class Status(val valveName: String, val openedValves: Set<String>)
0
Kotlin
0
0
923f08f3de3cdd7baae3cb19b5e9cf3e46745b51
3,627
advent-of-code-2022
Apache License 2.0
src/Day12.kt
mikemac42
573,071,179
false
{"Kotlin": 45264}
import java.io.File fun main() { val testInput = """Sabqponm abcryxxl accszExk acctuvwj abdefghi""" val realInput = File("src/Day12.txt").readText() val part1TestOutput = fewestSteps(testInput) { it == 'S' } println("Part 1 Test Output: $part1TestOutput") check(part1TestOutput == 31) val part1RealOutput = fewestSteps(realInput) { it == 'S' } println("Part 1 Real Output: $part1RealOutput") val part2TestOutput = fewestSteps(testInput) { it == 'S' || it == 'a' } println("Part 2 Test Output: $part2TestOutput") check(part2TestOutput == 29) val part2RealOutput = fewestSteps(realInput) { it == 'S' || it == 'a' } println("Part 2 Real Output: $part2RealOutput") } /** * The heightmap shows the local area from above broken into a grid. * a is the lowest elevation * z is the highest elevation * S is the starting position at elevation a * E is the ending position at elevation z * During each step, you can move exactly one square up, down, left, or right. * The elevation of the destination can be at most one higher than the current elevation. */ fun fewestSteps(input: String, isStartPos: (Char) -> Boolean): Int { val hill = parseHill(input, isStartPos) // Breadth First Search val visited = hill.elevations.entries.associate { it.key to false }.toMutableMap() val distances: MutableMap<Pos, Int?> = hill.elevations.entries.associate { it.key to null }.toMutableMap() val queue = mutableListOf<Pos>() hill.startPosList.forEach { startPos -> visited[startPos] = true distances[startPos] = 0 queue.add(startPos) } while (queue.isNotEmpty()) { val pos = queue.removeFirst() if (pos == hill.endPos) break val elevation = hill.elevations[pos]!! val distance = distances[pos]!! listOf( Pos(pos.x, pos.y - 1), Pos(pos.x, pos.y + 1), Pos(pos.x - 1, pos.y), Pos(pos.x + 1, pos.y) ).filter { nextPos -> 0 <= nextPos.x && nextPos.x <= hill.maxPos.x && 0 <= nextPos.y && nextPos.y <= hill.maxPos.y && hill.elevations[nextPos]!! <= elevation + 1 && visited[nextPos] == false }.map { nextPos -> visited[nextPos] = true distances[nextPos] = distance + 1 queue.add(nextPos) } } return distances[hill.endPos]!! } private fun parseHill(input: String, isStartPos: (Char) -> Boolean): Hill { val startPosList = mutableListOf<Pos>() var endPos = Pos(-1, -1) val elevations = mutableMapOf<Pos, Int>() input.lines().mapIndexed { i, line -> line.mapIndexed { j, char -> if (isStartPos(char)) startPosList.add(Pos(i, j)) if (char == 'E') endPos = Pos(i, j) elevations[Pos(i, j)] = when (char) { 'S' -> 0 'E' -> 'z'.code - 'a'.code else -> char.code - 'a'.code } } } return Hill(elevations, startPosList, endPos, elevations.keys.last()) } private data class Hill(val elevations: Map<Pos, Int>, val startPosList: List<Pos>, val endPos: Pos, val maxPos: Pos) private data class Pos(val x: Int, val y: Int)
0
Kotlin
1
0
909b245e4a0a440e1e45b4ecdc719c15f77719ab
3,047
advent-of-code-2022
Apache License 2.0
src/Day08.kt
iProdigy
572,297,795
false
{"Kotlin": 33616}
import kotlin.math.max fun main() { fun part1(input: List<String>): Int { val grid = input.map { it.toCharArray() }.map { chars -> chars.map { it.digitToInt() } } val width = grid.first().size val length = grid.size val visible = Array(length) { BooleanArray(width) } fun directionalRunningMax( rowInterval: IntProgression = 0 until length, colInterval: IntProgression = 0 until width, rowOffset: Int = 0, colOffset: Int = 0, startingEdge: (Int, Int) -> Boolean ) = Array(length) { IntArray(width) }.apply { for (row in rowInterval) { for (col in colInterval) { if (startingEdge(row, col)) { visible[row][col] = true this[row][col] = grid[row][col] } else { this[row][col] = max(this[row + rowOffset][col + colOffset], grid[row + rowOffset][col + colOffset]) } } } } val ltrMax = directionalRunningMax(colOffset = -1) { _, col -> col == 0 } val rtlMax = directionalRunningMax(colInterval = width - 1 downTo 0, colOffset = 1) { _, col -> col + 1 == width } val ttbMax = directionalRunningMax(rowOffset = -1) { row, _ -> row == 0 } val bttMax = directionalRunningMax(rowInterval = length - 1 downTo 0, rowOffset = 1) { row, _ -> row + 1 == length } val maxes = listOf(ltrMax, rtlMax, ttbMax, bttMax) for (row in 1 until length - 1) { for (col in 1 until width - 1) { val height = grid[row][col] val minMax = maxes.minOf { it[row][col] } if (height > minMax) visible[row][col] = true } } return visible.sumOf { it.count { b -> b } } } fun part2(input: List<String>): Int { val grid = input.map { it.toCharArray() }.map { chars -> chars.map { it.digitToInt() } } val width = grid.first().size val length = grid.size var scenic = 0 for (row in 1 until length - 1) { for (col in 1 until width - 1) { val height = grid[row][col] fun outwardCount(rowOffset: Int = 0, colOffset: Int = 0, range: IntProgression): Int { var c = 1 if (height > grid[row + rowOffset][col + colOffset]) { c += range.takeWhileAndOneMore { grid[if (rowOffset != 0) it else row][if (rowOffset != 0) col else it] < height }.count() } return c } val top = outwardCount(-1, 0, row - 2 downTo 0) val left = outwardCount(0, -1, col - 2 downTo 0) val right = outwardCount(0, 1, col + 2 until width) val bottom = outwardCount(1, 0, row + 2 until length) scenic = max(scenic, top * left * right * bottom) } } return scenic } // 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)) // 1859 println(part2(input)) // 332640 }
0
Kotlin
0
1
784fc926735fc01f4cf18d2ec105956c50a0d663
3,426
advent-of-code-2022
Apache License 2.0
src/aoc2022/Day15.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* import kotlin.math.abs import kotlin.math.max import kotlin.math.min private class Day15(val lines: List<String>) { val sensors = lines.map { it.removePrefix("Sensor at ").allInts() } .map { Sensor(Coord.xy(it[0], it[1]), Coord.xy(it[2], it[3])) } .toList() data class Sensor(val sensorLoc: Coord, val beaconLoc: Coord) { fun range() : Int { return abs(sensorLoc.x - beaconLoc.x) + abs(sensorLoc.y - beaconLoc.y) } } fun part1(targetY: Int): Long { val coveredRanges = coveredRanges(targetY) val invalidLocations = coveredRanges.flatMap { it }.distinct().debug() val beacons = sensors.map { it.beaconLoc }.filter { it.y == targetY }.distinct() return invalidLocations.size - beacons.size.toLong() } fun part2(dimension: Int): Long { for (y in 0..dimension) { val x = findOpenSpot(y) if (x != -1L) { println("Found it! $x $y") println("Answer: ${x * 4_000_000 + y}") return x * 4_000_000 + y } } throw RuntimeException("Solution not found") } /** Finds the open x value in the target y row or returns -1 to indicate that there is no opening. */ private fun findOpenSpot(y: Int): Long { val coveredRanges = coveredRanges(y).sortedBy { it.first }.toList() coveredRanges.reduce { a, b -> if (a.overlaps(b) || a.last + 1 == b.first) { return@reduce min(a.first, b.first)..max(a.last, b.last) } return a.last + 1.toLong() } return -1 } /** Returns a list of ranges that are covered by sensors for the give row y. */ private fun coveredRanges(targetY: Int): List<IntRange> { val notHereRanges = sensors.filter { s -> abs(targetY - s.sensorLoc.y) <= s.range() }.map { s -> val dx = s.range() - abs(targetY - s.sensorLoc.y) -dx + s.sensorLoc.x..dx + s.sensorLoc.x } return notHereRanges } } fun main() { val day = "15".toInt() val todayTest = Day15(readInput(day, 2022, true)) execute({ todayTest.part1(10) }, "Day[Test] $day: pt 1", 26L) val today = Day15(readInput(day, 2022)) // execute({ today.part1(2000000) }, "Day $day: pt 1") execute({ todayTest.part2(20) }, "Day[Test] $day: pt 2", 56000011L) execute({ today.part2(4_000_000) }, "Day $day: pt 2", 13615843289729) // 796961409 }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
2,332
aoc2022
Apache License 2.0
src/Day04.kt
RichardLiba
572,867,612
false
{"Kotlin": 16347}
fun main() { fun fullyContainsOther(a: Pair<Int, Int>, b: Pair<Int, Int>): Boolean { return a.first <= b.first && a.second >= b.second } fun intersecting(a: Pair<Int, Int>, b: Pair<Int, Int>): Boolean { return a.first <= b.second && b.first <= a.second } fun intersecting(a: Pair<String, String>, b: Pair<String, String>): Boolean { return a.first.toInt() <= b.second.toInt() && b.first.toInt() <= a.second.toInt() } fun String.splitBy(char: Char): Pair<Int, Int> { return Pair(this.substringBefore(char).toInt(), this.substringAfter(char).toInt()) } fun splitLine(string: String): Pair<Pair<Int, Int>, Pair<Int, Int>> { return Pair(string.substringBefore(',').splitBy('-'), string.substringAfter(',').splitBy('-')) } fun List<String>.intoPairs(): List<Pair<String, String>> { return chunked(2).map { it[0] to it[1] } } fun splitLine2(string: String): Pair<Pair<String, String>, Pair<String, String>> { return string.replace(",", "-").split("-").intoPairs().zipWithNext().first() } fun checkLine(string: String): Int { val ranges = splitLine(string) return if (fullyContainsOther(ranges.first, ranges.second) || fullyContainsOther( ranges.second, ranges.first ) ) 1 else 0 } fun checkLine2(string: String): Int { val ranges = splitLine(string) return (if (intersecting(ranges.first, ranges.second) || intersecting( ranges.second, ranges.first ) ) 1 else 0) } fun checkLine2_2(string: String): Int { val ranges = splitLine2(string) return (if (intersecting(ranges.first, ranges.second) || intersecting( ranges.second, ranges.first ) ) 1 else 0) } fun part1(input: List<String>): Int { return input.sumOf { checkLine(it) } } fun part2(input: List<String>): Int { return input.sumOf { checkLine2(it) } } fun part2_2(input: List<String>): Int { return input.sumOf { checkLine2_2(it) } } val input = readInput("Day04") println(part1(input)) println(part2_2(input)) println(part2(input)) }
0
Kotlin
0
0
6a0b6b91b5fb25b8ae9309b8e819320ac70616ed
2,306
aoc-2022-in-kotlin
Apache License 2.0
src/day09/Day09.kt
maxmil
578,287,889
false
{"Kotlin": 32792}
package day09 import println import readInput import kotlin.system.measureTimeMillis data class Position(val x: Int, val y: Int) typealias Grid = List<List<Int>> fun main() { fun List<String>.parseGrid() = map { row -> row.map { it.toString().toInt() } } fun Grid.withinBounds(it: Position) = it.x >= 0 && it.x < this[0].size && it.y >= 0 && it.y < this.size fun Grid.adjacent(position: Position) = listOf( position.copy(x = position.x - 1), position.copy(x = position.x + 1), position.copy(y = position.y - 1), position.copy(y = position.y + 1), ).filter { withinBounds(it) } fun Grid.isLowPoint(position: Position, value: Int): Boolean { return !adjacent(position).any { this[it.y][it.x] <= value } } fun Grid.lowPoints() = flatMapIndexed { rowIndex, row -> List(row.size) { colIndex -> Position(colIndex, rowIndex) } .filter { position -> isLowPoint(position, this[position.y][position.x]) } } fun Grid.basinSize(position: Position, visited: MutableSet<Position>): Int { if (visited.contains(position)) return 0 visited.add(position) return adjacent(position) .filter { this[it.y][it.x] != 9 } .sumOf { this@basinSize.basinSize(it, visited) } + 1 } fun part1(grid: Grid) = grid.lowPoints().sumOf { grid[it.y][it.x] + 1 } fun part2(grid: Grid): Int { val visited = mutableSetOf<Position>() return grid.lowPoints() .map { grid.basinSize(it, visited) } .sorted() .takeLast(3) .reduce { acc, size -> acc * size } } fun part2BFS(grid: Grid): Int { return grid.lowPoints().map { lowPoint -> var cnt = 0 val visited = mutableSetOf<Position>() val toVisit = grid.adjacent(lowPoint).toMutableList() while (toVisit.isNotEmpty()) { val position = toVisit.removeFirst() if (!visited.add(position) || grid[position.y][position.x] == 9) continue cnt++; toVisit.addAll(grid.adjacent(position)) } cnt; }.sorted() .takeLast(3) .reduce { acc, size -> acc * size } } val testGrid = readInput("day09/input_test").parseGrid() check(part1(testGrid) == 15) check(part2(testGrid) == 1134) check(part2BFS(testGrid) == 1134) val grid = readInput("day09/input").parseGrid() part1(grid).println() measureTimeMillis { print(part2(grid)) }.let { println(" in ${it}ms") } measureTimeMillis { print(part2BFS(grid)) }.let { println(" in ${it}ms") } }
0
Kotlin
0
0
246353788b1259ba11321d2b8079c044af2e211a
2,677
advent-of-code-2021
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-15.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2015, "15-input") val test1 = readInputLines(2015, "15-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Long { val ingredients = input.map { Ingredient.parse(it) } val total = 100 val combinations = combinations(ingredients.size, total) return combinations.maxOf { combo -> val zip = combo.zip(ingredients) val cap = zip.sumOf { (count, ingredient) -> count * ingredient.capacity }.coerceAtLeast(0) val dur = zip.sumOf { (count, ingredient) -> count * ingredient.durability }.coerceAtLeast(0) val fla = zip.sumOf { (count, ingredient) -> count * ingredient.flavor }.coerceAtLeast(0) val tex = zip.sumOf { (count, ingredient) -> count * ingredient.texture }.coerceAtLeast(0) cap.toLong() * dur * fla * tex } } private fun part2(input: List<String>): Long { val ingredients = input.map { Ingredient.parse(it) } val total = 100 val targetCalories = 500 val combinations = combinations(ingredients.size, total) return combinations.maxOf { combo -> val zip = combo.zip(ingredients) val cal = zip.sumOf { (count, ingredient) -> count * ingredient.calories } if (cal != targetCalories) return@maxOf 0L val cap = zip.sumOf { (count, ingredient) -> count * ingredient.capacity }.coerceAtLeast(0) val dur = zip.sumOf { (count, ingredient) -> count * ingredient.durability }.coerceAtLeast(0) val fla = zip.sumOf { (count, ingredient) -> count * ingredient.flavor }.coerceAtLeast(0) val tex = zip.sumOf { (count, ingredient) -> count * ingredient.texture }.coerceAtLeast(0) cap.toLong() * dur * fla * tex } } private fun combinations(size: Int, total: Int): List<List<Int>> { if (size == 1) return listOf(listOf(total)) val result = mutableListOf<List<Int>>() for (i in 0..total) { val subResult = combinations(size - 1, total - i) subResult.forEach { combo -> result += combo + i } } return result } private data class Ingredient( val name: String, val capacity: Int, val durability: Int, val flavor: Int, val texture: Int, val calories: Int ) { companion object { fun parse(input: String): Ingredient { val (name, cap, dur, fla, tex, cal) = regex.matchEntire(input)!!.destructured return Ingredient(name, cap.toInt(), dur.toInt(), fla.toInt(), tex.toInt(), cal.toInt()) } } } private val regex = """(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (-?\d+)""".toRegex()
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,970
advent-of-code
MIT License
src/year2022/day11/Day11.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day11 import check import readInput import java.util.LinkedList fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day11_test") check(part1(testInput), 10605) check(part2(testInput), 2713310158L) val input = readInput("2022", "Day11") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = playMonkeyInTheMiddle( monkeysById = parseMonkeysById(input), rounds = 20, divideWorryLevel = 3, ) private fun part2(input: List<String>) = playMonkeyInTheMiddle( monkeysById = parseMonkeysById(input), rounds = 10000, ) private fun playMonkeyInTheMiddle(monkeysById: Map<Int, Monkey>, rounds: Int, divideWorryLevel: Int = 1): Long { val monkeys = monkeysById.values val greatestCommonModFactor = monkeys.map { it.mod }.reduce { acc, n -> acc * n } val monkeyBusiness = Array(monkeys.size) { 0L } repeat(rounds) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { var itemWorryLevel = monkey.items.removeFirst() itemWorryLevel = monkey.inspect(itemWorryLevel) monkeyBusiness[monkey.id]++ if (divideWorryLevel > 1) { itemWorryLevel /= divideWorryLevel } else { itemWorryLevel %= greatestCommonModFactor } val isDivisible = itemWorryLevel % monkey.mod == 0L val nextMonkeyId = if (isDivisible) monkey.monkeyIdTrue else monkey.monkeyIdFalse monkeysById[nextMonkeyId]!!.items.add(itemWorryLevel) } } } return monkeyBusiness.sorted().takeLast(2).let { it[0] * it[1] } } private fun parseMonkeysById(input: List<String>) = (input + "").chunked(7).map { lines -> val id = lines[0][7].digitToInt() val items = lines[1].substringAfter(':').split(',').mapTo(LinkedList()) { it.trim().toLong() } val inspect: Inspect = lines[2].substringAfter("new = old ").let { line -> val (operationString, numString) = line.split(' ') val num = if (numString == "old") null else numString.toLong() val operation: Long.(Long) -> Long = when (operationString) { "*" -> Long::times "+" -> Long::plus else -> error("Operand $operationString not supported") } { it.operation(num ?: it) } } val mod = lines[3].split(' ').last().toInt() val monkeyIdTrue = lines[4].split(' ').last().toInt() val monkeyIdFalse = lines[5].split(' ').last().toInt() Monkey(id, items, inspect, mod, monkeyIdTrue, monkeyIdFalse) }.associateBy { it.id } typealias Inspect = (Long) -> Long class Monkey( val id: Int, val items: LinkedList<Long>, val inspect: Inspect, val mod: Int, val monkeyIdTrue: Int, val monkeyIdFalse: Int, )
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,932
AdventOfCode
Apache License 2.0
y2016/src/main/kotlin/adventofcode/y2016/Day10.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution object Day10 : AdventSolution(2016, 10, "Balance Bots") { override fun solvePartOne(input: String): Int? { val (chips, lowInstr, highInstr) = parse(input) while (chips.values.any { it.size > 1 }) { step(chips, lowInstr, highInstr) chips.entries.find { it.value == listOf(17, 61) } ?.let { return it.key } } return null } override fun solvePartTwo(input: String): Int { val (chips, lowInstr, highInstr) = parse(input) while (chips.values.any { it.size > 1 }) step(chips, lowInstr, highInstr) return (0..2) .map { -it - 1 } .map(chips::getValue) .map(List<Int>::first) .reduce(Int::times) } private fun step(chips: MutableMap<Int, List<Int>>, lowInstr: Map<Int, Int>, highInstr: Map<Int, Int>) { chips .filter { it.value.size > 1 } .forEach { (bot, ch) -> chips[bot] = emptyList() val (lowChip, highChip) = ch chips.merge(lowInstr.getValue(bot), listOf(lowChip)) { a, b -> (a + b).sorted() } chips.merge(highInstr.getValue(bot), listOf(highChip)) { a, b -> (a + b).sorted() } } } private fun parse(input: String): Triple<MutableMap<Int, List<Int>>, Map<Int, Int>, Map<Int, Int>> { val lines = input.lineSequence() val valuePattern = ("value (\\d+) goes to bot (\\d+)").toRegex() val chips = lines .mapNotNull { valuePattern.matchEntire(it) } .groupBy({ it.groupValues[2].toInt() }, { it.groupValues[1].toInt() }) .mapValues { it.value.sorted() } .toMutableMap() val instructionPattern = ("bot (\\d+) gives low to (output|bot) (\\d+) and high to (output|bot) (\\d+)").toRegex() val low = lines .mapNotNull { instructionPattern.matchEntire(it)?.destructured } .associate { (b0, t1, b1) -> b0.toInt() to if (t1 == "bot") b1.toInt() else -b1.toInt() - 1 } val high = lines .mapNotNull { instructionPattern.matchEntire(it)?.destructured } .associate { (b0, _, _, t1, b1) -> b0.toInt() to if (t1 == "bot") b1.toInt() else -b1.toInt() - 1 } return Triple(chips, low, high) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,472
advent-of-code
MIT License
src/Day12.kt
sungi55
574,867,031
false
{"Kotlin": 23985}
import java.util.* fun main() { val day = "Day12" val testGraph: Graph = readInput(name = "${day}_test").asGraph() val graph: Graph = readInput(name = "Day12").asGraph() fun part1(graph: Graph): Int = graph.bfs( start = graph.start, isComplete = { it == graph.destination }, isNotBlocked = { from, to -> to - from <= 1 } ) fun part2(graph: Graph): Int = graph.bfs( start = graph.destination, isComplete = { graph.elevations[it] == 0 }, isNotBlocked = { from, to -> from - to <= 1 } ) check(part1(testGraph) == 31) check(part2(testGraph) == 29) println(part1(graph)) println(part2(graph)) } data class Position( val x: Int = 0, val y: Int = 0 ) { fun neighbors(): Set<Position> = setOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1) ) } data class Path( val position: Position, val weight: Int ) : Comparable<Path> { override fun compareTo(other: Path): Int = weight.compareTo(other.weight) } class Graph( var start: Position, var destination: Position, var elevations: Map<Position, Int>, ) { fun bfs( start: Position, isComplete: (Position) -> Boolean, isNotBlocked: (Int, Int) -> Boolean ): Int { val visitedPosition = mutableSetOf<Position>() val queue = PriorityQueue<Path>().apply { add(Path(start, 0)) } while (queue.isNotEmpty()) { val nextPath = queue.poll() nextPath.position .takeIf { it !in visitedPosition } ?.also { visitedPosition.add(it) } ?.neighbors() ?.filter { it in elevations } ?.filter { isNotBlocked(elevations[nextPath.position]!!, elevations[it]!!) } ?.also { neighbors -> when (neighbors.any { isComplete(it) }) { true -> return nextPath.weight + 1 else -> queue.addAll(neighbors.map { Path(it, nextPath.weight + 1) }) } } } return -1 } } fun List<String>.asGraph(): Graph = let { var start = Position() var destination = Position() val elevations = it.flatMapIndexed { y, row -> row.mapIndexed { x, height -> val currentPosition = Position(x, y) currentPosition to when (height) { 'S' -> 0.also { start = currentPosition } 'E' -> 25.also { destination = currentPosition } else -> height - 'a' } } }.toMap() Graph(start, destination, elevations) }
0
Kotlin
0
0
2a9276b52ed42e0c80e85844c75c1e5e70b383ee
2,661
aoc-2022
Apache License 2.0
src/day04/Task.kt
dniHze
433,447,720
false
{"Kotlin": 35403}
package day04 import readInput fun main() { val input = readInput("day04") println(solvePartTwo(input)) println(solvePartTwo(input)) } fun solvePartOne(input: List<String>): Int { val winners = calculateBingoWinners(input) return winners.first().sum } fun solvePartTwo(input: List<String>): Int { val winners = calculateBingoWinners(input) return winners.last().sum } private fun calculateBingoWinners(input: List<String>): List<BingoWinner> { val bingoInputs = input.bingoInputList() val boards = buildBoards(input) val indexes = buildIndexes(boards) return buildList<BingoWinner> { for (numberString in bingoInputs) { val number = numberString.toInt() val boardIndexes = indexes[number] if (boardIndexes != null) { for (boardIndex in boardIndexes) { if (boardIndex.markAndCheck() && none { (index) -> index == boardIndex.board.index }) { val index = boardIndex.board.index val sum = boardIndex.board.calculateUnmarkedSum() * number add(BingoWinner(index, sum)) } } } } } } private fun buildBoards(input: List<String>) = buildList { val boardsInputOnly = input.drop(1) val tempMatrix = mutableListOf<List<BingoNumber>>() boardsInputOnly.forEachIndexed { index, value -> val inputs = value.replace(' ', ',') .split(',') .filter { member -> member.isNotEmpty() } .map { member -> member.toInt() } if (inputs.isNotEmpty()) { tempMatrix += inputs.map { intValue -> BingoNumber(intValue, false) } } if ((inputs.isEmpty() || index == boardsInputOnly.lastIndex) && tempMatrix.isNotEmpty()) { val card = tempMatrix.toList() tempMatrix.clear() add(card) } } }.mapIndexed { index, numbers -> BingoBoard(index, numbers) } private fun buildIndexes(boards: List<BingoBoard>): Map<Int, List<BingoIndex>> = buildMap { boards.forEach { board -> board.numbers.forEachIndexed { y, row -> row.forEachIndexed { x, (intValue) -> val indexList = getOrPut(intValue) { emptyList() } this[intValue] = indexList + BingoIndex(board, x, y) } } } } private fun List<String>.bingoInputList() = first().splitToSequence(",") private typealias BingoNumbers = List<List<BingoNumber>> private data class BingoBoard( val index: Int, val numbers: BingoNumbers, ) private fun BingoBoard.markAndCheck(x: Int, y: Int): Boolean { get(x, y).marked = true return checkRow(y) || checkColumn(x) } private fun BingoBoard.get(x: Int, y: Int) = numbers[y][x] private fun BingoBoard.checkRow(y: Int): Boolean = numbers[y].all { number -> number.marked } private fun BingoBoard.checkColumn(x: Int): Boolean = numbers.map { it[x] }.all { number -> number.marked } private fun BingoBoard.calculateUnmarkedSum(): Int = numbers.sumOf { row -> row.sumOf { number -> number.value.takeIf { !number.marked } ?: 0 } } private data class BingoIndex( val board: BingoBoard, val x: Int, val y: Int, ) private data class BingoWinner( val index: Int, val sum: Int, ) private fun BingoIndex.markAndCheck(): Boolean = board.markAndCheck(x, y) private data class BingoNumber( val value: Int, var marked: Boolean, )
0
Kotlin
0
1
f81794bd57abf513d129e63787bdf2a7a21fa0d3
3,493
aoc-2021
Apache License 2.0