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/Day09.kt
HylkeB
573,815,567
false
{"Kotlin": 83982}
import kotlin.math.absoluteValue private data class Position(val x: Int, val y: Int) { operator fun plus(other: Position): Position { return Position(x + other.x, y + other.y) } operator fun minus(other: Position): Position { return Position(x - other.x, y - other.y) } infix fun moveTo(target: Position): Position { val delta = this - target return if (delta.x.absoluteValue == 2 || delta.y.absoluteValue == 2) { Position( this.x - delta.x.coerceIn(-1, 1), this.y - delta.y.coerceIn(-1, 1) ) } else { this.copy() } } } private sealed class Direction(val deltaPosition: Position) { class Up : Direction(Position(0, 1)) class Down : Direction(Position(0, -1)) class Left : Direction(Position(-1, 0)) class Right : Direction(Position(1, 0)) } private fun String.toDirection(): Direction { return when (this) { "U" -> Direction.Up() "D" -> Direction.Down() "L" -> Direction.Left() "R" -> Direction.Right() else -> throw IllegalArgumentException("Unknown direction: $this") } } fun main() { fun parseLine(line: String): Pair<Direction, Int> { return line.split(" ").let { it[0].toDirection() to it[1].toInt() } } fun part1(input: List<String>): Int { var currentHeadPosition = Position(0, 0) var currentTailPosition = Position(0, 0) val visitedPositions = mutableListOf(currentTailPosition) input.map { parseLine(it) } .forEach { (direction, amount) -> repeat(amount) { currentHeadPosition += direction.deltaPosition currentTailPosition = currentTailPosition moveTo currentHeadPosition visitedPositions += currentTailPosition } } return visitedPositions.distinct().count() } fun part2(input: List<String>): Int { val positions = Array(10) { Position(0, 0) } val visitedPositions = mutableListOf(positions.last()) input.map { parseLine(it) } .forEach { (direction, amount) -> repeat(amount) { positions[0] += direction.deltaPosition for (positionIndex in 1..9) { positions[positionIndex] = positions[positionIndex] moveTo positions[positionIndex - 1] } visitedPositions += positions.last() } } return visitedPositions.distinct().count() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8649209f4b1264f51b07212ef08fa8ca5c7d465b
3,023
advent-of-code-2022-kotlin
Apache License 2.0
src/day21/Code.kt
fcolasuonno
162,470,286
false
null
package day21 import java.io.File import java.lang.Character.isDigit import kotlin.math.max fun main(args: Array<String>) { val name = if (true) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val (parsed, equipment) = parse(input) println("Part 1 = ${part1(parsed, equipment)}") println("Part 2 = ${part2(parsed, equipment)}") } data class Item(val name: String, val cost: Int, val damage: Int, val armour: Int) val weapons = listOf( Item("Dagger", 8, 4, 0), Item("Shortsword", 10, 5, 0), Item("Warhammer", 25, 6, 0), Item("Longsword", 40, 7, 0), Item("Greataxe", 74, 8, 0) ) val armour = listOf( Item("None", 0, 0, 0), Item("Leather", 13, 0, 1), Item("Chainmail", 31, 0, 2), Item("Splintmail", 53, 0, 3), Item("Bandedmail", 75, 0, 4), Item("Platemail", 102, 0, 5) ) val rings = listOf( Item("None1", 0, 0, 0), Item("None2", 0, 0, 0), Item("Damage +1", 25, 1, 0), Item("Damage +2", 50, 2, 0), Item("Damage +3", 100, 3, 0), Item("Defense +1", 20, 0, 1), Item("Defense +2", 40, 0, 2), Item("Defense +3", 80, 0, 3) ) data class Stat(var hp: Int, var damage: Int, var armour: Int) { operator fun plus(item: Item) = copy(damage = damage + item.damage, armour = armour + item.armour) } fun parse(input: List<String>) = input.let { Stat(it[0].filter(::isDigit).toInt(), it[1].filter(::isDigit).toInt(), it[2].filter(::isDigit).toInt()) } to weapons.flatMap { w -> armour.flatMap { a -> rings.flatMap { r1 -> rings.filter { it != r1 }.map { r2 -> listOf(w, a, r1, r2) } } } }.sortedBy { it.sumBy { it.cost } } fun playerWins(player: Stat, boss: Stat): Boolean { var isPlayerTurn = true while (player.hp > 0 && boss.hp > 0) { val attacker = if (isPlayerTurn) player else boss val defender = if (isPlayerTurn) boss else player isPlayerTurn = !isPlayerTurn defender.hp -= max(1, attacker.damage - defender.armour) } return player.hp > 0 } fun part1(boss: Stat, equipment: List<List<Item>>): Any? = equipment.first { (w, a, r1, r2) -> val player = Stat(100, 0, 0) + w + a + r1 + r2 playerWins(player, boss.copy()) }.sumBy { it.cost } fun part2(boss: Stat, equipment: List<List<Item>>): Any? = equipment.last { (w, a, r1, r2) -> val player = Stat(100, 0, 0) + w + a + r1 + r2 !playerWins(player, boss.copy()) }.sumBy { it.cost }
0
Kotlin
0
0
24f54bf7be4b5d2a91a82a6998f633f353b2afb6
2,508
AOC2015
MIT License
y2016/src/main/kotlin/adventofcode/y2016/Day20.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2016 import adventofcode.io.AdventSolution object Day20 : AdventSolution(2016, 20, "Firewall Rules") { override fun solvePartOne(input: String): String { val blacklistedIpRanges = coalesceIpRanges(input) .first() return if (blacklistedIpRanges.first > 0) "0" else (blacklistedIpRanges.last + 1).toString() } override fun solvePartTwo(input: String): String { val blacklistedIpCount = coalesceIpRanges(input).sumOf { (it.last - it.first) + 1 } return (4294967296L - blacklistedIpCount).toString() } } private fun coalesceIpRanges(input: String): List<LongRange> { return input.lineSequence() .map { it.substringBefore('-').toLong()..it.substringAfter('-').toLong() } .sortedBy { it.first } .fold(listOf(), ::combineOverlapping) .sortedBy { it.first } .fold(listOf(), ::combineAdjacent) .sortedBy { it.first } .toList() } private tailrec fun combineOverlapping(list: List<LongRange>, range: LongRange): List<LongRange> { val toCombine = list.find { range.first in it || range.last in it || it.first in range } ?: return list.plusElement(range) return when { range.first in toCombine && range.last in toCombine -> list toCombine.first in range && toCombine.last in range -> list else -> combineOverlapping(list.minusElement(toCombine), minOf(range.first, toCombine.first)..maxOf(range.last, toCombine.last)) } } private fun combineAdjacent(list: List<LongRange>, range: LongRange): List<LongRange> { val toCombine = list.find { it.last + 1 == range.first } ?: return list.plusElement(range) return list.minusElement(toCombine).plusElement(toCombine.first..range.last) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
1,652
advent-of-code
MIT License
src/aoc2023/Day07.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day07" fun totalWinning(input: List<String>, hasJoker: Boolean): Long { val size = input.size return input.map { line -> val (cards, bid) = line.split(" ").map { it.trim() } Hand(cards, hasJoker) to bid.toLong() }.sortedBy { it.first }.mapIndexed { index, (_, bid) -> (size - index) * bid }.sum() } fun part1(input: List<String>) = totalWinning(input, hasJoker = false) fun part2(input: List<String>) = totalWinning(input, hasJoker = true) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 6440) println(part1(input)) checkValue(part2(testInput), 5905) println(part2(input)) } data class Hand(val cards: String, val hasJoker: Boolean = false) : Comparable<Hand> { private val cardOrder = if (!hasJoker) { listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') } else { listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') } private val cardsComparator: Comparator<String> = Comparator { hand1, hand2 -> for (i in hand1.indices) { val order1 = cardOrder.indexOf(hand1[i]) val order2 = cardOrder.indexOf(hand2[i]) if (order1 < order2) return@Comparator -1 if (order1 > order2) return@Comparator 1 } return@Comparator 0 } private fun handType(cards: String): Int { val groups = cards.groupBy { it }.entries.map { (key, value) -> key to value.size }.sortedByDescending { it.second }.toMutableList() if (hasJoker) { val jokerIndex = groups.indexOfFirst { it.first == 'J' } val biggerIndex = groups.indexOfFirst { it.first != 'J' } if (jokerIndex >= 0 && biggerIndex >= 0) { groups[biggerIndex] = groups[biggerIndex].first to (groups[biggerIndex].second + groups[jokerIndex].second) groups.removeAt(jokerIndex) } } return when { groups.size == 1 -> 1 groups.size == 2 && groups.first().second == 4 -> 2 groups.size == 2 && groups.first().second == 3 -> 3 groups.size == 3 && groups.first().second == 3 -> 4 groups.size == 3 && groups.first().second == 2 -> 5 groups.size == 4 && groups.first().second == 2 -> 6 else -> 7 } } override fun compareTo(other: Hand): Int { val handType = handType(this.cards) val otherHandType = handType(other.cards) return when { handType != otherHandType -> handType.compareTo(otherHandType) else -> cardsComparator.compare(cards, other.cards) } } }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,961
aoc-kotlin
Apache License 2.0
src/Day11.kt
JanTie
573,131,468
false
{"Kotlin": 31854}
fun main() { fun parseInput(input: List<String>): List<Monkey> = input.chunked(7) .mapIndexed { index, it -> val items = it[1].split(": ")[1].split(", ").map { it.toLong() } val operation = it[2].split(": ")[1] val test = it[3].split(": ")[1] val ifTrue = it[4].split(": ")[1] val ifFalse = it[5].split(": ")[1] Monkey( id = index, items = items, roundTestDivisible = test.split(" ").last().toLong(), targetMonkeyIfTrue = ifTrue.split(" ").last().toInt(), targetMonkeyIfFalse = ifFalse.split(" ").last().toInt(), operation = { val left = when (val l = operation.split(" ")[2]) { "old" -> it else -> l.toLong() } val right = when (val r = operation.split(" ")[4]) { "old" -> it else -> r.toLong() } when (operation.split(" ")[3].toCharArray().first()) { '+' -> left.plus(right) '*' -> left.times(right) else -> left.plus(right) } } ) } fun simulateRounds(input: List<String>, amountOfRounds: Int, worryLevelDecrease: (Long) -> Long): List<Int> { var monkeys = parseInput(input) // calculate greatest common divisor, to decrease the numbers val modulus = monkeys.map { it.roundTestDivisible }.fold(1, Long::times) return (0 until amountOfRounds).map { // create new monkey list based on the previous one val newMonkeys = monkeys.map { it.copy() } newMonkeys.map { monkey -> val itemCountAtStart = monkey.items.size monkey.items .map { monkey.operation(it) } .map { worryLevelDecrease(it) % modulus } .forEach { if (it % monkey.roundTestDivisible == 0L) { newMonkeys[monkey.targetMonkeyIfTrue].items += it } else { newMonkeys[monkey.targetMonkeyIfFalse].items += it } monkey.items = monkey.items.drop(1) } monkey to itemCountAtStart }.also { monkeys = it.map { pair -> pair.first } } } .let { rounds -> // map by items held by each monkey (0 until rounds.first().size).map { index -> rounds.sumOf { round -> round[index].second } } } .sorted() } fun part1(input: List<String>): Int { return simulateRounds(input, 20) { it / 3 } .takeLast(2) .fold(1, Int::times) } fun part2(input: List<String>): Long { return simulateRounds(input, 10000) { it } .takeLast(2) .fold(1, Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val input = readInput("Day11") check(part1(testInput) == 10605) println(part1(input)) check(part2(testInput) == 2713310158) println(part2(input)) } data class Monkey( val id: Int, var items: List<Long>, val roundTestDivisible: Long, val targetMonkeyIfTrue: Int, val targetMonkeyIfFalse: Int, val operation: (old: Long) -> Long, )
0
Kotlin
0
0
3452e167f7afe291960d41b6fe86d79fd821a545
3,606
advent-of-code-2022
Apache License 2.0
src/Day04.kt
Jessenw
575,278,448
false
{"Kotlin": 13488}
fun main() { fun part1(input: List<String>) = input.map { pair -> val sections = processRangePair(pair) .map { Pair(it[0], it[1]) } if (rangeInRange(sections[0], sections[1]) || rangeInRange(sections[1], sections[0])) 1 else 0 }.sum() fun part2(input: List<String>) = input.map { pair -> val sections = processRangePair(pair) .map { // Generate range of values with given start and end (it[1] downTo it[0]).toList() } .flatten() // If we remove duplicates, then there is overlap if (sections.distinct().size != sections.size) 1 else 0 }.sum() val testInput = readInputLines("Day04_test") part2(testInput) check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInputLines("Day04") check(part1(input) == 413) check(part2(input) == 806) } fun processRangePair(pair: String) = pair.split(",") .map { ranges -> ranges.split("-") .map { it.toInt() } } /** * Check if a pair (a) of values fully exists within another pair (b) * Note: Assumes the first value in a pair is the lower bound */ fun rangeInRange(a: Pair<Int, Int>, b: Pair<Int, Int>) = a.first >= b.first && a.second <= b.second
0
Kotlin
0
0
05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3
1,496
aoc-22-kotlin
Apache License 2.0
year2023/src/main/kotlin/net/olegg/aoc/year2023/day7/Day7.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day7 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 7](https://adventofcode.com/2023/day/7) */ object Day7 : DayOf2023(7) { private val JOKERS = "23456789TQKA".toList() override fun first(): Any? { val order = "23456789TJQKA" return lines.map { it.split(" ").toPair() } .sortedWith( compareBy( { (card, _) -> getStrength(card) }, { (card, _) -> card.fold(0) { acc, value -> acc * order.length + order.indexOf(value) } }, ), ) .mapIndexed { index, (_, cost) -> (index + 1) * cost.toLong() } .sum() } override fun second(): Any? { val order = "J23456789TQKA" return lines.map { it.split(" ").toPair() } .sortedWith( compareBy( { (card, _) -> getStrengthJoker(card) }, { (card, _) -> card.fold(0) { acc, value -> acc * order.length + order.indexOf(value) } }, ), ) .mapIndexed { index, (_, cost) -> (index + 1) * cost.toLong() } .sum() } private fun getStrength(card: String): Int { val counts = card.groupingBy { it } .eachCount() .values .sortedDescending() return when { counts.first() == 5 -> 7 counts.first() == 4 -> 6 counts.first() == 3 && counts.second() == 2 -> 5 counts.first() == 3 -> 4 counts.first() == 2 && counts.second() == 2 -> 3 counts.first() == 2 -> 2 else -> 1 } } private fun getStrengthJoker(card: String): Int { val options = card.map { if (it == 'J') JOKERS else listOf(it) } val combinations = options.fold(1) { acc, value -> acc * value.size } return generateSequence(0) { it + 1 } .takeWhile { it < combinations } .map { combo -> options.fold(combo to emptyList<Char>()) { (rem, head), option -> rem / option.size to head + option[rem % option.size] }.second.joinToString("") } .maxOf { getStrength(it) } } private fun <T> List<T>.second() = get(1) } fun main() = SomeDay.mainify(Day7)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,145
adventofcode
MIT License
src/Day08.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
fun main() { fun part1(input: List<String>): Int { val matrix = input.map { it.map { elem -> elem.digitToInt() } } val transpose = List(matrix.first().size) { index -> matrix.map { it[index] } } var total = input.size * 4 - 4 for (i in 1..input.size - 2) for (j in 1..input.size - 2) if (transpose[j].take(i).max() < matrix[i][j] || transpose[j].takeLast(input.size - i - 1).max() < matrix[i][j] || matrix[i].take(j).max() < matrix[i][j] || matrix[i].takeLast(input.size - j - 1).max() < matrix[i][j]) total++ return total } fun part2(input: List<String>): Int { fun List<Int>.countTreesLower(): Int { var count = 0 for(tree in drop(1)) { count++ if(first() <= tree) break } return count } val matrix = input.map { it.map { elem -> elem.digitToInt() } } val transpose = List(matrix.first().size) { index -> matrix.map { it[index] } } var maxTrees = 0 for (i in 1..input.size - 2) for (j in 1..input.size - 2) { val partialMaxTrees = transpose[j].take(i + 1).reversed().countTreesLower() * transpose[j].takeLast(input.size - i).countTreesLower() * matrix[i].take(j + 1).reversed().countTreesLower() * matrix[i].takeLast(input.size - j).countTreesLower() if(partialMaxTrees > maxTrees) maxTrees = partialMaxTrees } return maxTrees } val testInput = readInput("Day08_test") val input = readInput("Day08") // part1(testInput) println(part1(testInput)) check(part1(testInput) == 21) println(part1(input)) println(part2(testInput)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
1,956
AoC-2022
Apache License 2.0
src/year2023/day17/Day17.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day17 import check import readInput import util.aStar import kotlin.math.abs fun main() { val testInput = readInput("2023", "Day17_test") check(part1(testInput), 102) check(part2(testInput), 94) val input = readInput("2023", "Day17") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.heatLoss(minStraightSteps = 0, maxStraightSteps = 3) private fun part2(input: List<String>) = input.heatLoss(minStraightSteps = 4, maxStraightSteps = 10) private data class Pos(val x: Int, val y: Int) { fun reverse() = Pos(-x, -y) companion object { val up = Pos(0, -1) val down = Pos(0, 1) val left = Pos(-1, 0) val right = Pos(1, 0) } operator fun plus(other: Pos) = Pos(x + other.x, y + other.y) infix fun distanceTo(other: Pos) = abs(x - other.x) + abs(y - other.y) override fun toString() = "($x,$y)" } private data class Node( val pos: Pos, val straightSteps: Int, val dir: Pos?, ) { fun move(moveDir: Pos) = Node( pos = pos + moveDir, straightSteps = if (moveDir == dir) (straightSteps + 1) else 1, dir = moveDir, ) } private fun List<String>.heatLoss(minStraightSteps: Int, maxStraightSteps: Int): Int { val xRange = first().indices val yRange = indices fun Node.neighboursWithHeatLoss() = sequenceOf(Pos.up, Pos.down, Pos.left, Pos.right) .filter { it.reverse() != dir } .map { move(it) } .filter { it.pos.x in xRange && it.pos.y in yRange } .filter { straightSteps >= minStraightSteps || (it.dir == dir || dir == null) } .filter { it.straightSteps <= maxStraightSteps } .mapTo(mutableSetOf()) { it to heatLoss(it.pos) } val target = Pos(first().lastIndex, lastIndex) val from = Node(Pos(0, 0), 0, null) val cruciblePath = aStar( from = from, goal = { it.pos == target && it.straightSteps >= minStraightSteps }, heuristic = { it.pos distanceTo target }, neighboursWithCost = Node::neighboursWithHeatLoss, ) //printPath(cruciblePath.path().map(Node::pos)) return cruciblePath?.cost ?: error("no path found") } private fun List<String>.heatLoss(pos: Pos) = get(pos.y)[pos.x].digitToInt() private fun List<String>.printPath(path: List<Pos>, displayPathOnly: Boolean = false) { for ((y, line) in withIndex()) { for ((x, c) in line.withIndex()) { val map = if (Pos(x, y) in path) '#' else c val pathOnly = if (Pos(x, y) in path) c else ' ' print(if (displayPathOnly) pathOnly else map) } println() } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,672
AdventOfCode
Apache License 2.0
src/Day12.kt
jbotuck
573,028,687
false
{"Kotlin": 42401}
fun main() { val lines = readInput("Day12") solve('S', lines) solve('a', lines) } fun solve(target: Char, lines: List<String>) { val distances = Array(lines.size) { Array(lines.first().length) { Int.MAX_VALUE } } val visited = mutableSetOf<Pair<Int, Int>>() val start = lines.withIndex().firstNotNullOf { indexedLine -> indexedLine.value.indexOfFirst { it == 'E' }.takeUnless { it == -1 }?.let { indexedLine.index to it } } distances.set(start, 0) val toVisit = mutableListOf(start) while (toVisit.isNotEmpty()) { val visiting = toVisit.removeClosest(distances) if (visiting in visited) continue visited.add(visiting) if (lines.getOrNull(visiting) == target) { println(distances.get(visiting)) return } val distanceOfNeighbor = distances.get(visiting).inc() for (index in lines.neighborsOf(visiting).filter { it !in visited }) { toVisit.add(index) if (distanceOfNeighbor < distances.get(index)) distances.set(index, distanceOfNeighbor) } } } private fun MutableList<Pair<Int, Int>>.removeClosest( distances: Array<Array<Int>> ): Pair<Int, Int> = removeAt(indexOfClosest(distances)) private fun List<Pair<Int, Int>>.indexOfClosest(distances: Array<Array<Int>>) = withIndex().minBy { distances.get(it.value) }.index fun Array<Array<Int>>.set(index: Pair<Int, Int>, value: Int) { get(index.first)[index.second] = value } fun Array<Array<Int>>.get(index: Pair<Int, Int>) = get(index.first)[index.second] private fun List<String>.neighborsOf(index: Pair<Int, Int>) = listOf( above(index), below(index), leftOf(index), rightOf(index) ).filter { neighbor -> getOrNull(neighbor)?.height()?.let { neighborHeight -> neighborHeight >= getOrNull(index)!!.height().dec() } ?: false } fun above(index: Pair<Int, Int>) = (index.first.dec() to index.second) fun below(index: Pair<Int, Int>) = (index.first.inc() to index.second) fun leftOf(index: Pair<Int, Int>) = (index.first to index.second.dec()) fun rightOf(index: Pair<Int, Int>) = (index.first to index.second.inc()) private fun Char.height() = when (this) { 'S' -> 'a'.code 'E' -> 'z'.code else -> code } private fun List<String>.getOrNull(index: Pair<Int, Int>) = getOrNull(index.first)?.getOrNull(index.second)
0
Kotlin
0
0
d5adefbcc04f37950143f384ff0efcd0bbb0d051
2,387
aoc2022
Apache License 2.0
src/poyea/aoc/mmxxii/day15/Day15.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day15 import kotlin.math.abs import poyea.aoc.utils.readInput data class Beacon(val x: Int, val y: Int) data class Sensor( val x: Int, val y: Int, val min_x: Int, val max_x: Int, val min_y: Int, val max_y: Int ) { companion object { fun of(x: Int, y: Int, beacon: Beacon): Sensor { val distance = abs(beacon.x - x) + abs(beacon.y - y) return Sensor( x = x, y = y, min_x = x - distance, max_x = x + distance, min_y = y - distance, max_y = y + distance ) } } fun canCover(x: Int, y: Int): Boolean { if (x in min_x..max_x && y in min_y..max_y) { val rowDiff = abs(this.y - y) return x in (min_x + rowDiff)..(max_x - rowDiff) } return false } fun intervalEnds(y: Int): Int { return max_x - abs(this.y - y) + 1 } } fun part1(input: String): Int { val sensors = mutableListOf<Sensor>() val beacons = mutableListOf<Beacon>() input .split("\n") .map { Regex("-?\\d+").findAll(it).map { it.value }.toList() } .map { beacons.add(Beacon(it[2].toInt(), it[3].toInt())) sensors.add(Sensor.of(it[0].toInt(), it[1].toInt(), beacons.last())) } val (min_x, max_x) = sensors.minOf { it.min_x } to sensors.maxOf { it.max_x } return (min_x..max_x) .fold(mutableListOf<Pair<Int, Int>>()) { coveredPoints, x -> if (sensors.any { it.canCover(x, 2000000) }) { coveredPoints.add(x to 2000000) } coveredPoints } .filter { point -> sensors.none { it.x == point.first && it.y == point.second } && beacons.none { it.x == point.first && it.y == point.second } } .size } fun part2(input: String): Long { val sensors = mutableListOf<Sensor>() val beacons = mutableListOf<Beacon>() input .split("\n") .map { Regex("-?\\d+").findAll(it).map { it.value }.toList() } .map { beacons.add(Beacon(it[2].toInt(), it[3].toInt())) sensors.add(Sensor.of(it[0].toInt(), it[1].toInt(), beacons.last())) } (0..4000000).map { y -> var x = 0 while (x < 4000000) { x = sensors.firstOrNull { it.canCover(x, y) }?.intervalEnds(y) ?: return x * 4000000L + y } } return 1L } fun main() { println(part1(readInput("Day15"))) println(part2(readInput("Day15"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
2,650
aoc-mmxxii
MIT License
src/main/kotlin/com/anahoret/aoc2022/day08/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day08 import java.io.File fun main() { val input = File("src/main/kotlin/com/anahoret/aoc2022/day08/input.txt") .readText() .trim() val matrix = parse(input) // Part 1 part1(matrix) // Part 2 part2(matrix) } fun parse(input: String): List<List<Int>> { return input.split("\n").map { it.map(Char::digitToInt) } } private fun part1(matrix: List<List<Int>>) { matrix.indices.sumOf { rowIdx -> matrix[rowIdx].indices.count { colIdx -> isVisible(matrix, rowIdx, colIdx) } }.let(::println) } private fun part2(matrix: List<List<Int>>) { matrix.indices .maxOf { rowIdx -> matrix[rowIdx].indices.maxOf { colIdx -> scenicScore(matrix, rowIdx, colIdx) } } .let(::println) } fun isVisible(matrix: List<List<Int>>, rowIdx: Int, colIdx: Int): Boolean { fun shorterThanCurrentTree(i: Int) = i < matrix[rowIdx][colIdx] val row = matrix.row(rowIdx) val col = matrix.col(colIdx) val visibleTop = col.take(rowIdx).all(::shorterThanCurrentTree) val visibleBottom = col.drop(rowIdx + 1).all(::shorterThanCurrentTree) val visibleLeft = row.take(colIdx).all(::shorterThanCurrentTree) val visibleRight = row.drop(colIdx + 1).all(::shorterThanCurrentTree) return visibleTop || visibleBottom || visibleLeft || visibleRight } fun List<List<Int>>.row(rowIdx: Int): List<Int> = this[rowIdx] fun List<List<Int>>.col(colIdx: Int): List<Int> = this.map { it[colIdx] } fun scenicScore(matrix: List<List<Int>>, rowIdx: Int, colIdx: Int): Int { fun countVisibleTrees(list: List<Int>): Int { return list .indexOfFirst { it >= matrix[rowIdx][colIdx] } .inc() .takeIf { it > 0 } ?: list.size } val scoreTop = matrix.col(colIdx).take(rowIdx).reversed().let(::countVisibleTrees) val scoreBottom = matrix.col(colIdx).drop(rowIdx + 1).let(::countVisibleTrees) val scoreLeft = matrix.row(rowIdx).take(colIdx).reversed().let(::countVisibleTrees) val scoreRight = matrix.row(rowIdx).drop(colIdx + 1).let(::countVisibleTrees) return scoreTop * scoreBottom * scoreLeft * scoreRight }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
2,175
advent-of-code-2022
Apache License 2.0
src/Day08.kt
mjossdev
574,439,750
false
{"Kotlin": 81859}
fun main() { fun readHeightMap(input: List<String>): Array<IntArray> = Array(input.size) { row -> IntArray(input[row].length) { input[row][it].digitToInt() } } fun Array<IntArray>.isVisible(row: Int, col: Int): Boolean { val height = this[row][col] return (0 until col).all { this[row][it] < height } || (col + 1..this[row].lastIndex).all { this[row][it] < height } || (0 until row).all { this[it][col] < height } || (row + 1..this.lastIndex).all { this[it][col] < height } } fun Array<IntArray>.scenicScore(row: Int, col: Int): Int { val height = this[row][col] val rowPredicate: (Int) -> Boolean = { this[it][col] >= height } val colPredicate: (Int) -> Boolean = { this[row][it] >= height } return ( (row - 1 downTo 0).countUntil(rowPredicate) * (row + 1..lastIndex).countUntil(rowPredicate) * (col - 1 downTo 0).countUntil(colPredicate) * (col + 1..this[row].lastIndex).countUntil(colPredicate) ) } fun part1(input: List<String>): Int { val heightMap = readHeightMap(input) return heightMap.indices.sumOf { row -> heightMap[row].indices.count { col -> heightMap.isVisible(row, col) } } } fun part2(input: List<String>): Int { val heightMap = readHeightMap(input) return heightMap.indices.maxOf { row -> heightMap[row].indices.maxOf { col -> heightMap.scenicScore( row, col ) } } } // 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
afbcec6a05b8df34ebd8543ac04394baa10216f0
1,895
advent-of-code-22
Apache License 2.0
2k23/aoc2k23/src/main/kotlin/08.kt
papey
225,420,936
false
{"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117}
package d08 import input.raw fun main() { println("Part 1: ${part1(raw("08.txt"))}") println("Part 2: ${part2(raw("08.txt"))}") } enum class Direction { Left, Right, None; companion object { fun fromChar(c: Char): Direction = when (c) { 'R' -> Right 'L' -> Left else -> None } } } typealias Nodes = MutableMap<String, Pair<String, String>> fun parseInput(input: String): Pair<List<Direction>, Nodes> = input.split("\n\n").let { parts -> val instructions = parts.first().toCharArray().map { Direction.fromChar(it) } val regex = Regex("(\\w+) = \\((\\w+), (\\w+)\\)") val nodes: Nodes = parts[1].split("\n").filter { it.isNotBlank() }.fold(mutableMapOf()) { acc, line -> val groups = regex.find(line)!!.groupValues acc[groups[1]] = Pair(groups[2], groups[3]) acc } Pair(instructions, nodes) } const val END_NODE = "ZZZ" fun traverse(start: String, nodes: Nodes, instructions: List<Direction>, isEndReached: (String) -> Boolean): Int { var currentNode = start val directions = generateSequence { instructions }.flatten().iterator() return directions.asSequence().takeWhile { val node = nodes[currentNode]!! currentNode = if (it == Direction.Left) { node.first } else { node.second } !isEndReached(currentNode) }.count() + 1 } fun gcd(a: Long, b: Long): Long { return if (b == 0L) a else gcd(b, a % b) } fun lcm(a: Long, b: Long): Long { return if (a == 0L || b == 0L) 0 else (a * b) / gcd(a, b) } fun part1(input: String): Int { val (instructions, nodes) = parseInput(input) return traverse("AAA", nodes, instructions) { node -> node == END_NODE } } fun part2(input: String): Long { val (instructions, nodes) = parseInput(input) val startingNodes = nodes.filter { it.key.endsWith('A') } return startingNodes.keys.map { traverse(it, nodes, instructions) { node -> node.endsWith('Z') } }.map { it.toLong() }.reduce { acc, v -> lcm(acc, v) } }
0
Rust
0
3
cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5
2,119
aoc
The Unlicense
src/Day11.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
private class Monkey( val items: MutableList<Long>, val operation: (Long) -> Long, val test: Long, val ifTrue: Int, val ifFalse: Int, ) { var inspected : Long = 0 } private fun monkeys(input: String) = input.split("\n\n").map { it.lines() }.map { monkey -> Monkey( items = monkey[1].dropWhile { !it.isDigit() }.split(", ").map { it.toLong() }.toMutableList(), operation = monkey[2].split(" ").takeLast(2).let { (op, value) -> when (op) { "+" -> { old -> old + (value.toLongOrNull() ?: old) } "*" -> { old -> old * (value.toLongOrNull() ?: old) } else -> error(op) } }, test = monkey[3].split(" ").last().toLong(), ifTrue = monkey[4].split(" ").last().toInt(), ifFalse = monkey[5].split(" ").last().toInt(), ) } fun main() { fun part1(input: String): Long { val monkeys = monkeys(input) repeat(times = 20) { monkeys.forEach { monkey -> generateSequence { monkey.items.removeFirstOrNull() }.forEach { item -> monkey.inspected++ val worryLevel = monkey.operation(item) / 3 monkeys[if (worryLevel % monkey.test == 0L) monkey.ifTrue else monkey.ifFalse].items.add(worryLevel) } } } return monkeys.map { it.inspected }.sortedDescending().take(2).reduce(Long::times) } fun part2(input: String): Long { val monkeys = monkeys(input) val calmFactor = monkeys.map { it.test }.distinct().reduce(Long::times) repeat(times = 10000) { monkeys.forEach { monkey -> generateSequence { monkey.items.removeFirstOrNull() }.forEach { item -> monkey.inspected++ val worryLevel = monkey.operation(item) % calmFactor monkeys[if (worryLevel % monkey.test == 0L) monkey.ifTrue else monkey.ifFalse].items.add(worryLevel) } } } return monkeys.map { it.inspected }.sortedDescending().take(2).reduce(Long::times) } // test if implementation meets criteria from the description, like: val testInput = readText("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readText("Day11") with(part1(input)) { check(this == 182293L) println(this) } with(part2(input)) { check(this == 54832778815) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
2,566
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
rafael-ribeiro1
572,657,838
false
{"Kotlin": 15675}
fun main() { fun part1(input: List<String>): Int { return input.buildMatrix() .visibleTrees() } fun part2(input: List<String>): Int { return input.buildMatrix() .highestScenicScore() } // 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)) } fun List<String>.buildMatrix(): Array<IntArray> { return Array(this.size) { IntArray(this[0].length) }.also { this.forEachIndexed { i, input -> it[i] = input.toList().map { it.digitToInt() }.toIntArray() } } } fun Array<IntArray>.visibleTrees(): Int { var visibleTrees = 0 this.forEachIndexed { i, row -> row.forEachIndexed { j, _ -> if (this.isTreeVisible(i, j)) { visibleTrees++ } } } return visibleTrees } fun Array<IntArray>.isTreeVisible(row: Int, column: Int): Boolean { if (row == 0 || column == 0 || row == this.size - 1 || column == this[0].size - 1) { return true } val treeHeight = this[row][column] // Left if (this[row].copyOfRange(0, column).all { it < treeHeight }) { return true } // Right if (this[row].copyOfRange(column + 1, this[row].size).all { it < treeHeight }) { return true } // Top if (this.copyOfRange(0, row).all { it[column] < treeHeight }) { return true } // Bottom if (this.copyOfRange(row + 1, this.size).all { it[column] < treeHeight }) { return true } return false } fun Array<IntArray>.highestScenicScore(): Int { return this.withIndex() .maxOf { row -> row.value.withIndex() .maxOf { column -> this.scenicScore(row.index, column.index) } } } fun Array<IntArray>.scenicScore(row: Int, column: Int): Int { if (row == 0 || column == 0 || row == this.size - 1 || column == this[0].size - 1) { return 0 } val treeHeight = this[row][column] return this[row].copyOfRange(0, column).reversed().viewingDistance(treeHeight) * // Left this[row].copyOfRange(column + 1, this[row].size).toList().viewingDistance(treeHeight) * // Right this.copyOfRange(0, row).map { it[column] }.reversed().viewingDistance(treeHeight) * // Top this.copyOfRange(row + 1, this.size).map { it[column] }.viewingDistance(treeHeight) // Bottom } fun List<Int>.viewingDistance(treeHeight: Int): Int { return (this.indexOfFirst { it >= treeHeight }.takeIf { it != -1 } ?: (this.size - 1)) + 1 }
0
Kotlin
0
0
5cae94a637567e8a1e911316e2adcc1b2a1ee4af
2,740
aoc-kotlin-2022
Apache License 2.0
src/2022/Day12.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun parseInput(input: List<String>): Day12Input { val field = input.map { it.asIterable().toMutableList() } var startPoint = Point(0, 0) var endPoint = Point(0, 0) field.forEachIndexed { i,line -> line.forEachIndexed { j, char -> when (char) { 'S' -> { startPoint = Point(i, j) field[i][j] = 'a' } 'E' -> { endPoint = Point(i, j) field[i][j] = 'z' } } } } return Day12Input(field, startPoint, endPoint) } fun buildWeights(input: Day12Input): Map<Point, Int> { fun List<List<Char>>.canReach(currentPoint: Point, nextPoint: Point): Boolean { val m = size val n = first().size if (currentPoint.x !in 0 until m || currentPoint.y !in 0 until n) return false if (nextPoint.x !in 0 until m || nextPoint.y !in 0 until n) return false return this[nextPoint.x][nextPoint.y] - this[currentPoint.x][currentPoint.y] <= 1 } val (field, _, endPoint) = input val weights = mutableMapOf(endPoint to 0) var step = 0 do { val currentPoints = weights.filter { (_, weight) -> weight == step }.keys step++ currentPoints.forEach { point -> point.nearestPoints().forEach { if (field.canReach(it, point) && !weights.contains(it)) { weights[it] = step } } } } while (currentPoints.isNotEmpty()) return weights } fun part1(input: List<String>): Int { val parsedInput = parseInput(input) val weights = buildWeights(parsedInput) return weights[parsedInput.startPoint]!! } fun part2(input: List<String>): Int { val parsedInput = parseInput(input) val weights = buildWeights(parsedInput) val (field) = parsedInput val possibleStarts = field.flatMapIndexed { i,line -> line.mapIndexedNotNull { j, char -> if (char == 'a') Point(i, j) else null } } return possibleStarts.mapNotNull { weights[it] }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) } data class Day12Input(val field: List<List<Char>>, val startPoint: Point, val endPoint: Point) fun Point.nearestPoints(): List<Point> { return listOf(Point(x - 1, y), Point(x, y - 1), Point(x + 1, y), Point(x, y + 1)) }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
2,983
aoc-2022-in-kotlin
Apache License 2.0
src/Day08.kt
inssein
573,116,957
false
{"Kotlin": 47333}
fun main() { fun List<String>.toGrid(): List<List<Int>> = this.map { s -> s.map { it.digitToInt() } } fun List<List<Int>>.toView(row: Int, col: Int): List<List<Int>> = listOf( (row - 1 downTo 0).map { this[it][col] }, // up (row + 1 until this.size).map { this[it][col] }, // down (col - 1 downTo 0).map { this[row][it] }, // left this[row].drop(col + 1), // right ) fun List<List<Int>>.isVisible(row: Int, col: Int): Boolean { if (row == 0 || col == 0 || row == this.size - 1 || col == this.first().size - 1) { return true } return this.toView(row, col).any { direction -> direction.all { it < this[row][col] } } } fun List<List<Int>>.scenicScore(row: Int, col: Int): Int { if (row == 0 || col == 0 || row == this.size - 1 || col == this.first().size - 1) { return 0 } return this.toView(row, col).map { direction -> direction .indexOfFirst { it >= this[row][col] } .let { if (it == -1) direction.size else it + 1 } }.reduce { acc, it -> acc * it } } fun part1(input: List<String>): Int { val grid = input.toGrid() return (grid.indices).sumOf { row -> (grid.first().indices).count { col -> grid.isVisible(row, col) } } } fun part2(input: List<String>): Int { val grid = input.toGrid() return (grid.indices).maxOf { row -> (grid.first().indices).maxOf { col -> grid.scenicScore(row, col) } } } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) // 1849 println(part2(input)) // 201600 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
1,883
advent-of-code-2022
Apache License 2.0
src/Day12.kt
chbirmes
572,675,727
false
{"Kotlin": 32114}
fun main() { fun part1(input: List<String>): Int = HeightGrid.parse(input).shortestPathLengthToTopFrom { it.isStart } fun part2(input: List<String>): Int = HeightGrid.parse(input).shortestPathLengthToTopFrom { it.height == 'a' } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) } class HeightGrid(private val cells: List<List<Cell>>) { fun shortestPathLengthToTopFrom(cellPredicate: (Cell) -> Boolean): Int { val start = positionsWhere(cellPredicate) val sequence = generateSequence(start) { step(it) } return sequence.indexOfFirst { it.map { visited -> cellAt(visited) } .any { cell -> cell.isGoal } } } private fun positionsWhere(cellPredicate: (Cell) -> Boolean): Set<Position> = cells.flatMapIndexed { y, row -> row.mapIndexed { x: Int, cell: Cell -> if (cellPredicate.invoke(cell)) Position(x, y) else null } } .filterNotNull() .toSet() private fun cellAt(position: Position) = cells[position.y][position.x] private fun nonVisitedNeighbors(p: Position) = p.neighbors() .filter { it.y in cells.indices && it.x in cells.first().indices } .filter { cellAt(it).height.code - cellAt(p).height.code <= 1 } .filterNot { cellAt(it).wasVisited } private fun step(lastVisited: Set<Position>): Set<Position> { return lastVisited.flatMap { nonVisitedNeighbors(it) } .onEach { cellAt(it).wasVisited = true } .toSet() } data class Cell( val height: Char, val isStart: Boolean = false, val isGoal: Boolean = false, var wasVisited: Boolean = false ) data class Position(val x: Int, val y: Int) { fun neighbors() = setOf(copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1)) } companion object { fun parse(input: List<String>): HeightGrid { val cells = input.map { line -> line.map { when (it) { 'S' -> Cell('a', isStart = true, wasVisited = true) 'E' -> Cell('z', isGoal = true) else -> Cell(it) } } } return HeightGrid(cells) } } }
0
Kotlin
0
0
db82954ee965238e19c9c917d5c278a274975f26
2,529
aoc-2022
Apache License 2.0
src/Day15.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
import java.math.BigInteger import kotlin.math.absoluteValue fun main() { fun part1(input: List<String>, targetY: Int): Int { val sensorsAndBeacons = inputToSensorsAndBeacons(input) val inRange = sensorsAndBeacons.filter { val coverageRadius = it.first.manhattanDinstanceTo(it.second) val sensorY = it.first.y sensorY - coverageRadius <= targetY && sensorY + coverageRadius >= targetY } val pointsInRange = inRange.flatMap { val coverageRadius = it.first.manhattanDinstanceTo(it.second) coverageAtY(it.first, coverageRadius, targetY) }.toSet() val beacons = sensorsAndBeacons.map { it.second }.toSet() return pointsInRange.subtract(beacons).size } fun part2(input: List<String>): BigInteger { val sensorsAndBeacons = inputToSensorsAndBeacons(input) val intersectionsWithY = sensorsAndBeacons.flatMap { val coverageRadius = it.first.manhattanDinstanceTo(it.second) intersectsAxisY(it.first, coverageRadius) }.toSet().sortedBy { point -> point.first } println(intersectionsWithY) // algo: // for each intersection, check if there is another one with the same slope only two positions away // for each of those two pairs of intersections // calculate the y and x // check with inRange returns false // calculate x * 4M + y and return // intersections with a difference of two are (241656, true), (241658, true) and (6650616, false), (6650618, false) val y = ((6650618 - 1) - (241658 - 1)) / 2 val x = 6650618 - 1 - y return x.toBigInteger() * 4000000.toBigInteger() + y.toBigInteger() } val testInput = readLines("Day15_test") val input = readLines("Day15") check(part1(testInput, 10) == 26) println(part1(input, 2000000)) println(part2(input)) } fun coverageAtY(sensor: Point, coverageRadius: Int, y: Int): Set<Point> { return if (sensor.y - coverageRadius <= y && sensor.y + coverageRadius >= y) { val gap = (sensor.y - y).absoluteValue ((sensor.x - coverageRadius + gap)..(sensor.x + coverageRadius - gap)).map { Point(it, y) }.toSet() } else emptySet() } fun inRange(point: Point, sensor: Point, beacon: Point): Boolean { val coverageRadius = sensor.manhattanDinstanceTo(beacon) val distance = point.manhattanDinstanceTo(sensor) return distance <= coverageRadius } fun intersectsAxisY(sensor: Point, coverageRadius: Int): Set<Pair<Int, Boolean>> { val up = if (sensor.y - coverageRadius >= 0) { setOf(Pair(sensor.x - (sensor.y - coverageRadius), true), Pair(sensor.x + (sensor.y - coverageRadius), false)) } else { setOf(Pair(sensor.x - (coverageRadius - sensor.y), true), Pair(sensor.x + (coverageRadius - sensor.y), false)) } return setOf(Pair(sensor.x - (sensor.y + coverageRadius), true), Pair(sensor.x + (sensor.y + coverageRadius), false)).union(up) } fun inputToSensorsAndBeacons(input: List<String>): List<Pair<Point, Point>> { return input.map { val match = "Sensor at x=(-*\\d+), y=(-*\\d+): closest beacon is at x=(-*\\d+), y=(-*\\d+)".toRegex().find(it) Pair( Point(match!!.groups[1]?.value?.toInt()!!, match.groups[2]?.value?.toInt()!!), Point(match.groups[3]?.value?.toInt()!!, match.groups[4]?.value?.toInt()!!)) } }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
3,478
advent-of-code-kotlin-2022
Apache License 2.0
src/day12/Day12_functional.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day12 import Point2D import readLines import java.util.PriorityQueue /** * 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. */ data class PathCost(val point: Point2D, val cost: Int) : Comparable<PathCost> { override fun compareTo(other: PathCost): Int = this.cost.compareTo(other.cost) } class HeightMap(val elevations: Map<Point2D, Int>, val start: Point2D, val end: Point2D) { fun shortestPath(begin: Point2D, isGoal: (Point2D) -> Boolean, canMove: (Int, Int) -> Boolean): Int { val seen = mutableSetOf<Point2D>() val queue = PriorityQueue<PathCost>().apply { add(PathCost(begin, 0)) } while (queue.isNotEmpty()) { val nextPoint = queue.poll() if (nextPoint.point !in seen) { seen += nextPoint.point val neighbors = nextPoint.point.cardinalNeighbors() .filter { it in elevations } // filters OUT anything off the map .filter { canMove(elevations.getValue(nextPoint.point), elevations.getValue(it)) } // gathers valid moves if (neighbors.any { isGoal(it) }) return nextPoint.cost + 1 // if we found what we're looking for, return cost+1 queue.addAll(neighbors.map { PathCost(it, nextPoint.cost + 1) }) // else add PathCosts to queue } } throw IllegalStateException("No valid path from $start to $end") } } private fun parseInput(input: List<String>): HeightMap { var start: Point2D? = null var end: Point2D? = null val elevations = input.flatMapIndexed { y, row -> // flatMapIndexed takes a bunch of lists and flattens/combines them row.mapIndexed { x, char -> // for each (index, char) in row val here = Point2D(x, y) here to when (char) { // "here to" is creating a pair with the result ("height" of the char) from the when statement 'S' -> 0.also { start = here } 'E' -> 25.also { end = here } else -> char - 'a' } } }.toMap() return HeightMap(elevations, start!!, end!!) } fun part1(heightMap: HeightMap): Int { return heightMap.shortestPath( begin = heightMap.start, isGoal = { it == heightMap.end }, canMove = { from, to -> to - from <= 1 } ) } fun part2(heightMap: HeightMap): Int { return heightMap.shortestPath( begin = heightMap.end, isGoal = { heightMap.elevations[it] == 0 }, canMove = { from, to -> from - to <= 1 } ) } fun main() { println(part1(parseInput(readLines("day12/test")))) println(part2(parseInput(readLines("day12/test")))) println(part1(parseInput(readLines("day12/input")))) println(part2(parseInput(readLines("day12/input")))) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
2,955
aoc2022
Apache License 2.0
src/Day01.kt
ralstonba
573,072,217
false
{"Kotlin": 4128}
fun main() { fun part1(input: List<String>): Int { var currentMax = Int.MIN_VALUE var runningSum = 0 for (i in input) { // Check that the current value is a number if (i.toIntOrNull() != null) { runningSum += i.toInt() } else { // Space is delimiter currentMax = currentMax.coerceAtLeast(runningSum) runningSum = 0 } } return currentMax } fun part2(input: List<String>, k: Int): Int { // Given ["a", "", "a", "b", "", "c"] return the index of each "" // Yield [1, 4] val splitAt = input.withIndex() .filter { it.value.isBlank() } .map { it.index }.toMutableList() splitAt += input.size // Given [1, 4], the list of all split points, create the sublists // ["a", "", "a", "b", "", "c"] -> subList(0, 1) == ["a"], sublist(2, 4) == ["a", "b"], sublist(5, size) == ["c"] return (0 until splitAt.size) .asSequence() .map { input.subList(if (it == 0) it else splitAt[it - 1] + 1 , splitAt[it]) } // At this point every item in the list should be numbers, convert the strings to actual numbers .map { sublist -> sublist.sumOf { it.toInt() }} // Sort the sequence so that we can retrieve the k-largest .sortedDescending() // Get the sum .take(k) .sum() } // Cuts should be happening [0, 3], [4, 5], [6, 8], [9, 12], [13, 14] // test if implementation meets criteria from the description, like: val testInput = readInput("Day01TestInput") check(part1(testInput) == 24_000) // Solve Part 1 val input = readInput("Day01Input") println("Part 1 solution: ${part1(input)}") // Test with provided example check(part2(testInput, 3) == 45_000) // Solve Part 2 println("Part 2 solution: ${part2(input, 3)}") }
0
Kotlin
0
0
93a8ba96db519f4f3d42e2b4148614969faa79b1
2,002
aoc-2022
Apache License 2.0
src/main/kotlin/be/twofold/aoc2021/Day05.kt
jandk
433,510,612
false
{"Kotlin": 10227}
package be.twofold.aoc2021 object Day05 { fun part1(lines: List<Line>): Int { return solve(lines, false) } fun part2(lines: List<Line>): Int { return solve(lines, true) } private fun solve(lines: List<Line>, useDiagonal: Boolean): Int { val horizontal = lines .filter { it.y1 == it.y2 } .flatMap { range(it.x1, it.x2).map { x -> Point(x, it.y1) } } val vertical = lines .filter { it.x1 == it.x2 } .flatMap { range(it.y1, it.y2).map { y -> Point(it.x1, y) } } val allPoints = if (useDiagonal) { val diagonal = lines .filter { it.x1 - it.y1 == it.x2 - it.y2 || it.x1 + it.y1 == it.x2 + it.y2 } .flatMap { (x1, y1, x2, y2) -> range(x1, x2).zip(range(y1, y2)) .map { Point(it.first, it.second) } } horizontal + vertical + diagonal } else { horizontal + vertical } return allPoints .groupingBy { it } .eachCount() .filterValues { it > 1 } .count() } private fun range(a: Int, b: Int) = if (a < b) a..b else a downTo b fun line(s: String): Line { return s.split(',', ' ') .let { Line(it[0].toInt(), it[1].toInt(), it[3].toInt(), it[4].toInt()) } } data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int) data class Point(val x: Int, val y: Int) } fun main() { val input = Util.readFile("/day05.txt") .map { Day05.line(it) } println("Part 1: ${Day05.part1(input)}") println("Part 2: ${Day05.part2(input)}") }
0
Kotlin
0
0
2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3
1,698
aoc2021
MIT License
src/Day02.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
import kotlin.math.max fun main() { fun isPossible(mm: Map<String, Int>, marbles: String): Boolean { marbles.trim().split(";").forEach { mb -> mb.trim().split(",").associate { it.trim().split(" ").let { it[1] to it[0].toInt() } }.forEach { (color, count) -> if (count > (mm[color] ?: 0)) return false } } return true } fun part1(input: List<String>): Int { val m = mapOf( "red" to 12, "green" to 13, "blue" to 14, ) return input.sumOf { line -> val (game, marbles) = line.split(":").let { it[0].split(" ")[1].toInt() to it[1] } if (isPossible(m, marbles)) game else 0 } } fun minRequired(marbles: String): Int { val maxMap = mutableMapOf<String, Int>() marbles.trim().split(";").map { mb -> mb.trim().split(",").associate { it.trim().split(" ").let { it[1] to it[0].toInt() } }.forEach { (color, count) -> maxMap[color] = max(count, maxMap[color] ?: 0) } } return maxMap.values.fold(1) { acc, i -> acc * i } } fun part2(input: List<String>): Int { return input.sumOf { line -> val (_, marbles) = line.split(":").let { it[0].split(" ")[1].toInt() to it[1] } minRequired(marbles) } } val input = readInput("Day02") part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
1,636
aoc-2023
Apache License 2.0
src/day08/Day08.kt
Harvindsokhal
572,911,840
false
{"Kotlin": 11823}
package day08 import readInput enum class Direction { LEFT, RIGHT, UP, DOWN } fun main() { val data = readInput("day08/day08_data") fun visibleTrees(x: Int, y: Int) = if (x == 0 || x == data[0].lastIndex || y == 0 || y == data.lastIndex) { true } else { (0 until x).none { data[y][it] >= data[y][x] } || (x + 1 until data[0].length).none { data[y][it] >= data[y][x] } || (0 until y).none { data[it][x] >= data[y][x] } || (y + 1 until data.size).none { data[it][x] >= data[y][x] } } fun part1(list: List<String>) = list.mapIndexed { y, line -> line.filterIndexed { x, _ -> visibleTrees(x, y) } }.sumOf { it.length } fun viewingDistance(direction: Direction, x: Int, y: Int): Int { val range = when (direction) { Direction.LEFT -> (x - 1 downTo 0) Direction.RIGHT -> (x + 1 until data[0].length) Direction.UP -> (y - 1 downTo 0) Direction.DOWN -> (y + 1 until data.size) } var blockingTreeMet = false return range.takeWhile { val tree = when (direction) { Direction.LEFT, Direction.RIGHT -> data[y][it] Direction.UP, Direction.DOWN -> data[it][x] } if (blockingTreeMet) return@takeWhile false if (tree >= data[y][x]) blockingTreeMet = true true }.count() } fun scenicScore(x: Int, y: Int) = viewingDistance(Direction.LEFT, x, y) * viewingDistance(Direction.RIGHT, x, y) * viewingDistance(Direction.UP, x, y) * viewingDistance(Direction.DOWN, x, y) fun part2(list: List<String>) = list.mapIndexed { y, line -> List(line.length) { x -> scenicScore(x, y) } }.flatten().max() println(part1(data)) println(part2(data)) }
0
Kotlin
0
0
7ebaee4887ea41aca4663390d4eadff9dc604f69
1,931
aoc-2022-kotlin
Apache License 2.0
src/Day08.kt
mhuerster
572,728,068
false
{"Kotlin": 24302}
enum class Direction { NORTH, SOUTH, EAST, WEST } fun main() { class Tree(val height: Int, val y: Int, val x: Int) { override fun toString() : String { return "$height at [$y, $x]" } fun viewingDistance(direction: Direction, trees: List<List<Tree>>) : Int { val neighbors = when (direction) { Direction.NORTH -> northernNeighbors(trees).asReversed() Direction.SOUTH -> southernNeighbors(trees) Direction.EAST -> easternNeighbors(trees) Direction.WEST -> westernNeighbors(trees).asReversed() } val visibleNeighbors = neighbors.takeWhile { it.height < this.height || it.isEdge(trees) } if (visibleNeighbors.size == neighbors.size) { return visibleNeighbors.size } if (neighbors.elementAt(visibleNeighbors.size).height >= this.height) { return visibleNeighbors.size + 1 } else { return visibleNeighbors.size } } fun scenicScore(trees: List<List<Tree>>) : Int { return viewingDistance(Direction.NORTH, trees) .times(viewingDistance(Direction.SOUTH, trees)) .times(viewingDistance(Direction.EAST, trees)) .times(viewingDistance(Direction.WEST, trees)) } // same x value as Tree, lesser y value fun northernNeighbors(trees: List<List<Tree>>): List<Tree> { return trees.take(this.y).flatten().filter { it.x == this.x } } // same x value as Tree, greater y value fun southernNeighbors(trees: List<List<Tree>>): List<Tree> { return trees.slice((this.y+1)..trees.lastIndex).flatten().filter { it.x == this.x } } // same y value as Tree, greater x value fun easternNeighbors(trees: List<List<Tree>>): List<Tree> { return trees[this.y].filter { it.x > this.x } } // same y value as Tree, lesser x value fun westernNeighbors(trees: List<List<Tree>>): List<Tree> { return trees[this.y].filter { it.x < this.x } } /* A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree. One neighbor in each direction must be taller for a tree to to be invisible. */ fun isVisible(trees: List<List<Tree>>) : Boolean { if (isEdge(trees)) { return true} when { northernNeighbors(trees).filter { it.height >= height }.isEmpty() -> return true southernNeighbors(trees).filter { it.height >= height }.isEmpty() -> return true easternNeighbors(trees).filter { it.height >= height }.isEmpty() -> return true westernNeighbors(trees).filter { it.height >= height }.isEmpty() -> return true else -> return false } } // assumes minX and minY are both 0 fun isEdge(trees: List<List<Tree>>) : Boolean { val maxX = trees.first().lastIndex val maxY = trees.lastIndex when { (x == 0) -> return true (y == 0) -> return true (x == maxX) -> return true (y == maxY) -> return true else -> return false } } } fun part1(input: List<String>): Int { val trees = input.mapIndexed { y, element -> element.toCharArray().mapIndexed { x, height -> Tree(height.digitToInt(), y, x) } } val visibleTrees = trees.flatten().filter { it.isVisible(trees)} return visibleTrees.size } fun part2(input: List<String>): Int { val trees = input.mapIndexed { y, element -> element.toCharArray().mapIndexed { x, height -> Tree(height.digitToInt(), y, x) } } return trees.flatten().map { it.scenicScore(trees) }.max() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_sample") // println(part1(testInput)) check(part1(testInput) == 21) // println(part2(testInput)) check(part2(testInput) == 8) val input = readInput("Day09") // println(part1(input)) check(part1(input) == 1711) check(part2(input) < 2322000) check(part2(input) > 267904) println(part2(input)) }
0
Kotlin
0
0
5f333beaafb8fe17ff7b9d69bac87d368fe6c7b6
4,111
2022-advent-of-code
Apache License 2.0
2021/src/main/kotlin/Day09.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day09(private val input: List<String>) { private fun List<String>.heightMap(): Grid = this.map { it.toList().map { Character.getNumericValue(it) } } private fun Grid.lowPoints(): List<Pair<Int, Int>> = this.foldIndexed(emptyList()) { rowIdx, allPoints, row -> row.foldIndexed(allPoints) { colIdx, points, height -> this.neighbours(rowIdx, colIdx).all { (x, y) -> this[x][y] > height } .let { isLowest -> if (isLowest) points + (rowIdx to colIdx) else points } } } private fun Grid.neighbours(rowIdx: Int, colIdx: Int): List<Pair<Int, Int>> = arrayOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1)).map { (dx, dy) -> rowIdx + dx to colIdx + dy } .filter { (x, y) -> x in this.indices && y in this.first().indices } private fun Grid.basin(rowIdx: Int, colIdx: Int): List<Pair<Int, Int>> = this.neighbours(rowIdx, colIdx).filterNot { (x, y) -> this[x][y] == 9 } .fold(listOf((rowIdx to colIdx))) { points, (x, y) -> points + if (this[x][y] - this[rowIdx][colIdx] >= 1) basin(x, y) else emptyList() } fun solve1(): Int { val heightMap = input.heightMap() return heightMap.lowPoints().sumOf { (x, y) -> heightMap[x][y] + 1 } } fun solve2(): Int { val heightMap = input.heightMap() return heightMap.lowPoints().map { (rowIdx, colIdx) -> heightMap.basin(rowIdx, colIdx).toSet().size } .sortedDescending().take(3).reduce { acc, i -> acc * i } } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
1,537
adventofcode-2021-2025
MIT License
src/Day07.kt
Totwart123
573,119,178
false
null
fun main() { data class File(val name: String, val size: Int) data class Folder(val name: String, val files: MutableList<File>, val folders: MutableList<Folder>, val parentFolder: Folder?) fun calculateFolderSize(folder: Folder): Int{ val size = folder.files.sumOf { it.size } + folder.folders.sumOf { calculateFolderSize(it) } return size } fun flatnFolder(folder: Folder): MutableList<Folder>{ val result = folder.folders.toMutableList() folder.folders.forEach { result.addAll(flatnFolder(it)) } return result } fun getFoldersFromInput(input: List<String>): List<Pair<Folder, Int>> { var currentFolder = Folder("/", mutableListOf(), mutableListOf(), null) val rootFolder = currentFolder input.forEach { line -> val splitted = line.split(" ") if (splitted[0] == "$") { if (splitted[1] == "cd") { if (splitted[2].startsWith("/")) { currentFolder = rootFolder } val dirs = splitted[2].trim().split("/") dirs.filter { it.isNotEmpty() && it.isNotBlank() }.forEach { dir -> currentFolder = if (dir == "..") { val parentFolder = currentFolder.parentFolder parentFolder ?: currentFolder } else { if (!currentFolder.folders.any { it.name == dir }) { currentFolder.folders.add(Folder(dir, mutableListOf(), mutableListOf(), currentFolder)) } currentFolder.folders.first { it.name == dir } } } } } else if (splitted[0].toIntOrNull() != null) { currentFolder.files.add(File(splitted[1], splitted[0].toInt())) } } val allFolders = flatnFolder(rootFolder) allFolders.add(rootFolder) return allFolders.map { Pair(it, calculateFolderSize(it)) } } fun part1(input: List<String>): Int { return getFoldersFromInput(input).filter { it.second <= 100000 }.sumOf { it.second } } fun part2(input: List<String>): Int { val folders = getFoldersFromInput(input) val totalSize = folders.first { it.first.name == "/" }.second val spaceToFreeUp = 30000000 - 70000000 + totalSize return folders.filter { it.second >= spaceToFreeUp }.minOf { it.second } } 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
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
2,805
AoC
Apache License 2.0
src/main/kotlin/Day24.kt
gijs-pennings
573,023,936
false
{"Kotlin": 20319}
import java.util.* fun main() { val lines = readInput(24) val blizzards = mutableListOf<Blizzard>() lines.forEachIndexed { y, row -> row.forEachIndexed { x, pos -> if (pos != '.' && pos != '#') blizzards += Blizzard(x, y, when (pos) { '^' -> 1 '>' -> 2 'v' -> 3 '<' -> 4 else -> throw IllegalStateException() }) } } val start = Pos(1, 0) val end = Pos(lines[0].length - 2, lines.size - 1) var s = State(Map(lines[0].length, lines.size, blizzards), setOf(start)) while (end !in s) s = s.next() /* uncomment for part 2: s = s.replacePositions(end) while (start !in s) s = s.next() s = s.replacePositions(start) while (end !in s) s = s.next() */ println(s.time) } private data class Blizzard( val x: Int, val y: Int, val d: Int // direction: 1=north, 2=east, 3=south, 4=west ) { fun next(w: Int, h: Int) = when (d) { 1 -> Blizzard(x, if (y == 1) h-2 else y-1, d) 3 -> Blizzard(x, if (y == h-2) 1 else y+1, d) 2 -> Blizzard(if (x == w-2) 1 else x+1, y, d) 4 -> Blizzard(if (x == 1) w-2 else x-1, y, d) else -> throw IllegalStateException() } } private class Map( val w: Int, val h: Int, private val blizzards: List<Blizzard> ) { private val occupiedByBlizzard = BitSet(w * h) init { for (b in blizzards) occupiedByBlizzard[b.x + b.y * w] = true } fun isValid(x: Int, y: Int): Boolean { if (x == 1 && y == 0 || x == w-2 && y == h-1) return true if (x <= 0 || x >= w-1 || y <= 0 || y >= h-1) return false return !occupiedByBlizzard[x + y * w] } fun next() = Map(w, h, blizzards.map { it.next(w, h) }) } private class State( val map: Map, val possiblePositions: Set<Pos>, val time: Int = 0 ) { operator fun contains(p: Pos) = p in possiblePositions fun next(): State { val nextMap = map.next() return State( nextMap, possiblePositions .flatMap { (x, y) -> listOf(Pos(x, y), Pos(x, y-1), Pos(x+1, y), Pos(x, y+1), Pos(x-1, y)) } .distinct() .filter { (x, y) -> nextMap.isValid(x, y) } .toSet(), time + 1 ) } fun replacePositions(vararg ps: Pos) = State(map, ps.toSet(), time) }
0
Kotlin
0
0
8ffbcae744b62e36150af7ea9115e351f10e71c1
2,478
aoc-2022
ISC License
src/day8/Day8.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day8 import readInput fun main() { val testInput = parse(readInput("day08/test")) val input = parse(readInput("day08/input")) println(solve1(testInput)) println(solve1(input)) println(solve2(testInput)) println(solve2(input)) } fun row(arr: Array<IntArray>, idx: Int, ids: IntProgression) : Sequence<Int> { require(idx >= 0 && idx < arr.size) return ids.map { arr[idx][it] }.asSequence() } fun column(arr: Array<IntArray>, idx: Int, ids: IntProgression): Sequence<Int> { return ids.map { arr[it][idx] }.asSequence() } fun <T> Sequence<T>.takeWhileInclusive(pred: (T) -> Boolean): Sequence<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = pred(it) result } } fun solve2(arr: Array<IntArray>): Int { fun value(o: Int, i: Int) : Int { val v = arr[o][i] return sequenceOf( row(arr, o, i - 1 downTo 0), row(arr, o, i + 1 .. arr[0].lastIndex), column(arr, i, o - 1 downTo 0), column(arr, i, o + 1 .. arr.lastIndex) ) .map {x -> x.takeWhileInclusive { v > it }.count() } .reduce{ a,b -> a * b } } var max = -1 for(o in arr.indices) { for(i in arr[o].indices) { val result = value(o,i) if(result > max) max = result } } return max } fun solve1(arr: Array<IntArray>): Int { var counter = 0 fun isVisible(o: Int, i: Int): Boolean { val v = arr[o][i] return sequenceOf( row(arr, o, i - 1 downTo 0), row(arr, o, i + 1 .. arr[0].lastIndex), column(arr, i, o - 1 downTo 0), column(arr, i, o + 1 .. arr.lastIndex) ).map { it.all { x -> x < v } }.any{it} } for(o in arr.indices) { for(i in arr[0].indices) { if(isVisible(o, i)) { counter += 1 } } } return counter } fun parse(input: List<String>): Array<IntArray> { fun arr(s: String): IntArray = s.map { it.digitToInt() }.toIntArray() return input.map{arr(it)}.toTypedArray() }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
2,183
aoc-2022
Apache License 2.0
src/Day11.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Long { return solve(monkeys = input.asMonkeys(), iterations = 20, reliefOp = { x -> x / 3 }) } fun part2(input: List<String>): Long { val monkeys = input.asMonkeys() val moduloOp = monkeys.fold(1) { acc, b -> acc * b.divisibleBy } return solve(monkeys = input.asMonkeys(), iterations = 10000, reliefOp = { x -> x % moduloOp }) } val input = readInput("Day11") println(part1(input)) println(part2(input)) } private fun List<String>.asMonkeys(): List<Monkey> = chunked(7) .map { val items = it[1].substringAfter(Items_Prefix).split(", ").map(String::toLong).toMutableList() val operationData = it[2].substringAfter(Operation_Prefix).split(" ") val amount = operationData.last().toLongOrNull() val operation = if (operationData.first() == "*") { x: Long -> x * (amount ?: x) } else { x: Long -> x + (amount ?: x) } val testOp = it[3].substringAfter(Test_Prefix).toInt() val trueIndex = it[4].substringAfter(Test_True_Prefix).toInt() val falseIndex = it[5].substringAfter(Test_False_Prefix).toInt() val getForwardTo = { x: Long -> if (x % testOp == 0L) trueIndex else falseIndex } Monkey(items = items, divisibleBy = testOp, operation = operation, getForwardTo = getForwardTo) } fun solve(monkeys: List<Monkey>, iterations: Int, reliefOp: (Long) -> Long): Long { repeat(iterations) { monkeys.forEach { monkey -> monkey.items.forEach { item -> val newValue = reliefOp(monkey.evaluate(item)) val to = monkey.getForwardTo(newValue) monkeys[to].items.add(newValue) } monkey.items.clear() } } return monkeys.map(Monkey::evaluations).sortedDescending().take(2).reduce { a, b -> a * b } } const val Items_Prefix = "Starting items: " const val Operation_Prefix = "Operation: new = old " const val Test_Prefix = "Test: divisible by " const val Test_True_Prefix = "If true: throw to monkey " const val Test_False_Prefix = "If false: throw to monkey " data class Monkey( val items: MutableList<Long>, val divisibleBy: Int, private val operation: (Long) -> (Long), val getForwardTo: (Long) -> Int ) { var evaluations: Long = 0L fun evaluate(value: Long): Long { evaluations++ return operation(value) } }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
2,533
aoc-2022
Apache License 2.0
src/day12/Day12.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day12 import utils.* data class Coords(var x: Int, var y: Int) { operator fun plus(other: Coords): Coords = Coords(x + other.x, y + other.y) operator fun minus(other: Coords): Coords = Coords(x - other.x, y - other.y) } class Map(lines: List<String>) { lateinit var start: Coords private lateinit var end: Coords private val map: List<List<Int>> = lines.mapIndexed { y, line -> line.mapIndexed { x, c -> when (c) { 'S' -> { start = Coords(x, y) 'a' } 'E' -> { end = Coords(x, y) 'z' } else -> c } - 'a' } } private val width get() = map.first().size private val height get() = map.size fun getCoordsOfHeight(height: Int): Set<Coords> = map.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, h -> Coords(x, y).takeIf { h == height } } }.toSet() private fun getValidNeighbors(coords: Coords): List<Coords> = listOf( coords + Coords(1, 0), coords + Coords(-1, 0), coords + Coords(0, 1), coords + Coords(0, -1) ).filter { it.x in 0 until width && it.y in 0 until height && map[it.y][it.x] <= map[coords.y][coords.x] + 1 } fun solve(possibleStarts: Set<Coords>): Int { val visited = possibleStarts.toMutableSet() var stack = possibleStarts.toMutableList() generateSequence(0) { (it + 1).takeIf { stack.isNotEmpty() } }.forEach { depth -> val newStack = mutableListOf<Coords>() stack.forEach { coords -> getValidNeighbors(coords).forEach neighborLoop@{ neighbor -> if (neighbor in visited) return@neighborLoop if (neighbor == end) return depth + 1 newStack.add(neighbor) visited.add(neighbor) } } stack = newStack } return -1 } } fun part1(input: List<String>): Int = Map(input).run { solve(setOf(start)) } fun part2(input: List<String>): Int = Map(input).run { solve(getCoordsOfHeight(0)) } fun main() { val testInput = readInput("Day12_test") expect(part1(testInput), 31) expect(part2(testInput), 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
2,690
AOC-2022-Kotlin
Apache License 2.0
src/Day11.kt
bananer
434,885,332
false
{"Kotlin": 36979}
fun increase(levels: Array<IntArray>, flashes: MutableSet<Pair<Int, Int>>, x: Int, y: Int) { if(++levels[x][y] > 9 && !flashes.contains(Pair(x, y))) { flash(levels, flashes, x, y) } } fun flash(levels: Array<IntArray>, flashes: MutableSet<Pair<Int, Int>>, x: Int, y: Int) { flashes.add(Pair(x, y)) val adjacent = listOf( Pair(x - 1, y - 1), Pair(x - 1, y), Pair(x - 1, y + 1), Pair(x, y - 1), Pair(x, y + 1), Pair(x + 1, y - 1), Pair(x + 1, y), Pair(x + 1, y + 1), ) adjacent.forEach { (ax, ay) -> if (levels.indices.contains(ax) && levels[0].indices.contains(ay)) { increase(levels, flashes, ax, ay) } } } fun step(levels: Array<IntArray>): Int { val flashes = mutableSetOf<Pair<Int, Int>>() levels.indices.forEach { x -> levels[x].indices.forEach { y -> increase(levels, flashes, x, y) } } levels.indices.forEach { x -> levels[x].indices.forEach { y -> if (levels[x][y] > 9) { levels[x][y] = 0 } } } return flashes.size } fun main() { fun parseInput(input: List<String>): Array<IntArray> { val w = input.first().length return input.map { line -> line.map { it.digitToInt() } .also { check(it.size == w) } .toIntArray() }.toTypedArray() } fun part1(input: List<String>): Int { val levels = parseInput(input) return (0 until 100).sumOf { step(levels) } } fun part2(input: List<String>): Int { val levels = parseInput(input) val count = levels.size * levels[0].size return (1 until Int.MAX_VALUE).first { step(levels) == count } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val testOutput1 = part1(testInput) println("test output1: $testOutput1") check(testOutput1 == 1656) val testOutput2 = part2(testInput) println("test output2: $testOutput2") check(testOutput2 == 195) val input = readInput("Day11") println("output part1: ${part1(input)}") println("output part2: ${part2(input)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
2,322
advent-of-code-2021
Apache License 2.0
src/day08/Day08.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day08 import readInput fun main() { data class Point( val x: Int, val y: Int, val height: Int, var matching: Boolean = false, var scenicScore: Int = 0 ) fun createGrid(input: List<String>): List<List<Point>> { val grid = mutableListOf<MutableList<Point>>() for ((index, line) in input.withIndex()) { grid.add(index, mutableListOf()) grid[index].addAll(line.mapIndexed { i, c -> Point(x = i, y = index, height = c.digitToInt()) }) } return grid } fun part1(input: List<String>): Int { val grid = createGrid(input) grid.forEach { line -> line.forEachIndexed { lineIndex, point -> when { // The tree is at the edge x coordinate point.x == 0 || point.x == line.lastIndex -> point.matching = true // The tree is at the edge y coordinate point.y == 0 || point.y == line.lastIndex -> point.matching = true // All trees on the left are less tall (0 until point.x).all { i -> line[i].height < point.height } -> point.matching = true // All trees on the right are less tall (point.x + 1..line.lastIndex).all { i -> line[i].height < point.height } -> point.matching = true // All trees above are less tall (0 until point.y).all { i -> grid[i][lineIndex].height < point.height } -> point.matching = true // All trees below are less tall (point.y + 1..grid.lastIndex).all { i -> grid[i][lineIndex].height < point.height } -> point.matching = true } } } return grid.sumOf { list -> list.count { it.matching } } } fun part2(input: List<String>): Int { val grid = createGrid(input) grid.forEach { line -> line.forEachIndexed { lineIndex, point -> // Count the trees to the left that are less tall var first = (point.x - 1 downTo 0).takeWhile { i -> line[i].height < point.height }.count() if (point.x > first) first++ // Count the trees to the right that are less tall var second = (point.x + 1..line.lastIndex).takeWhile { i -> line[i].height < point.height }.count() if (line.lastIndex - point.x > second) second++ // Count the trees above that are less tall var third = (point.y - 1 downTo 0).takeWhile { i -> grid[i][lineIndex].height < point.height }.count() if (point.y > third) third++ // Count the trees below that are less tall var fourth = (point.y + 1..grid.lastIndex).takeWhile { i -> grid[i][lineIndex].height < point.height }.count() if (grid.lastIndex - point.y > fourth) fourth++ point.scenicScore = first * second * third * fourth } } return grid.maxOf { list -> list.maxOf { it.scenicScore } } } val input = readInput("day08/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
3,230
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/aoc2021/day5.kt
sodaplayer
434,841,315
false
{"Kotlin": 31068}
package aoc2021 import aoc2021.utils.loadInput import aoc2021.utils.partitionWhen import kotlin.math.max import kotlin.math.min fun main() { val pattern = Regex("""(\d+),(\d+) -> (\d+),(\d+)""") val lines = loadInput("/2021/day5-test") .bufferedReader() .readLines() .map { val (x1, y1, x2, y2) = pattern.find(it)!!.destructured Line( x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt() ) } val orthogonal = lines.filter { (x1, y1, x2, y2) -> x1 == x2 || y1 == y2 } val (horizontal, vertical) = orthogonal.partition { it.y1 == it.y2 } val horRanges = horizontal.groupBy({it.x1}) { min(it.x1, it.x2) .. max(it.x1, it.x2) } .mapValues { (_, ranges) -> ranges.sortedWith(compareBy({ it.first }, { it.last })) } // val horOverlaps = horRanges.filterValues { it.size > 1 } println( listOf(0..2, 0..3, 3..4, 5..6, 6..7).groupOverlapping().toList() ) } data class RangeMerge(val overlapping: Int, val ranges: List<IntRange>) data class RangeMergeStep(val overlapping: Int, val ranges: List<IntRange>) /** Merges contiguous ranges together and counts their overlaps */ //fun Sequence<IntRange>.mergeRanges(): RangeMerge { //} /** Separates a sorted sequence of ranges into groups of overlapping ones */ fun Sequence<IntRange>.groupOverlapping(): Sequence<List<IntRange>> { return partitionWhen { prev, next -> prev.last < next.first } } fun Iterable<IntRange>.groupOverlapping(): Sequence<List<IntRange>> = this.asSequence().groupOverlapping() //data class //fun countOverlaps /* Assumes other begins after this and other's start is contained in this */ fun IntRange.overlap(other: IntRange): Int = other.first - this.first + 1 data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int)
0
Kotlin
0
0
2d72897e1202ee816aa0e4834690a13f5ce19747
1,963
aoc-kotlin
Apache License 2.0
src/day9/Day9.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day9 import readInput import toPair import kotlin.math.absoluteValue import kotlin.math.sign fun main() { val testInput = parse(readInput("day09/test")) val input = parse(readInput("day09/input")) println("${solve1(testInput)} , ${solve2(testInput, 1)}") println("${solve1(input)} , ${solve2(input, 1)}") println(solve2(testInput, 9)) println(solve2(input, 9)) } fun next(pKnot : Pos, thisKnot: Pos) : Pos { val x = pKnot.first - thisKnot.first val y = pKnot.second - thisKnot.second return if(x.absoluteValue < 2 && y.absoluteValue < 2) { thisKnot } else { thisKnot.first + x.sign to thisKnot.second + y.sign } } fun solve1(moves: List<Move>): Int { val tailVisited = hashSetOf<Pos>() val head = 0 to 0 var tail = 0 to 0 for(p in (sequenceOf(head) + positions(head, moves))) { tailVisited.add(tail) tail = next(p, tail) } tailVisited.add(tail) return tailVisited.size } fun positions(initial: Pos, moves: List<Move>): Sequence<Pos> { var current = initial return sequence { for(m in moves) { val next = m.apply(current) current = next.last() yieldAll(next) } } } fun solve2(moves: List<Move>, knotsNo: Int): Int { val head = 0 to 0 val tailVisited = hashSetOf<Pos>() var knots = Array(knotsNo) {0 to 0}.toList() fun move(s: Pos): List<Pos> { var prev = s val r= sequence { for(k in knots) { val n = next(prev, k) prev = n yield(n) } }.toList() return r } for(p in (sequenceOf(head) + positions(head, moves))) { tailVisited.add(knots.last()) knots = move(p) } tailVisited.add(knots.last()) return tailVisited.size } typealias Pos = Pair<Int, Int> /* first horizontal (x), second vertical (y) */ enum class Dir { L, R, U, D } data class Move(val steps: Int, val dir: Dir) { fun apply(p: Pos): Sequence<Pos> { return when(dir) { Dir.L -> (1 .. steps).map { p.first + it to p.second } Dir.R -> (1 .. steps).map { p.first - it to p.second } Dir.U -> (1 .. steps).map { p.first to p.second + it } Dir.D -> (1 .. steps).map { p.first to p.second - it } }.asSequence() } } fun parse(input: List<String>): List<Move> { fun map(s: String) : Move { val (d, st) = s.split("""\s+""".toRegex()).toPair() return Move(st.toInt(), Dir.valueOf(d)) } return input.map{map(it)} }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
2,611
aoc-2022
Apache License 2.0
src/year2021/day09/Day09.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2021.day01.day09 import util.assertTrue import util.model.Counter import util.read2021DayInput import java.awt.Point fun main() { fun task01(input: List<List<Int>>): Int { return findLowPoints(input).sumOf { it.first + 1 } } fun task02(input: List<List<Int>>): Int { val lowPoints = findLowPoints(input) val basins = MutableList(input.size) { MutableList(input[0].size) { false } } val basinCounts = MutableList(lowPoints.count()) { Counter() } fun markBasins(point: Point, previous: Int, counter: Counter) { input.getOrNull(point.y)?.getOrNull(point.x)?.let { current -> if (current > previous && current != 9 && !basins[point.y][point.x]) { basins[point.y][point.x] = true counter.i++ markBasins(Point(point.x + 1, point.y), current, counter) markBasins(Point(point.x - 1, point.y), current, counter) markBasins(Point(point.x, point.y + 1), current, counter) markBasins(Point(point.x, point.y - 1), current, counter) } } } lowPoints.forEachIndexed { index, lowPoint -> markBasins(lowPoint.second, lowPoint.first - 1, basinCounts[index]) } return basinCounts.map { it.i }.sorted().takeLast(3).reduce { acc, basinSize -> acc * basinSize } } val input = read2021DayInput("Day09").map { it.map { "$it".toInt() } } assertTrue(task01(input) == 514) assertTrue(task02(input) == 1103130) } fun findLowPoints(list: List<List<Int>>): MutableList<Pair<Int, Point>> { val lowPoints = mutableListOf<Pair<Int, Point>>() for (y in list.indices) { for (x in list[y].indices) { val point = Point(x, y) val result = listOf( if (point.y + 1 > list.size - 1) null else list[point.y][point.x] < list[point.y + 1][point.x], // smaller than down if (point.y - 1 < 0) null else list[point.y][point.x] < list[point.y - 1][point.x], // smaller than up if (point.x + 1 > list[point.y].size - 1) null else list[point.y][point.x] < list[point.y][point.x + 1], // smaller than right if (point.x - 1 < 0) null else list[point.y][point.x] < list[point.y][point.x - 1] // smaller than left ) if (!result.any { it == false }) lowPoints.add(Pair(list[y][x], Point(x, y))) } } return lowPoints }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
2,517
advent-of-code-kotlin-template
Apache License 2.0
src/Day08.kt
zdenekobornik
572,882,216
false
null
import java.lang.Integer.max fun main() { fun <T> Iterable<T>.countWhile(predicate: (T) -> Boolean): Int { var count = 0 for (item in this) { if (!predicate(item)) break count++ } return count } fun part1(input: List<String>): Int { val map = input.map { it.map(Char::digitToInt) } var treeCount = 0 for (y in 1 until map.size - 1) { for (x in 1 until map[y].size - 1) { val left by lazy { (0 until x).all { map[y][it] < map[y][x] } } val right by lazy { (x + 1 until map[y].size).all { map[y][it] < map[y][x] } } val bottom by lazy { (y + 1 until map.size).all { map[it][x] < map[y][x] } } val top by lazy { (0 until y).all { map[it][x] < map[y][x] } } if (left || right || bottom || top) { treeCount++ } } } return 2 * (map.size - 2) + 2 * (map[0].size) + treeCount } fun part2(input: List<String>): Int { val map = input.map { it.map(Char::digitToInt) } var score = 0 for (y in 1 until map.size - 1) { for (x in 1 until map[y].size - 1) { val left = (x - 1 downTo 1).countWhile { map[y][it] < map[y][x] } + 1 val right = (x + 1 until map[y].size - 1).countWhile { map[y][it] < map[y][x] } + 1 val bottom = (y + 1 until map.size - 1).countWhile { map[it][x] < map[y][x] } + 1 val top = (y - 1 downTo 1).countWhile { map[it][x] < map[y][x] } + 1 score = max(score, left * right * bottom * top) } } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") checkResult(part1(testInput), 21) checkResult(part2(testInput), 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f73e4a32802fa43b90c9d687d3c3247bf089e0e5
2,029
advent-of-code-2022
Apache License 2.0
src/day15/Day15.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day15 import Edges import Position import readInput import kotlin.math.abs fun main() { fun parse(input: List<String>): Pair<List<Position>, List<Position>> { return input.map { line -> val chunks = line.split(" ").map { it.replace(Regex("""[xy,:=]"""), "") } Position(chunks[2].toInt(), chunks[3].toInt()) to Position(chunks[8].toInt(), chunks[9].toInt()) }.unzip() } fun findEdges(positions: List<Position>): Edges { val xValues = positions.map { line -> line.x } val yValues = positions.map { line -> line.y } return Edges( Position(xValues.min(), yValues.min()), Position(xValues.max(), yValues.max()), ) } fun Position.distance(to: Position): Int { return abs(to.x - this.x) + abs(to.y - this.y) } fun countEmptySpaces(sensors: List<Position>, beacons: List<Position>, atY: Int): Int { val beaconDistances = sensors.zip(beacons).map { (sensor, beacon) -> sensor to sensor.distance(beacon) } val minX = beaconDistances.map { (sensor, dist) -> sensor.x - dist }.min() val maxX = beaconDistances.map { (sensor, dist) -> sensor.x + dist }.max() return (minX..maxX).map { x -> val currentPos = Position(x, atY) beaconDistances.map { (sensor, dist) -> currentPos.distance(sensor) <= dist && !beacons.contains(currentPos) }.any { it } }.count { it } } fun part1(input: List<String>, atY: Int): Int { val (sensors, beacons) = parse(input) return countEmptySpaces(sensors, beacons, atY) } fun inRange(currentPos: Position, min: Int, max: Int): Boolean { return currentPos.x in min..max && currentPos.y in min..max } fun findSensor(sensors: List<Position>, beacons: List<Position>, min: Int, max: Int): Position { val beaconDistances = sensors.zip(beacons).map { (sensor, beacon) -> sensor to sensor.distance(beacon) } beaconDistances.forEach { (sensor, dist) -> sensor.positionsAtDist(dist + 1).forEach { position -> if (inRange(position, min, max)) { if (beaconDistances.map { (s, d) -> position.distance(s) > d }.all { it }) { return position } } } } error(" ") } fun part2(input: List<String>, min: Int, max: Int): Long { val (sensors, beacons) = parse(input) val sensor = findSensor(sensors, beacons, min, max) return (sensor.x * 4000000L) + sensor.y } // test if implementation meets criteria from the description, like: val testInput = readInput("day15/Day15_test") val input = readInput("day15/Day15") check((part1(testInput, 10)).also { println(it) } == 26) println(part1(input, 2_000_000)) check(part2(testInput, 0, 20).also { println(it) } == 56000011L) println(part2(input, 0, 4000000)) } private fun Position.positionsAtDist(dist: Int): Set<Position> { return (-dist..dist).map { delta -> listOf( Position(this.x + delta, this.y + (dist - delta)), Position(this.x + delta, this.y - (dist - delta)), ) }.flatten().toSet() }
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
3,477
advent-of-code-kotlin-2022
Apache License 2.0
src/Day07.kt
anisch
573,147,806
false
{"Kotlin": 38951}
data class File(val name: String, val size: Long = 0) class Directory { var name: String = "" var upDir: Directory? = null val listDirs = mutableListOf<Directory>() val listFiles = mutableListOf<File>() var totalSize = 0L } fun calculateSizes(root: Directory): Directory { if (root.listDirs.isNotEmpty()) { root.totalSize += calculateSizes(root.listDirs) } return root } fun calculateSizes(list: List<Directory>): Long = list.map { calculateSizes(it) }.sumOf { it.totalSize } fun tree(root: Directory): List<Directory> = if (root.listDirs.isNotEmpty()) listOf(root) + tree(root.listDirs) else listOf(root) fun tree(list: List<Directory>): List<Directory> = list.flatMap { tree(it) } fun createFileSystem(input: List<String>): Directory { val fileSystem = Directory().also { it.name = "/" } var current = fileSystem input .drop(1) // jump over "cd /" .forEach { line -> when { line.startsWith("$ cd") -> { val s = line.split(" ") val tmp = if (s[2] == "..") current.upDir!! else current.listDirs.first { f -> f.name == s[2] } current = tmp } line.startsWith("$ ls") -> {} // ignore else -> { // ls val (size, name) = line.split(" ") if (line.startsWith("dir")) { val dir = Directory().also { it.name = name it.upDir = current } current.listDirs += dir } else { current.listFiles += File(name, size.toLong()) current.totalSize += size.toLong() } } } } return calculateSizes(fileSystem) } fun main() { fun part1(input: List<String>): Long { val fileSystem = createFileSystem(input) return tree(fileSystem) .filter { it.totalSize <= 100_000 } .sumOf { it.totalSize } } fun part2(input: List<String>): Long { val maxSpace = 70_000_000L val minSpace = 30_000_000L val fileSystem = createFileSystem(input) val free = maxSpace - fileSystem.totalSize val freeUp = minSpace - free return tree(fileSystem) .filter { it.totalSize >= freeUp } .minOf { it.totalSize } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") val input = readInput("Day07") check(part1(testInput) == 95437L) println(part1(input)) check(part2(testInput) == 24933642L) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
2,937
Advent-of-Code-2022
Apache License 2.0
src/day08/Day08.kt
zypus
573,178,215
false
{"Kotlin": 33417, "Shell": 3190}
package day08 import AoCTask // https://adventofcode.com/2022/day/8 private fun firstPassFromEdge(input: List<String>): List<List<Pair<Int, Boolean>>> { val rowHeights = input.first().map { -1 }.toMutableList() val firstPass = input.map { row -> var maxPreviousHeight = -1 row.mapIndexed { index, tree -> val height = tree.digitToInt() var visible = false if (rowHeights[index] < height) { rowHeights[index] = height visible = true } if (maxPreviousHeight < height) { maxPreviousHeight = height visible = true } height to visible } } return firstPass } private fun secondPassFromEdge( firstPass: List<List<Pair<Int, Boolean>>> ): List<List<Pair<Int, Boolean>>> { val rowHeights = firstPass.first().map { -1 }.toMutableList() return firstPass.reversed().map { row -> var maxPreviousHeight = -1 row.reversed().mapIndexed { index, (height, alreadyVisible) -> var visible = alreadyVisible if (rowHeights[index] < height) { rowHeights[index] = height visible = true } if (maxPreviousHeight < height) { maxPreviousHeight = height visible = true } height to visible } } } private fun computeTreeScores(input: List<String>): List<Int> { return input.flatMapIndexed { rowIndex, row -> row.mapIndexed { colIndex, tree -> val height = tree.digitToInt() val left = minOf(colIndex, row.take(colIndex).reversed().takeWhile { it.digitToInt() < height }.length + 1) val right = minOf(row.length - colIndex - 1, row.drop(colIndex + 1).takeWhile { it.digitToInt() < height }.length + 1) val top = minOf(rowIndex, input.take(rowIndex).reversed().takeWhile { it[colIndex].digitToInt() < height }.size + 1) val bottom = minOf(input.size - rowIndex - 1, input.drop(rowIndex + 1).takeWhile { it[colIndex].digitToInt() < height }.size + 1) left * right * top * bottom } } } fun part1(input: List<String>): Int { val firstPass = firstPassFromEdge(input) val secondPass = secondPassFromEdge(firstPass) return secondPass.sumOf { row -> row.count { it.second } } } fun part2(input: List<String>): Int { val scores = computeTreeScores(input) return scores.max() } fun main() = AoCTask("day08").run { // test if implementation meets criteria from the description, like: check(part1(testInput) == 21) check(part2(testInput) == 8) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f37ed8e9ff028e736e4c205aef5ddace4dc73bfc
2,757
aoc-2022
Apache License 2.0
src/year2023/Day17.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import Direction import Grid import Point import readLines import java.util.PriorityQueue fun main() { val input = parseInput(readLines("2023", "day17")) val testInput = parseInput(readLines("2023", "day17_test")) check(part1(testInput) == 102) { "Incorrect result for part 1: ${part1(testInput)}" } println("Part 1:" + part1(input)) check(part2(testInput) == 94) { "Incorrect result for part 2: ${part2(testInput)}" } println("Part 2:" + part2(input)) } private fun parseInput(input: List<String>): Grid<Int> { return Grid(input.map { line -> line.toCharArray().toList().map { it.digitToInt() } }) } private fun part1(grid: Grid<Int>): Int { return solve(grid, 1, 3) } private fun part2(grid: Grid<Int>): Int { return solve(grid, 4, 10) } private fun solve(grid: Grid<Int>, minStraightMoves: Int, maxStraightMoves: Int): Int { val goal = Point(grid.cols - 1, grid.rows - 1) val visited = mutableSetOf<Pair<Point, Direction>>() val frontier = PriorityQueue<State>(compareBy<State> { it.costSoFar }.thenBy { it.point.manhattenDistance(goal) }).also { queue -> queue.addAll(Direction.entries.map { State(Point(0, 0), it, 0) }) } while (frontier.isNotEmpty()) { frontier.peek() val state = frontier.remove() val point = state.point if (point == goal) { return state.costSoFar } if (visited.contains(Pair(state.point, state.fromDirection))) { continue } visited.add(Pair(state.point, state.fromDirection)) frontier.addAll(state.generateAllValidNextStates(grid, minStraightMoves, maxStraightMoves)) } return -1 } private data class State(val point: Point, val fromDirection: Direction, val costSoFar: Int) { fun generateAllValidNextStates(grid: Grid<Int>, minStraightMoves: Int, maxStraightMoves: Int): List<State> { val neighbors = mutableListOf<State>() for (direction in fromDirection.orthogonalDirections()) { var newCost = 0 var newPoint = point for (amount in (1..maxStraightMoves)) { newPoint = newPoint.add(direction.toPoint()) val newPointIsValid = newPoint.x >= 0 && newPoint.x < grid.cols && newPoint.y >= 0 && newPoint.y < grid.rows if (!newPointIsValid) { break } newCost += grid.getOrNull(newPoint.x, newPoint.y) ?: 0 if (amount >= minStraightMoves) { neighbors.add(State(newPoint, direction, costSoFar + newCost)) } } } return neighbors } } private fun Direction.orthogonalDirections() = when (this) { Direction.NORTH, Direction.SOUTH -> listOf(Direction.EAST, Direction.WEST) Direction.EAST, Direction.WEST -> listOf(Direction.NORTH, Direction.SOUTH) }
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
2,916
advent_of_code
MIT License
src/Day18.kt
nikolakasev
572,681,478
false
{"Kotlin": 35834}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { val cubes = inputToCubes(input) return surfaceArea(cubes) } fun part2(input: List<String>): Int { val cubes = inputToCubes(input) val minX = cubes.minByOrNull { it.first } val minY = cubes.minByOrNull { it.second } val minZ = cubes.minByOrNull { it.third } val min = min(min(minX!!.first, minY!!.second), minZ!!.third) val maxX = cubes.maxByOrNull { it.first } val maxY = cubes.maxByOrNull { it.second } val maxZ = cubes.maxByOrNull { it.third } val max = max(max(maxX!!.first, maxY!!.second), maxZ!!.third) val startingPoint = Triple(0, 0, 0) val visited = mutableSetOf<Triple<Int, Int, Int>>() var surfaceArea = 0 val q = ArrayDeque<Triple<Int, Int, Int>>() q.add(startingPoint) while (q.isNotEmpty()) { val c = q.removeFirst() if (c !in visited) { visited.add(c) val neighbours = withinBounds(min - 1, max + 1, neighbours(c.first, c.second, c.third)) .subtract(visited) for (n in neighbours) { if (n in cubes) { surfaceArea += 1 } else q.add(n) } } } return surfaceArea } val testInput = readLines("Day18_test") val testInput2 = readLines("Day18_test2") val input = readLines("Day18") check(part1(testInput) == 10) check(part1(testInput2) == 64) check(part2(testInput2) == 58) check(part2(testInput2) == 58) println(part1(input)) println(part2(input)) } fun neighbours(x: Int, y: Int, z: Int): Set<Triple<Int, Int, Int>> { return setOf( Triple(x + 1, y, z), Triple(x - 1, y, z), Triple(x, y + 1, z), Triple(x, y - 1, z), Triple(x, y, z + 1), Triple(x, y, z - 1) ) } fun withinBounds(min: Int, max: Int, cubes: Set<Triple<Int, Int, Int>>): Set<Triple<Int, Int, Int>> { return cubes.filter { it.first in min..max && it.second in min..max && it.third in min..max }.toSet() } fun inputToCubes(input: List<String>): Set<Triple<Int, Int, Int>> { return input.map { val coordinates = it.split(",") Triple(coordinates[0].toInt(), coordinates[1].toInt(), coordinates[2].toInt()) }.toSet() } fun surfaceArea(cubes: Set<Triple<Int, Int, Int>>): Int { return cubes.sumOf { c -> val rest = cubes - c 6 - neighbours(c.first, c.second, c.third).intersect(rest).size } }
0
Kotlin
0
1
5620296f1e7f2714c09cdb18c5aa6c59f06b73e6
2,678
advent-of-code-kotlin-2022
Apache License 2.0
src/Day02.kt
zhtk
579,137,192
false
{"Kotlin": 9893}
enum class Shape { PAPER, ROCK, SCISSORS } enum class RoundOutcome { WIN, DRAW, LOSS } val shapeWinsWithMap = mapOf(Shape.PAPER to Shape.ROCK, Shape.ROCK to Shape.SCISSORS, Shape.SCISSORS to Shape.PAPER) data class Round(val you: Shape, val opponent: Shape) { fun getOutcome(): RoundOutcome = when { you == opponent -> RoundOutcome.DRAW shapeWinsWithMap[you] == opponent -> RoundOutcome.WIN else -> RoundOutcome.LOSS } } fun main() { val opponentMoves = mapOf("A" to Shape.ROCK, "B" to Shape.PAPER, "C" to Shape.SCISSORS) val yourMoves = mapOf("X" to Shape.ROCK, "Y" to Shape.PAPER, "Z" to Shape.SCISSORS) val yourOutcomes = mapOf("X" to RoundOutcome.LOSS, "Y" to RoundOutcome.DRAW, "Z" to RoundOutcome.WIN) val outcomePoints = mapOf(RoundOutcome.LOSS to 0, RoundOutcome.DRAW to 3, RoundOutcome.WIN to 6) val shapePoints = mapOf(Shape.ROCK to 1, Shape.PAPER to 2, Shape.SCISSORS to 3) val input = readInput("Day02").filterNot { it.isEmpty() }.map { it.split(' ') } val strategy1 = input.map { Round(yourMoves[it[1]]!!, opponentMoves[it[0]]!!) } strategy1.sumOf { outcomePoints[it.getOutcome()]!! + shapePoints[it.you]!! }.println() val strategy2 = input.map { val opponentMove = opponentMoves[it[0]]!! Round(getCorrectMove(yourOutcomes[it[1]]!!, opponentMove), opponentMove) } strategy2.sumOf { outcomePoints[it.getOutcome()]!! + shapePoints[it.you]!! }.println() } fun getCorrectMove(expectedOutcome: RoundOutcome, opponentMove: Shape): Shape = when (expectedOutcome) { RoundOutcome.DRAW -> opponentMove RoundOutcome.WIN -> shapeWinsWithMap.entries.firstOrNull { it.value == opponentMove }!!.key RoundOutcome.LOSS -> shapeWinsWithMap[opponentMove]!! }
0
Kotlin
0
0
bb498e93f9c1dd2cdd5699faa2736c2b359cc9f1
1,762
aoc2022
Apache License 2.0
y2022/src/main/kotlin/adventofcode/y2022/Day12.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2022 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import adventofcode.util.vector.neighbors object Day12 : AdventSolution(2022, 12, "Hill Climbing Algorithm") { override fun solvePartOne(input: String): Int { val landscape = parse(input) return bfs(listOf(landscape.start), landscape.end, landscape::reachableNeighbors) } override fun solvePartTwo(input: String): Int { val landscape = parse(input) return bfs(landscape.getLowestPoints(), landscape.end, landscape::reachableNeighbors) } private fun bfs(start: Iterable<Vec2>, goal: Vec2, reachableNeighbors: (Vec2) -> Iterable<Vec2>): Int = generateSequence(Pair(start.toSet(), start.toSet())) { (frontier, visited) -> val unexploredNeighbors = frontier.flatMap(reachableNeighbors).toSet() - visited Pair(unexploredNeighbors, visited + unexploredNeighbors) } .takeWhile { (frontier, _) -> frontier.isNotEmpty() } .indexOfFirst { (frontier, _) -> goal in frontier } } private fun parse(input: String): Landscape { var start: Vec2? = null var end: Vec2? = null val terrain = input.lines().mapIndexed { row, line -> line.mapIndexed { col, ch -> when (ch) { 'S' -> 0.also { start = Vec2(col, row) } 'E' -> 25.also { end = Vec2(col, row) } else -> ch - 'a' } } } return Landscape(start!!, end!!, terrain) } private data class Landscape(val start: Vec2, val end: Vec2, private val heights: List<List<Int>>) { private operator fun contains(pos: Vec2) = pos.y in heights.indices && pos.x in heights[pos.y].indices private fun height(pos: Vec2) = heights[pos.y][pos.x] fun reachableNeighbors(pos: Vec2) = pos.neighbors() .filter { it in this } .filter { height(pos) + 1 >= height(it) } fun getLowestPoints() = heights.indices.flatMap { y -> heights[0].indices.map { x -> Vec2(x, y) } } .filter { height(it) == 0 } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,147
advent-of-code
MIT License
src/year2021/08/Day08.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`08` import readInput fun main() { fun deductMappingOfNumbers(left: List<String>): Map<Set<Char>, Int> { val leftSet = left.toSortedSet() val one = leftSet.find { it.length == 2 }!!.toSortedSet() val four = leftSet.find { it.length == 4 }!!.toSortedSet() val seven = leftSet.find { it.length == 3 }!!.toSortedSet() val eight = leftSet.find { it.length == 7 }!!.toSortedSet() val segment0 = (seven - one).single() val six = leftSet .filter { it.length == 6 } .map { it.toSortedSet() } .single { sixCandidate -> sixCandidate.containsAll(eight - seven) } val segment2 = (eight - six).single() val five = leftSet .filter { it.length == 5 } .map { it.toSortedSet() } .single { fiveCandidate -> six.containsAll(fiveCandidate) } val segment4 = (six - five).single() val segment6 = (five - four - segment0).single() val two = leftSet .filter { it.length == 5 } .map { it.toSortedSet() } .single { twoCandidate -> twoCandidate.containsAll(setOf(segment0, segment2, segment4, segment6)) } val three = leftSet .filter { it.length == 5 } .map { it.toSortedSet() } .single { threeCandidate -> threeCandidate !in listOf(two, five) } val nine = leftSet .filter { it.length == 6 } .map { it.toSortedSet() } .single { nineCandidate -> (eight - nineCandidate) == setOf(segment4) } val zero = leftSet .filter { it.length == 6 } .map { it.toSortedSet() } .single { zeroCandidate -> zeroCandidate !in listOf(six, nine) } // println("Segment 0: $segment0") // println("Segment 2: $segment2") // println("Segment 4: $segment4") // println("Segment 6: $segment6") // // println("Zero: $zero") // println("One: $one") // println("Two: $two") // println("Three: $three") // println("Four: $four") // println("Five: $five") // println("Six: $six") // println("Seven: $seven") // println("Eight: $eight") // println("Nine: $nine") return mapOf( zero to 0, one to 1, two to 2, three to 3, four to 4, five to 5, six to 6, seven to 7, eight to 8, nine to 9, ) } fun part1(input: List<String>): Int { val result = input.map { line -> line.split("|")[1].split(" ").filter { it.isNotBlank() } } return result.flatten() .count { it.length in listOf(2, 4, 3, 7) } } fun part2(input: List<String>): Int { return input.sumOf { line -> val (left, right) = line.split("|") .map { part -> part.split(" ").filter { it.isNotBlank() } } val mapOfMapping = deductMappingOfNumbers(left) val number = right .joinToString("") { mapOfMapping[it.toSortedSet()].toString() } .toInt() number } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 26) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
3,691
KotlinAdventOfCode
Apache License 2.0
src/main/kotlin/solutions/day15/Day15.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day15 import solutions.Solver import utils.Coordinate import utils.manhattanDistance import kotlin.math.abs data class SensorBeaconPair( val sensor: Coordinate, val beacon: Coordinate, val distance: Int ) fun SensorBeaconPair.distance(): Int = sensor.manhattanDistance(beacon) class Day15(val testInstance: Boolean = false) : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val pairs = input.map { parseSensorBeaconPair(it) } return if (!partTwo) { part1(pairs) } else { return part2(pairs) } } private fun part2(pairs: List<SensorBeaconPair>): String { val bounds = if (testInstance) { 20 } else { 4000000 } val candidates = pairs.flatMap { val cs = mutableListOf<Coordinate>() for (x in ((it.sensor.x - it.distance - 1)..(it.sensor.x + it.distance + 1))) { val yStep = (it.distance + 1) - abs(it.sensor.x - x) val y1 = it.sensor.y + yStep val y2 = it.sensor.y - yStep for (y in listOf(y1, y2)) { val c = Coordinate(x, y) if (c.x in 0..bounds && c.y in 0..bounds && c.manhattanDistance(it.sensor) == (it.distance + 1) ) { cs.add(c) } } } cs } for (c in candidates) { if (pairs.all { c.manhattanDistance(it.sensor) > it.distance }) { return (c.x * 4000000L + c.y).toString() } } throw Error("Not found") } private fun part1(pairs: List<SensorBeaconPair>): String { val rowToCheck = if (testInstance) { 10 } else { 2000000 } val maxRange = pairs.maxBy { it.distance() }.distance() val minX = pairs.flatMap { listOf(it.beacon.x, it.sensor.x) }.min() - maxRange - 10 val maxX = pairs.flatMap { listOf(it.beacon.x, it.sensor.x) }.max() + maxRange + 10 return (minX..maxX).count { x -> val pos = Coordinate(x = x, y = rowToCheck) pairs.any { pos != it.beacon && pos.manhattanDistance(it.sensor) <= it.distance() } }.toString() } private fun parseCoordinateInts(s: String): List<Int> = s.split(",") .map { it.trim() } .map { it.removeRange(0, 2) } .map { it.toInt() } private fun parseSensorBeaconPair(s: String): SensorBeaconPair { val parts = s.split(":") val sensorParts = parseCoordinateInts(parts[0].removePrefix("Sensor at ")) val beaconParts = parseCoordinateInts(parts[1].removePrefix(" closest beacon is at ")) val sensor = Coordinate(x = sensorParts[0], y = sensorParts[1]) val beacon = Coordinate(x = beaconParts[0], y = beaconParts[1]) return SensorBeaconPair(sensor = sensor, beacon = beacon, distance = sensor.manhattanDistance(beacon)) } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
3,104
Advent-of-Code-2022
MIT License
src/day09/Day09.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day09 import readInput fun main() { part1() part2() } data class Pos(var x: Int, var y: Int) fun moveNext(h: Pos, t: Pos) { when { h.x == t.x && h.y - t.y == 2 -> t.y++ h.x == t.x && t.y - h.y == 2 -> t.y-- h.y == t.y && h.x - t.x == 2 -> t.x++ h.y == t.y && t.x - h.x == 2 -> t.x-- (h.y - t.y == 2 && h.x - t.x == 1) || (h.x - t.x == 2 && h.y - t.y == 1) || (h.x - t.x == 2 && h.y - t.y == 2) -> { t.x++; t.y++ } (t.y - h.y == 2 && h.x - t.x == 1) || (h.x - t.x == 2 && t.y - h.y == 1) || (h.x - t.x == 2 && t.y - h.y == 2) -> { t.x++; t.y-- } (t.y - h.y == 2 && t.x - h.x == 1) || (t.x - h.x == 2 && t.y - h.y == 1) || (t.x - h.x == 2 && t.y - h.y == 2) -> { t.x--; t.y-- } (h.y - t.y == 2 && t.x - h.x == 1) || (t.x - h.x == 2 && h.y - t.y == 1) || (t.x - h.x == 2 && h.y - t.y == 2) -> { t.x--; t.y++ } } } fun part1() { val input = readInput(9) val visited = mutableListOf(Pos(0, 0)) val h = Pos(0, 0) val t = Pos(0, 0) for (line in input) { val direction = line.split(" ")[0] val count = line.split(" ")[1].toInt() repeat(count) { when (direction) { "U" -> h.y++ "D" -> h.y-- "L" -> h.x-- "R" -> h.x++ } moveNext(h, t) visited += t.copy() } } println(visited.distinctBy { it.x to it.y }.size) } fun part2() { val input = readInput(9) val visited = mutableListOf(Pos(0, 0)) val snake = List(10) { Pos(0, 0) } for (line in input) { val direction = line.split(" ")[0] val count = line.split(" ")[1].toInt() repeat(count) { when (direction) { "U" -> snake[0].y++ "D" -> snake[0].y-- "L" -> snake[0].x-- "R" -> snake[0].x++ } for (i in 1..snake.lastIndex) { moveNext(snake[i - 1], snake[i]) } visited += snake.last().copy() } } println(visited.distinctBy { it.x to it.y }.size) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
2,322
advent-of-code-2022
Apache License 2.0
src/Day08.kt
kipwoker
572,884,607
false
null
import kotlin.math.max class Tree(val value: Int, var visible: Boolean) fun main() { fun parse(input: List<String>): List<List<Tree>> { return input.map { line -> line.toCharArray().map { Tree(it.digitToInt(), false) } } } fun findVisible(trees: List<List<Tree>>): Int { val size = trees.size val lastIdx = size - 1 for (i in 0..lastIdx) { var maxLeft = -1 var maxRight = -1 for (j in 0..lastIdx) { val cellLeft = trees[i][j] if (cellLeft.value > maxLeft) { cellLeft.visible = true maxLeft = cellLeft.value } val cellRight = trees[i][lastIdx - j] if (cellRight.value > maxRight) { cellRight.visible = true maxRight = cellRight.value } } } for (i in 0..lastIdx) { var maxTop = -1 var maxBottom = -1 for (j in 0..lastIdx) { val cellTop = trees[j][i] if (cellTop.value > maxTop) { cellTop.visible = true maxTop = cellTop.value } val cellBottom = trees[lastIdx - j][i] if (cellBottom.value > maxBottom) { cellBottom.visible = true maxBottom = cellBottom.value } } } return trees.sumOf { x -> x.count { y -> y.visible } } } fun findMax(center: Int, range: IntProgression, getter: (x: Int) -> Tree): Int { var count = 0 for (i in range) { val cell = getter(i) if (cell.value >= center) { return count + 1 } ++count } return count } fun findScenic(trees: List<List<Tree>>): Int { val size = trees.size val lastIdx = size - 1 var maxScenic = -1 for (i in 0..lastIdx) { for (j in 0..lastIdx) { val center = trees[i][j].value val left = findMax(center, j - 1 downTo 0) { x -> trees[i][x] } val right = findMax(center, j + 1..lastIdx) { x -> trees[i][x] } val top = findMax(center, i - 1 downTo 0) { x -> trees[x][j] } val bottom = findMax(center, i + 1..lastIdx) { x -> trees[x][j] } val scenic = top * left * bottom * right maxScenic = max(scenic, maxScenic) } } return maxScenic } fun part1(input: List<String>): Int { val trees = parse(input) return findVisible(trees) } fun part2(input: List<String>): Int { val trees = parse(input) return findScenic(trees) } val testInput = readInput("Day08_test") assert(part1(testInput), 21) assert(part2(testInput), 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8aeea88d1ab3dc4a07b2ff5b071df0715202af2
3,089
aoc2022
Apache License 2.0
src/Day12.kt
RobvanderMost-TomTom
572,005,233
false
{"Kotlin": 47682}
data class Day12Pos( val x: Int, val y: Int, ) { fun up() = Day12Pos(x, y - 1) fun down() = Day12Pos(x, y + 1) fun left() = Day12Pos(x - 1, y) fun right() = Day12Pos(x + 1, y) } data class Hill( val height: Char, var minDistance: Int = Int.MAX_VALUE ) { fun reachableFrom(origin: Hill) = when { (origin.height == 'z' || origin.height == 'y') && height == 'E' -> true height == origin.height -> true height - origin.height == 1 -> true height != 'E' && height != 'S' && height - origin.height < 0 -> true height == 'a' && origin.height == 'S' -> true else -> false } } fun main() { fun List<List<Hill>>.at(pos: Day12Pos) = this[pos.y][pos.x] fun List<List<Hill>>.validPos(pos: Day12Pos) = (pos.x >= 0) && (pos.y >= 0) && (pos.x <= first().lastIndex) && (pos.y <= lastIndex) fun List<List<Hill>>.findPath(origin: Day12Pos, distance: Int = 0): Int? { val newDistance = distance + 1 return listOf(origin.down(), origin.up(), origin.left(), origin.right()) .filter { validPos(it) } .filter { at(it).reachableFrom(at(origin)) } .also { if(it.any { dest -> at(dest).height == 'E'}) { // short circuit return newDistance } } .filter { at(it).minDistance > newDistance } .sortedByDescending { at(it).height } .onEach { at(it).minDistance = newDistance } .mapNotNull { findPath(it, newDistance) } .minOrNull() } fun findStartPos(input: List<String>): Day12Pos { input.forEachIndexed { y, row -> val x = row.indexOf('S') if (x > -1) { return Day12Pos(x, y) } } check(false) return Day12Pos(-1, -1) } fun findStartPositions(input: List<String>) = input.flatMapIndexed { y: Int, row: String -> row.mapIndexedNotNull { x, c -> if (c in "Sa") { Day12Pos(x, y) } else { null } } } fun loadMap(input: List<String>) = input.map { row -> row.map { height -> Hill(height) } } fun part1(input: List<String>): Int? { val hillMap = loadMap(input) val startPos = findStartPos(input) return hillMap.findPath(startPos) } fun part2(input: List<String>): Int? { val hillMap = loadMap(input) return findStartPositions(input) .mapNotNull {startPos -> hillMap.findPath(startPos) } .minOrNull() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(findStartPos(testInput) == Day12Pos(0, 0)) check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") check(findStartPos(input) == Day12Pos(0, 20)) println(part1(input)) println(part2(input)) }
5
Kotlin
0
0
b7143bceddae5744d24590e2fe330f4e4ba6d81c
3,245
advent-of-code-2022
Apache License 2.0
src/day04/Day04.kt
GrinDeN
574,680,300
false
{"Kotlin": 9920}
fun main() { fun part1(input: List<String>): Int { return input .map { it.split(',') } .map { Pair(it[0], it[1]) } .map { Pair( Pair(it.first.split('-')[0], it.first.split('-')[1]), Pair(it.second.split('-')[0], it.second.split('-')[1])) } .map { Pair( IntRange(it.first.first.toInt(), it.first.second.toInt()), IntRange(it.second.first.toInt(), it.second.second.toInt())) } .count {(it.first.contains(it.second.first) && it.first.contains(it.second.last)) || (it.second.contains(it.first.first) && it.second.contains(it.first.last)) } } fun part2(input: List<String>): Int { return input .map { it.split(',') } .map { Pair(it[0], it[1]) } .map { Pair( Pair(it.first.split('-')[0], it.first.split('-')[1]), Pair(it.second.split('-')[0], it.second.split('-')[1])) } .map { Pair( IntRange(it.first.first.toInt(), it.first.second.toInt()), IntRange(it.second.first.toInt(), it.second.second.toInt())) } .count {(it.first.contains(it.second.first) || it.first.contains(it.second.last)) || (it.second.contains(it.first.first) || it.second.contains(it.first.last)) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day04/Day04_test") check(part1(testInput) == 2) val input = readInput("day04/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f25886a7a3112c330f80ec2a3c25a2ff996d8cf8
1,637
aoc-2022
Apache License 2.0
src/day15/day15.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day15 import readInput import kotlin.math.abs private fun parse(input: List<String>): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> { return input.map { it.split(" ", ",", "=", ":") } .map { val startPoint = Pair(it[3].toInt(), it[6].toInt()) val beaconPoint = Pair(it[13].toInt(), it[16].toInt()) Pair(startPoint, beaconPoint) } } private fun solution( input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>, rowIndex: Int ): Pair<HashSet<Int>, HashSet<Int>> { val columns = HashSet<Int>() val itemsInRow = HashSet<Int>() for (item in input) { if (item.first.second == rowIndex) { itemsInRow.add(item.first.first) } else if (item.second.second == rowIndex) { itemsInRow.add(item.second.first) } val distance = abs(item.first.first - item.second.first) + abs(item.first.second - item.second.second) val sourceRowIndex = item.first.second val sourceColIndex = item.first.first val moves = distance - abs(rowIndex - sourceRowIndex) if (moves < 0) continue val startIndex = sourceColIndex - moves val endIndex = sourceColIndex + moves for (index in startIndex..endIndex) { columns.add(index) } } return Pair(columns, itemsInRow) } private fun part1(input: List<String>): Int { val parsedInput = parse(input) val result = solution(parsedInput, 2_000_000) return result.first.size - result.second.size } private fun solution2( input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>, range: IntRange ): Long { var row = 0 var col = 0 while (row <= range.last) { var found = false for (item in input) { val distance = abs(item.first.first - item.second.first) + abs(item.first.second - item.second.second) val sourceRowIndex = item.first.second val sourceColIndex = item.first.first val moves = distance - abs(row - sourceRowIndex) if (moves < 0) continue if (sourceColIndex - moves <= col && sourceColIndex + moves >= col) { col = sourceColIndex + moves + 1 if (col >= range.last + 1) { col = 0 row++ } found = true continue } } if (found.not()) return col.toLong() * MULTIPLIER + row } return Long.MIN_VALUE } private const val MAX_RANGE = 4_000_000 private const val MULTIPLIER = 4_000_000 private fun part2(input: List<String>, scope: IntRange): Long { val parsedInput = parse(input) return solution2(parsedInput, scope) } fun main() { val input = readInput("day15/input") val scope = IntRange(0, MAX_RANGE) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input, scope)}") }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
2,910
aoc-2022
Apache License 2.0
src/Day15.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
import kotlin.math.* fun main() { val inputPattern = "Sensor at x=(.*), y=(.*): closest beacon is at x=(.*), y=(.*)".toRegex() data class Point(val x: Int, val y: Int) infix fun Point.distanceTo(other: Point): Int { // https://en.wikipedia.org/wiki/Taxicab_geometry return abs(x - other.x) + abs(y - other.y) } fun String.toReading(): Pair<Point, Point> { val (sensorX, sensorY, beaconX, beaconY) = inputPattern.matchEntire(this)!!.destructured return Point(sensorX.toInt(), sensorY.toInt()) to Point(beaconX.toInt(), beaconY.toInt()) } fun Pair<Point, Point>.reachableRangeByRow() = sequence { val (sensor, closestBeacon) = this@reachableRangeByRow val taxicabDistance = sensor distanceTo closestBeacon for (offset in taxicabDistance downTo 0) { val width = taxicabDistance - offset val range = sensor.x - width..sensor.x + width yield(sensor.y + offset to range) yield(sensor.y - offset to range) } } fun part1(input: List<String>, measureY: Int): Int { val readings = input.map { it.toReading() } val reachablePoints = readings .asSequence() .flatMap { it.reachableRangeByRow() } .filter { (y, _) -> y == measureY } .flatMap { (y, range) -> range.map { Point(it, y) } } .toSet() val sensorAndBeaconsOnLine = readings.flatMap { listOf(it.first, it.second) }.filter { it.y == measureY }.toSet() return (reachablePoints - sensorAndBeaconsOnLine).size } fun part2(input: List<String>, maximum: Int): Long { val readings = input.map { it.toReading() } val solutionSpace = 0..maximum val blockedAreasByRow = readings .asSequence() .flatMap { it.reachableRangeByRow() } .filter { (y, _) -> y in solutionSpace } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) for ((y, blockedAreas) in blockedAreasByRow.entries) { var solution = solutionSpace.first var hitBlockedArea: Boolean while (solution < solutionSpace.last) { hitBlockedArea = false for (blockedArea in blockedAreas) { if (solution in blockedArea) { solution = blockedArea.last + 1 hitBlockedArea = true break } } if (!hitBlockedArea) { return solution.toLong() * 4_000_000L + y.toLong() } } } error("Distress signal not found") } val testInput = readInput("Day15_test") check(part1(testInput, measureY = 10) == 26) check(part2(testInput, maximum = 20) == 56000011L) val input = readInput("Day15") println(part1(input, measureY = 2_000_000)) println(part2(input, maximum = 4_000_000)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
3,018
advent-of-code-2022
Apache License 2.0
advent-of-code-2023/src/Day05.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import kotlin.math.max import kotlin.math.min private const val DAY = "Day05" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 35 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 46 measureAnswer { part2(input()) } } } private fun part1(almanac: Almanac): Long { return almanac.seeds.minOf { seed -> var result = seed for (mappings in almanac.mappingsLayers) result = mappings.transform(result) result } } private fun List<Mapping>.transform(value: Long) = find { value in it }?.transform(value) ?: value private fun part2(almanac: Almanac): Long { // Initially fill with ranges from input // Pairs: <layer of mapping> to <range> val ranges = ArrayDeque( almanac.seeds.chunked(2) .map { (start, size) -> 0 to (start rangeOfSize size) } ) val lastLayer = almanac.mappingsLayers.lastIndex var minLocation = Long.MAX_VALUE while (ranges.isNotEmpty()) { val (layer, range) = ranges.removeFirst() val mapping = almanac.mappingsLayers[layer].find { range in it } val rangeForNextLayer = if (mapping != null) { val (before, intersection, after) = range intersect mapping.range if (before != null) ranges.addFirst(layer to before) if (after != null) ranges.addFirst(layer to after) mapping.transform(intersection) } else { range } if (layer == lastLayer) { minLocation = min(minLocation, rangeForNextLayer.first) } else { ranges.addLast(layer + 1 to rangeForNextLayer) } } return minLocation } private fun readInput(name: String): Almanac { val almanacInput = readText(name).split("\n\n") fun parseMapping(line: String): Mapping { val (destinationStart, sourceStart, rangeSize) = line.splitLongs() return Mapping( range = sourceStart rangeOfSize rangeSize, offset = destinationStart - sourceStart, ) } return Almanac( seeds = almanacInput.first().substringAfter(": ").splitLongs(), mappingsLayers = almanacInput.drop(1).map { mappingInput -> mappingInput.lineSequence() .drop(1) // Skip mappings layer description .map(::parseMapping) .toList() } ) } private data class Almanac( val seeds: List<Long>, val mappingsLayers: List<List<Mapping>> ) private class Mapping(val range: LongRange, val offset: Long) { operator fun contains(value: Long) = value in range operator fun contains(values: LongRange) = values.first in range || values.last in range fun transform(value: Long) = value + offset fun transform(values: LongRange) = transform(values.first)..transform(values.last) } // region Utils private fun String.splitLongs() = split(" ").map(String::toLong) private infix fun Long.rangeOfSize(size: Long) = this..<(this + size) // Returns: (before?, intersection, after?) private infix fun LongRange.intersect(other: LongRange) = Triple( (first..<max(first, other.first)).takeUnless { it.isEmpty() }, // Before max(first, other.first)..min(last, other.last), // Intersection (min(last, other.last) + 1..last).takeUnless { it.isEmpty() }, // After ) // endregion
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
3,456
advent-of-code
Apache License 2.0
src/main/kotlin/aoc2023/Day03.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import Point import multiplyOf import readInput private data class SchemanticsChar(val point: Point, val char: Char) object Day03 { /** * Reads the complete part number starting from any position within the number * * @param allPoints all possible [SchemanticsChar] in the original input * @param part some character within the part number to find * @return a pair of the complete part number, in which [part] is one digit and its starting position (to avoid duplicates) */ private fun getPartNumber(allPoints: List<SchemanticsChar>, part: SchemanticsChar): Pair<Point, Int> { var partNumber = part.char.toString() var startPosition = part.point // move right var nextPoint = part.point while (true) { nextPoint = nextPoint.move(1, 0) val nextPart = allPoints.find { it.point == nextPoint } if (nextPart != null && nextPart.char.isDigit()) { partNumber += nextPart.char } else { break } } // move left nextPoint = part.point while (true) { nextPoint = nextPoint.move(-1, 0) val nextPart = allPoints.find { it.point == nextPoint } if (nextPart != null && nextPart.char.isDigit()) { partNumber = nextPart.char + partNumber startPosition = nextPoint } else { break } } return Pair(startPosition, partNumber.toInt()) } private fun parseInput(input: List<String>) = input.withIndex() .flatMap { indexLine -> val y = indexLine.index val line = indexLine.value line.withIndex().map { indexChar -> SchemanticsChar(Point(indexChar.index, y), indexChar.value) } } fun part1(input: List<String>): Int { val allPoints = parseInput(input) val validGrid = Pair(Point(0, 0), Point(input[0].length, input.size)) return allPoints.filter { it.char != '.' && !it.char.isDigit() } .flatMap { symbol -> symbol.point.getNeighbours(withDiagonal = true, validGrid) .mapNotNull { neighbour -> allPoints.find { it.point == neighbour } } .filter { it.char.isDigit() } .map { getPartNumber(allPoints, it) } .toSet() // eliminate duplicates }.sumOf { it.second } } fun part2(input: List<String>): Int { val allPoints = parseInput(input) val validGrid = Pair(Point(0, 0), Point(input[0].length, input.size)) return allPoints.filter { it.char == '*' } .sumOf { gear -> val neighbourParts = gear.point.getNeighbours(withDiagonal = true, validGrid) .mapNotNull { neighbour -> allPoints.find { it.point == neighbour } } .filter { it.char.isDigit() } .map { getPartNumber(allPoints, it) } .toSet() if (neighbourParts.size >= 2) { neighbourParts.multiplyOf { it.second } } else { 0 } } } } fun main() { val testInput = readInput("Day03_test", 2023) check(Day03.part1(testInput) == 4361) check(Day03.part2(testInput) == 467835) val input = readInput("Day03", 2023) println(Day03.part1(input)) println(Day03.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,543
adventOfCode
Apache License 2.0
src/day12/Day12.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day12 import Direction import Position import readInput import set import get fun main() { fun parseInput(input: List<String>): List<List<Char>> { return input.map { line -> line.chunked(1).map { when (val char = it.toCharArray().first()) { 'S' -> 'a' 'E' -> 'z' else -> char } } } } fun findPositions(map: List<String>): Pair<Position, Position> { var startPos = Position(0, 0) var endPos = Position(0, 0) map.forEachIndexed { y, line -> line.forEachIndexed { x, pos -> if (pos == 'S') { startPos = Position(x, y) } else if (pos == 'E') { endPos = Position(x, y) } } } return (startPos to endPos) } fun part1(input: List<String>): Int { val (startPos, endPos) = findPositions(input) val map = parseInput(input) return map.findRoute(startPos, endPos) } fun part2(input: List<String>): Int { val (_, endPos) = findPositions(input) val map = parseInput(input) return map.mapIndexed { y, line -> line.mapIndexed { x, c -> c to Position(x, y) } }.flatten() .filter { it.first == 'a' } .map { it.second }.minOf { p -> map.findRoute(p, endPos) } } // test if implementation meets criteria from the description, like: val testInput = readInput("day12/Day12_test") println(part1(testInput)) check(part1(testInput) == 31) val input = readInput("day12/Day12") println(part1(input)) println(part2(input)) } private fun List<List<Char>>.findRoute(startPos: Position, endPos: Position): Int { val heatMap = List(this.size) { MutableList(this.first().size) { 0 } } var heads = ArrayDeque(listOf(startPos)) heatMap[startPos] = 1 while (heads.isNotEmpty()) { heads.removeFirst().let { pos -> checkWhereToStep(pos, this, heatMap).forEach { direction -> val newPos = pos.newPosition(direction) if (newPos == endPos) { return heatMap[pos] } heads.add(newPos) heatMap[newPos] = heatMap[pos] + 1 } } } return Int.MAX_VALUE } fun checkWhereToStep(pos: Position, map: List<List<Char>>, heatMap: List<List<Int>>): List<Direction> = Direction.values().filter { dir -> val newPos = pos.newPosition(dir) when (dir) { Direction.U -> pos.y != 0 Direction.D -> pos.y != map.size - 1 Direction.L -> pos.x != 0 Direction.R -> pos.x != map.first().size - 1 } && (checkStep(map[pos], map[newPos])) && heatMap[newPos] == 0 }.toList() private fun checkStep(start: Char, end: Char): Boolean = start >= (end - 1)
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
3,031
advent-of-code-kotlin-2022
Apache License 2.0
src/year2021/Day8.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = parseInput(readLines("2021", "day8")) val smallTestInput = parseInput(readLines("2021", "day8_test_small")) val bigTestInput = parseInput(readLines("2021", "day8_test_big")) check(part1(bigTestInput) == 26) println("Part 1:" + part1(input)) check(part2(smallTestInput) == 5353) println("Part 2:" + part2(input)) } private fun parseInput(lines: List<String>) = lines.map { it.replace(" | ", " ").split(" ").map { it.split("").sorted().joinToString("") } } private fun part1(input: List<List<String>>): Int { return input .map { it.slice((10..13)).map { it.length }.filter { listOf(2, 4, 3, 7).contains(it) } } .flatten() .size } private fun part2(input: List<List<String>>): Int { return input.sumOf { decodeOneInputLine(it.slice((0..9)), it.slice((10..13))) } } private fun decodeOneInputLine( uniqueSignals: List<String>, output: List<String>, ): Int { for (a in 1..7) { for (b in 1..7) { if (b == a) continue for (c in 1..7) { if (c == a || c == b) continue for (d in 1..7) { if (d == a || d == b || d == c) continue for (e in 1..7) { if (e == a || e == b || e == c || e == d) continue for (f in 1..7) { if (f == a || f == b || f == c || f == d || f == e) continue val g = 28 - (a + b + c + d + e + f) val translationMapping = hashMapOf("a" to a, "b" to b, "c" to c, "d" to d, "e" to e, "f" to f, "g" to g) val resultOfMapping = uniqueSignals .map { signal -> toDisplay(signal, translationMapping) } .toSet() if (resultOfMapping == allDisplays) { return output .map { signal -> toDisplay(signal, translationMapping) } .map { display -> displayToIntMapping[display]!! } .joinToString("") .toInt() } } } } } } } throw IllegalStateException("Could not solve $uniqueSignals, $output") } private fun toDisplay( signal: String, mapping: HashMap<String, Int>, ) = signal.split("").filter { it != "" }.map { mapping[it]!! }.toSet() private val zero: Display = setOf(1, 2, 3, 5, 6, 7) private val one: Display = setOf(3, 6) private val two: Display = setOf(1, 3, 4, 5, 7) private val three: Display = setOf(1, 3, 4, 6, 7) private val four: Display = setOf(2, 3, 4, 6) private val five: Display = setOf(1, 2, 4, 6, 7) private val six: Display = setOf(1, 2, 4, 5, 6, 7) private val seven: Display = setOf(1, 3, 6) private val eight: Display = setOf(1, 2, 3, 4, 5, 6, 7) private val nine: Display = setOf(1, 2, 3, 4, 6, 7) private val allDisplays = setOf(zero, one, two, three, four, five, six, seven, eight, nine) private val displayToIntMapping = hashMapOf(zero to 0, one to 1, two to 2, three to 3, four to 4, five to 5, six to 6, seven to 7, eight to 8, nine to 9) typealias Display = Set<Int>
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
3,435
advent_of_code
MIT License
advent-of-code-2023/src/Day15.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import LensOperation.Put import LensOperation.Remove import java.util.* private const val DAY = "Day15" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 1320 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 145 measureAnswer { part2(input()) } } } private fun part1(input: List<String>): Int = input.sumOf(::hash) private fun part2(input: List<String>): Int { val hashMap = LensesHashMap() for (operation in input.parseOperations()) { when (operation) { is Put -> hashMap.put(operation.lens) is Remove -> hashMap.remove(operation.label) } } return hashMap.focusingPower() } private fun hash(value: String): Int = value.fold(initial = 0) { currentValue, char -> (currentValue + char.code) * 17 % 256 } private fun readInput(name: String) = readText(name).split(",") private fun List<String>.parseOperations() = map { instruction -> if ('=' in instruction) { val (label, focalLength) = instruction.split("=") Put(Lens(label, focalLength.toInt())) } else { Remove(label = instruction.dropLast(1)) } } private class LensesHashMap { private val boxes = List<MutableList<Lens>>(256) { LinkedList() } fun put(lens: Lens) { val box = findBox(lens.label) val index = box.indexOfFirst { it.label == lens.label } if (index == -1) { box += lens } else { box[index] = lens } } fun remove(label: String) { findBox(label).removeIf { it.label == label } } private fun findBox(label: String) = boxes[hash(label)] fun focusingPower(): Int = boxes.withIndex().sumOf { (i, box) -> box.focusingPower(i) } private fun List<Lens>.focusingPower(boxNumber: Int): Int { return withIndex().sumOf { (slotNumber, lens) -> (boxNumber + 1) * (slotNumber + 1) * lens.focalLength } } } private data class Lens(val label: String, val focalLength: Int) private sealed interface LensOperation { data class Remove(val label: String) : LensOperation data class Put(val lens: Lens) : LensOperation }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,255
advent-of-code
Apache License 2.0
src/Day08.kt
rdbatch02
575,174,840
false
{"Kotlin": 18925}
fun <T : Comparable<T>> Iterable<T>.maxOrDefault(default: T): T = this.maxOrNull() ?: default public inline fun <T> List<T>.indexOfFirstOrSize(predicate: (T) -> Boolean): Int { val firstIndex = this.indexOfFirst(predicate) return if (firstIndex > -1) firstIndex else this.size } fun main() { fun parseMap(input: List<String>): List<List<Int>> { return input.map { line -> line.map { it.digitToInt() } } } fun checkIsVisible(input: List<List<Int>>, row: Int, col: Int): Boolean { val treeHeight = input[row][col] val treeColumn = input.map { it[col] } val treeRow = input[row] if ((treeColumn.subList(0, row).maxOrNull() ?: -1) < treeHeight) { // Check North return true } if ((treeColumn.subList(row + 1, treeColumn.size).maxOrNull() ?: -1) < treeHeight) { // Check South return true } if ((treeRow.subList(0, col).maxOrNull() ?: -1) < treeHeight) { // Check West return true } if ((treeRow.subList(col + 1, treeRow.size).maxOrNull() ?: -1) < treeHeight) { // Check East return true } return false } fun calculateRangeScore (range: List<Int>, treeHeight: Int): Int { return when (val rangeStop = range.indexOfFirst { it >= treeHeight }) { 0 -> { // Top row 0 } -1 -> { // Nothing bigger to the north range.size } else -> { range.subList(0, rangeStop + 1).size } } } fun calculateScenicScore(input: List<List<Int>>, row: Int, col: Int): Int { val treeHeight = input[row][col] val treeColumn = input.map { it[col] } val treeRow = input[row] // Reverse North and West so that list[0] is right next to the tree in question val northOfTree = treeColumn.subList(0, row).reversed() val southOfTree = treeColumn.subList(row + 1, treeColumn.size) val westOfTree = treeRow.subList(0, col).reversed() val eastOfTree = treeRow.subList(col + 1, treeRow.size) val northScore = calculateRangeScore(northOfTree, treeHeight) val southScore = calculateRangeScore(southOfTree, treeHeight) val westScore = calculateRangeScore(westOfTree, treeHeight) val eastScore = calculateRangeScore(eastOfTree, treeHeight) return northScore * southScore * westScore * eastScore } fun part1(input: List<String>): Int { val map = parseMap(input) var visibleTrees = 0 for (rowIdx in map.indices) { val row = map[rowIdx] for (colIdx in row.indices) { if (checkIsVisible(map, rowIdx, colIdx)) { visibleTrees++ } } } return visibleTrees } fun part2(input: List<String>): Int { val map = parseMap(input) val scores = mutableListOf<Int>() for (rowIdx in map.indices) { val row = map[rowIdx] for (colIdx in row.indices) { scores.add(calculateScenicScore(map, rowIdx, colIdx)) } } return scores.max() } val input = readInput("Day08") println("Part 1 - " + part1(input)) println("Part 2 - " + part2(input)) }
0
Kotlin
0
1
330a112806536910bafe6b7083aa5de50165f017
3,375
advent-of-code-kt-22
Apache License 2.0
src/main/kotlin/day18.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* fun main() { val input = Input.day(18) println(day18A(input)) println(day18B(input)) } fun day18A(input: Input): Long { var on = Point(0, 0) val vectors = input.lines.map { line -> val (direction, meters) = line.split(' ') when(direction) { "R" -> Vector(on, Point(on.x + meters.toInt(), on.y)) "D" -> Vector(on, Point(on.x, on.y + meters.toInt())) "L" -> Vector(on, Point(on.x - meters.toInt(), on.y)) "U" -> Vector(on, Point(on.x, on.y - meters.toInt())) else -> throw Exception() }.also { on = it.b } } return lagoonSize(vectors) } fun day18B(input: Input): Long { var on = Point(0, 0) val vectors = input.lines.map { line -> val hexa = Regex("""\(#((\w|\d)+)\)""").find(line)!!.groupValues[1] val meters = hexa.dropLast(1).toInt(radix = 16) when(hexa.last()) { '0' -> Vector(on, Point(on.x + meters, on.y)) '1' -> Vector(on, Point(on.x, on.y + meters)) '2' -> Vector(on, Point(on.x - meters, on.y)) '3' -> Vector(on, Point(on.x, on.y - meters)) else -> throw Exception() }.also { on = it.b } } return lagoonSize(vectors) } private class Vector(val a: Point, val b: Point) private fun lagoonSize(vectors: List<Vector>): Long { var sum = 0L for(y in vectors.minOf { minOf(it.a.y, it.b.y) } .. vectors.maxOf { maxOf(it.a.y, it.b.y) }) { val wallsForRow = vectors.filter { it.a.y != it.b.y && y >= minOf(it.a.y, it.b.y) && y <= maxOf(it.a.y, it.b.y) }.sortedBy { it.a.x } val digged = wallsForRow.zipWithNext { a, b -> val aDirUp = a.a.y > a.b.y val bDirUp = b.a.y > b.b.y val isHorizontallyConnected = vectors.any { it.a.y == y && ((it.a.x == a.a.x && it.b.x == b.a.x) || (it.b.x == a.a.x && it.a.x == b.a.x)) } if((aDirUp && !bDirUp) || isHorizontallyConnected) { a.a.x to b.a.x } else { null } }.filterNotNull() sum += digged.sumOf { (it.second - it.first) + 1 } - digged.count { a -> digged.any { b -> a.first == b.second } } } return sum }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,402
AdventOfCode2023
MIT License
src/main/kotlin/aoc23/Day01.kt
asmundh
573,096,020
false
{"Kotlin": 56155}
package aoc23 import runTask import utils.InputReader fun day1part1(input: List<String>): Int { return input.sumOf { val d1 = it.first { it.isDigit() }.digitToInt() val d2 = it.last { it.isDigit() }.digitToInt() "$d1$d2".toInt() } } fun day1part2(input: List<String>): Int { return input.sumOf { val first: Int = findFirstDigitInString(it) val second: Int = findFirstDigitInString(it.reversed(), true) "${first}$second".toInt() } } fun findFirstDigitInString(input: String, isReversed: Boolean = false): Int { val candidates: MutableMap<Int, Int> = mutableMapOf() val firstIntDigit = input.map { it }.indexOfFirst { it.isDigit() } if (firstIntDigit != -1) candidates[firstIntDigit] = input[firstIntDigit].digitToInt() if (input.length >= 3) { val window = input.windowed(3, 1).map { if (isReversed) it.reversed() else it } val firstThreeIndex = window.indexOfFirst { getDigit(it) != -1 } if (firstThreeIndex != -1) candidates[firstThreeIndex] = getDigit(window[firstThreeIndex]) } if (input.length >= 4) { val window = input.windowed(4, 1).map { if (isReversed) it.reversed() else it } val firstFourIndex = input.windowed(4, 1).map { if (isReversed) it.reversed() else it }.indexOfFirst { getDigit(it) != -1 } if (firstFourIndex != -1) candidates[firstFourIndex] = getDigit(window[firstFourIndex]) } if (input.length >= 5) { val window = input.windowed(5, 1).map { if (isReversed) it.reversed() else it } val firstFiveIndex = input.windowed(5, 1).map { if (isReversed) it.reversed() else it }.indexOfFirst { getDigit(it) != -1 } if (firstFiveIndex != -1)candidates[firstFiveIndex] = getDigit(window[firstFiveIndex]) } return candidates[candidates.keys.min()]!! } fun getDigit(input: String): Int { val letters3 = mapOf("one" to 1, "two" to 2, "six" to 6) val letters4 = mapOf("four" to 4, "five" to 5, "nine" to 9) val letters5 = mapOf("three" to 3, "seven" to 7, "eight" to 8) return when (input.length) { 1 -> if (input.first().isDigit()) input.first().digitToInt() else -1 3 -> letters3[input] ?: -1 4 -> letters4[input] ?: -1 5 -> letters5[input] ?: -1 else -> -1 } } fun main() { val input: List<String> = InputReader.getInputAsList(1) runTask("D1p1") { day1part1(input) } runTask("D1p2") { day1part2(input) } }
0
Kotlin
0
0
7d0803d9b1d6b92212ee4cecb7b824514f597d09
2,471
advent-of-code
Apache License 2.0
src/main/kotlin/com/nibado/projects/advent/y2017/Day07.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.resourceLines val regex = Regex("([a-z]{4,8}) \\(([0-9]+)\\)( -> ([a-z ,]+))?") object Day07 : Day { val tree: Tree by lazy { parseTree(resourceLines(2017, 7)) } override fun part1() = tree.name override fun part2() = walk(tree).toString() } fun walk(tree: Tree): Int { if (!tree.balanced()) { val result = tree.children().map { walk(it) }.maxOrNull() if (tree.children().map { it.balanced() }.count { it } == tree.children().size) { val groups = tree.children().groupBy { it.sum() } val wrongTree = groups.values.first { it.size == 1 }.first() val correctTree = groups.values.first { it.size > 1 }.first() return wrongTree.weight - (wrongTree.sum() - correctTree.sum()) } return result!! } return Int.MIN_VALUE } fun parseTree(lines: List<String>): Tree { val input = lines.map { parse(it) }.toList() val programs = input.map { it.name to Tree(it.name, it.weight, null) }.toMap() input.flatMap { a -> a.programs.map { p -> Pair(a.name, p) } }.forEach { programs[it.first]!!.nodes[it.second] = programs[it.second]!! programs[it.second]!!.parent = programs[it.first]!! } return programs.values.filter { it.parent == null }.first() } fun parse(line: String): ProgramOutput { val result = regex.matchEntire(line)!! val name = result.groups.get(1)!!.value val weight = result.groups.get(2)!!.value.toInt() val programs = if (result.groups.get(4) == null) listOf() else result.groups.get(4)!!.value.split(", ").toList() return ProgramOutput(name, weight, programs) } data class ProgramOutput(val name: String, val weight: Int, val programs: List<String>) data class Tree(val name: String, val weight: Int, var parent: Tree?) { val nodes: MutableMap<String, Tree> = mutableMapOf() fun children() = nodes.values fun sum(): Int = weight + nodes.values.map { it.sum() }.sum() fun balanced() = nodes.values.map { it.sum() }.toSet().size == 1 }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
2,139
adventofcode
MIT License
src/Day08.kt
wujingwe
574,096,169
false
null
object Day08 { private val DIRS = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) fun part1(inputs: List<String>): Int { val forest = inputs .withIndex() .flatMap { (row, line) -> line.withIndex().map { (col, value) -> (row to col) to value - '0'} } .toMap() return forest.map { (pos, sourceValue) -> DIRS.map { (dx, dy) -> val (startRow, startCol) = pos val sequence = generateSequence(startRow to startCol) { (row, col) -> val nextRow = row + dx val nexCol = col + dy if (nextRow in inputs.indices && nexCol in inputs[0].indices) { nextRow to nexCol } else { null } } sequence .drop(1) .firstOrNull { forest.getValue(it) >= sourceValue } }.any { it == null } // reach the edge }.count { it } } fun part2(inputs: List<String>): Int { val forest = inputs .withIndex() .flatMap { (row, line) -> line.withIndex().map { (col, value) -> (row to col) to value - '0'} } .toMap() return forest.map { (pos, sourceValue) -> DIRS.map { (dx, dy) -> val (startRow, startCol) = pos val sequence = generateSequence(startRow to startCol) { (row, col) -> val nextRow = row + dx val nexCol = col + dy if (nextRow in inputs.indices && nexCol in inputs[0].indices) { nextRow to nexCol } else { null } } sequence .withIndex() .drop(1) .firstOrNull { (_, value) -> forest.getValue(value) >= sourceValue } ?.index ?: (sequence.count() - 1) }.fold(1) { acc, elem -> acc * elem } }.max() } } fun main() { fun part1(inputs: List<String>): Int { return Day08.part1(inputs) } fun part2(inputs: List<String>): Int { return Day08.part2(inputs) } val testInput = readInput("../data/Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("../data/Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
2,578
advent-of-code-kotlin-2022
Apache License 2.0
src/Day03.kt
stevefranchak
573,628,312
false
{"Kotlin": 34220}
class RucksacksAnalyzer { companion object { private const val CODE_PRIOR_TO_LOWERCASE_A = 96 private const val CODE_PRIOR_TO_UPPERCASE_A = 64 private const val ENGLISH_ALPHABET_LENGTH = 26 private const val ELVES_PER_GROUP = 3 fun sumPrioritiesOfCommonItems(input: List<String>) = input.asSequence() .filter { it.isNotBlank() } .map { Rucksack(it).getCommonElementsInComponents() } .flatten() .map { it.toPriority() } .sum() fun sumPrioritiesOfGroupBadges(input: List<String>) = input.asSequence() .filter { it.isNotBlank() } .map { Rucksack(it).allUniqueItems } .chunked(ELVES_PER_GROUP) .map { it.reduce(Set<Char>::intersect) } .flatten() .map { it.toPriority() } .sum() private fun Char.toPriority() = if (this.isLowerCase()) { this.code - CODE_PRIOR_TO_LOWERCASE_A } else { this.code - CODE_PRIOR_TO_UPPERCASE_A + ENGLISH_ALPHABET_LENGTH } } } class Rucksack(items: String) { private val componentOne: Set<Char> private val componentTwo: Set<Char> val allUniqueItems get() = componentOne.plus(componentTwo) init { items.chunked(items.length / 2).also { componentOne = it[0].toSet() componentTwo = it[1].toSet() } } fun getCommonElementsInComponents() = componentOne.intersect(componentTwo) } fun main() { fun part1(input: List<String>) = RucksacksAnalyzer.sumPrioritiesOfCommonItems(input) fun part2(input: List<String>) = RucksacksAnalyzer.sumPrioritiesOfGroupBadges(input) // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") val part1TestOutput = part1(testInput) val part1ExpectedOutput = 157 check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" } val part2TestOutput = part2(testInput) val part2ExpectedOutput = 70 check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
22a0b0544773a6c84285d381d6c21b4b1efe6b8d
2,371
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day15.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
import kotlin.math.abs typealias Coordinates = Pair<Int, Int> fun main() { fun Coordinates.distance(other: Coordinates) = abs(other.first - first) + abs(other.second - second) data class SensorResult(val sensor: Coordinates, val beacon: Coordinates) { val distance = sensor.distance(beacon) } val inputPattern = """Sensor at x=(?<sensorX>-?\d++), y=(?<sensorY>-?\d++): closest beacon is at x=(?<beaconX>-?\d++), y=(?<beaconY>-?\d++)""".toPattern() fun parseSensorResults(input: List<String>) = input .map { val matcher = inputPattern.matcher(it) check(matcher.matches()) SensorResult( Coordinates( matcher.group("sensorX").toInt(), matcher.group("sensorY").toInt() ), Coordinates( matcher.group("beaconX").toInt(), matcher.group("beaconY").toInt() ) ) } fun part1(input: List<String>, rowToInvestigate: Int): Int { val sensorResults = parseSensorResults(input) val minX = sensorResults.minOf { it.sensor.first - it.distance } val maxX = sensorResults.maxOf { it.sensor.first + it.distance } return (minX..maxX).count { x -> val coordinates = Coordinates(x, rowToInvestigate) sensorResults.none { (it.sensor == coordinates) || (it.beacon == coordinates) } && sensorResults.any { it.sensor.distance(coordinates) <= it.distance } } } fun part2(input: List<String>, maxCoordinate: Int): Long { val sensorResults = parseSensorResults(input) return sensorResults .asSequence() .flatMap { sensorResult -> val candidateDistance = sensorResult.distance + 1 (0..candidateDistance) .asSequence() .associateWith { candidateDistance - it } .flatMap { val sensorX = sensorResult.sensor.first val sensorY = sensorResult.sensor.second sequenceOf( Coordinates(sensorX + it.key, sensorY + it.value), Coordinates(sensorX + it.key, sensorY + -it.value), Coordinates(sensorX + -it.key, sensorY + it.value), Coordinates(sensorX + -it.key, sensorY + -it.value) ) } } .filter { sequenceOf(it.first, it.second).all { coordinate -> coordinate in 0..maxCoordinate } } .find { coordinates -> sensorResults.none { it.sensor.distance(coordinates) <= it.distance } }!! .let { (it.first * 4_000_000L) + it.second } } val testInput = readStrings("Day15_test") check(part1(testInput, rowToInvestigate = 10) == 26) val input = readStrings("Day15") println(part1(input, rowToInvestigate = 2_000_000)) check(part2(testInput, maxCoordinate = 20) == 56_000_011L) println(part2(input, maxCoordinate = 4_000_000)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
3,253
aoc-2022
Apache License 2.0
src/main/kotlin/day2/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day2 import day2.Hand.* import day2.RoundResult.* import util.readTestInput enum class Hand(val points: Int, val symbols: List<String>) { ROCK(1, listOf("X", "A")), PAPER(2, listOf("Y", "B")), SCISSORS(3, listOf("Z", "C")); companion object { fun ofSymbol(symbol: String): Hand { return values().findLast { hand -> hand.symbols.contains(symbol) }!! } } } data class Round(val opponentHand: Hand, val myHand: Hand) enum class RoundResult(val points: Int, val symbol: String) { LOSE(0, "X"), DRAW(3, "Y"), WIN(6, "Z") } val possibleRoundResults = mapOf( mapOf(ROCK to PAPER) to LOSE, mapOf(ROCK to SCISSORS) to WIN, mapOf(PAPER to ROCK) to WIN, mapOf(PAPER to SCISSORS) to LOSE, mapOf(SCISSORS to ROCK) to LOSE, mapOf(SCISSORS to PAPER) to WIN ) fun calculatePoints(round: Round): Int { val result = possibleRoundResults.getOrDefault(mapOf(round.myHand to round.opponentHand), DRAW) return round.myHand.points + result.points } fun part1(inputLines: List<String>): Int { return inputLines .map { it.split(" ").let { (h1, h2) -> Round(Hand.ofSymbol(h1), Hand.ofSymbol(h2)) } } .map { round -> calculatePoints(round) } .sum() } fun resolveExpectedHand(opponentSymbol: String, expectedResultSymbol: String): Round { val opponentHand = Hand.ofSymbol(opponentSymbol) val expectedResult = RoundResult.values().findLast { r -> r.symbol == expectedResultSymbol } val expectedHand = when { (expectedResult == WIN && opponentHand == ROCK) -> PAPER (expectedResult == WIN && opponentHand == PAPER) -> SCISSORS (expectedResult == WIN && opponentHand == SCISSORS) -> ROCK (expectedResult == LOSE && opponentHand == ROCK) -> SCISSORS (expectedResult == LOSE && opponentHand == PAPER) -> ROCK (expectedResult == LOSE && opponentHand == SCISSORS) -> PAPER else -> opponentHand } return Round(opponentHand, expectedHand) } fun part2(inputLines: List<String>): Int { return inputLines .map { it.split(" ").let { (opponentSymbol, expectedResultSymbol) -> resolveExpectedHand(opponentSymbol, expectedResultSymbol) } } .map { round -> calculatePoints(round) } .sum() } fun main() { val inputLines = readTestInput("day2") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
2,432
advent-of-code-2022
MIT License
src/Day12.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
import java.util.* fun main() { class Node( val name: String, val edges: MutableSet<Node> = TreeSet(compareBy { it.name }) ) { val isSmallCave get() = name.first().isLowerCase() && name != "start" && name != "end" val isBigCave get() = name.first().isUpperCase() override fun toString() = name fun getPathsTo(end: Node, visited: MutableMap<Node, Int>, allowSmallTwice: Boolean = false): Int { if (this == end) return 1 if (!isBigCave) visited.compute(this) { _, v -> (v ?: 0) + 1 } val paths = edges .filter { it.canBeVisited(visited, allowSmallTwice) } .sumOf { it.getPathsTo(end, visited, allowSmallTwice) } if (!isBigCave) visited.compute(this) { _, v -> (v ?: 0) - 1 } return paths } private fun canBeVisited(visited: MutableMap<Node, Int>, allowSmallTwice: Boolean): Boolean { if (isBigCave) return true val visitCount = visited.getOrElse(this) { 0 } if (visitCount == 0) return true return allowSmallTwice && isSmallCave && visited.none { it.value == 2 } } } fun parse(input: List<String>): Pair<Node, Node> { val nodes = mutableMapOf<String, Node>() for (line in input) { val (from, to) = line.split("-").map { nodes.getOrPut(it) { Node(it) } } from.edges += to to.edges += from } return nodes.getValue("start") to nodes.getValue("end") } fun part1(input: List<String>): Int { val (start, end) = parse(input) return start.getPathsTo(end, mutableMapOf()) } fun part2(input: List<String>): Int { val (start, end) = parse(input) return start.getPathsTo(end, mutableMapOf(), true) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 10) check(part2(testInput) == 36) val testInput2 = readInput("Day12_test2") check(part1(testInput2) == 19) check(part2(testInput2) == 103) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
2,246
AdventOfCode2021
Apache License 2.0
src/main/kotlin/com/oocode/Bag.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun powerOf(input: String) = input.split("\n").sumOf { line -> gameFrom(line).power() } data class Bag(val red: Int, val green: Int, val blue: Int) { fun possibilityTotal(input: String) = input.split("\n").sumOf { line -> line.possibilityValue(this) } fun power() = red * green * blue } private fun String.possibilityValue(bag: Bag) = gameFrom(this).possibilityValue(bag) data class Game(val number: Int, val reveals: Set<Reveal>) { fun possibilityValue(bag: Bag) = if (reveals.all { it.isPossibleGiven(bag) }) number else 0 fun minimumBag() = reveals.maxBag() fun power() = minimumBag().power() } private fun Set<Reveal>.maxBag() = Bag(red = maxRed(), green = maxGreen(), blue = maxBlue()) private fun Set<Reveal>.maxRed() = maxOf { it.red } private fun Set<Reveal>.maxGreen() = maxOf { it.green } private fun Set<Reveal>.maxBlue() = maxOf { it.blue } data class Reveal(val red: Int = 0, val green: Int = 0, val blue: Int = 0) { fun isPossibleGiven(bag: Bag) = red <= bag.red && green <= bag.green && blue <= bag.blue } // "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green" fun gameFrom(line: String): Game { val number = line.split(":")[0].split(" ")[1].toInt() val revealStrings = line.split(":")[1].split(";") return Game(number, revealStrings.map { revealFrom(it) }.toSet()) } fun revealFrom(revealString: String): Reveal { val colorNumberPairs = revealString.split(",").associate { asColorNumberPair(it.trim()) } return Reveal( red = colorNumberPairs["red"] ?: 0, green = colorNumberPairs["green"] ?: 0, blue = colorNumberPairs["blue"] ?: 0, ) } fun asColorNumberPair(colorNumberPairString: String): Pair<String, Int> = colorNumberPairString.split(" ")[1] to colorNumberPairString.split(" ")[0].toInt()
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
1,832
advent-of-code-2023
MIT License
src/year2023/Day5.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2023 import readLines fun main() { check(LongRange(98, 99).fastIntersect(LongRange(10, 200)).toList() == listOf(98L, 99L)) check(LongRange(98, 99).fastIntersect(LongRange(100, 200)).isEmpty()) check(LongRange(10, 20).fastIntersect(LongRange(15, 22)).toList() == listOf<Long>(15, 16, 17, 18, 19, 20)) check(LongRange(10, 20).fastIntersect(LongRange(7, 16)).toList() == listOf<Long>(10, 11, 12, 13, 14, 15, 16)) check(toLongRange(98, 2).addValue(-48).toList() == listOf<Long>(50, 51)) val input = parseInput(readLines("2023", "day5")) val testInput = parseInput(readLines("2023", "day5_test")) val part1Result = part1(testInput) check(part1Result == 35L) { "Part 1 test case failed with result = $part1Result" } println("Part 1:" + part1(input)) val part2Result = part2(testInput) check(part2Result == 46L) { "Part 2 test case failed with result = $part2Result" } println("Part 2:" + part2(input)) } private fun parseInput(input: List<String>): Pair<List<Long>, List<Mapping>> { val seeds = input[0].dropWhile { !it.isDigit() }.split(" ").map { it.toLong() } val maps = mutableListOf<Mapping>() var input = input.drop(2) while (input.isNotEmpty()) { val mapLength = input.drop(1).takeWhile { it != "" }.size val mapInput = input.drop(1).take(mapLength).map { row -> row.split(" ").map { it.toLong() } } val mappings = mapInput.map { triple -> val destinationRangeStart = triple[0] val sourceRangeStart = triple[1] val rangeLength = triple[2] SingleMapping(toLongRange(sourceRangeStart, rangeLength), destinationRangeStart - sourceRangeStart) } maps.add(Mapping(mappings)) input = input.drop(mapLength + 2) } return Pair(seeds, maps.toList()) } private fun part1(input: Pair<List<Long>, List<Mapping>>): Long { var (seeds, maps) = input for (map in maps) { seeds = seeds.map { seed -> val shiftingValue = map.singleMappings.firstOrNull { singleMapping -> singleMapping.range.contains(seed) }?.value ?: 0 seed + shiftingValue } } return seeds.min() } private fun part2(input: Pair<List<Long>, List<Mapping>>): Long { val (rawSeeds, maps) = input var seedRanges: List<LongRange> = rawSeeds.mapIndexed { index, long -> Pair(index, long) }.groupBy { it.first / 2 }.map { entry -> val numberPair = entry.value.map { it.second } toLongRange(numberPair[0], numberPair[1]) } for (map in maps) { seedRanges = seedRanges.map { seedRange -> val newRangesWithMappingIntersections = map.singleMappings.map { singleMapping -> singleMapping.range.fastIntersect(seedRange).addValue(singleMapping.value) } // val newRangeWithoutAnyIntersection = map.singleMappings.map { singleMapping -> singleMapping.range. } newRangesWithMappingIntersections }.flatten().filter { !it.isEmpty() } } return 0L } private fun LongRange.addValue(value: Long) = LongRange(start + value, endInclusive + value) private fun LongRange.fastIntersect(other: LongRange): LongRange { return LongRange(this.first.coerceAtLeast(other.first), this.last.coerceAtMost(other.last)) } private fun toLongRange( start: Long, length: Long, ) = LongRange(start, start + length - 1) private data class Mapping(val singleMappings: List<SingleMapping>) private data class SingleMapping(val range: LongRange, val value: Long)
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
3,721
advent_of_code
MIT License
src/Day15.kt
l8nite
573,298,097
false
{"Kotlin": 105683}
import kotlin.math.abs import kotlin.math.max class MutableIntRange(var first: Int, var last: Int) fun List<IntRange>.combine(): List<IntRange> { val result = mutableListOf<IntRange>() var ranger: MutableIntRange? = null this.sortedBy { it.first }.forEachIndexed { idx, range -> if (ranger == null) { ranger = MutableIntRange(range.first, range.last)} if (range.first <= (ranger!!.last+1)) { ranger!!.last = max(ranger!!.last, range.last) } else { result.add(IntRange(ranger!!.first, ranger!!.last)) ranger!!.first = range.first ranger!!.last = range.last } } if (ranger != null) { result.add(IntRange(ranger!!.first, ranger!!.last)) } return result } fun main() { val sensorRegex = "^Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() fun parse(input: List<String>): Map<Int, List<IntRange>> { val map = mutableMapOf<Int, MutableList<IntRange>>() input.map { sensorRegex.matchEntire(it)!!.destructured.toList().map(String::toInt) }.forEach { (sx, sy, bx, by) -> val d = abs(sx - bx) + abs(sy - by) val yRange = ((sy - d)..(sy + d)) yRange.forEach{ y -> map.getOrPut(y) { mutableListOf() }.add( (sx - d + abs(sy - y))..(sx + d - abs(sy - y)) ) } } map.replaceAll { y, ranges -> ranges.combine() as MutableList<IntRange> } return map } fun draw(map: Map<Int, List<IntRange>>, sx: Int? = null, sy: Int? = null) { val xMin = map.minOf { it.value.minOf { range -> range.first } } val xMax = map.maxOf { it.value.maxOf { range -> range.last } } for (y in map.keys.sorted()) { for (x in xMin..xMax) { var c = '.' if (map[y]!!.any { it.contains(x) }) { c = '#' } if (sx != null && x in 0..sx && (y == 0 || y == sy)) { c = '+' } if (sy != null && y in 0..sy && (x == 0 || x == sx)) { c = '|' } print(c) } print("\n") } } fun part1(input: List<String>, y: Int): Int { val map = parse(input) if (y == 10) { draw(map) } return map[y]!!.sumOf { (it.last - it.first) } } fun part2(input: List<String>, sx: Int = 20, sy: Int = 20): Long { val map = parse(input) map.keys.sorted().filter { it in 0..sy }.forEach { y -> if(map[y]!!.size > 1) { return (map[y]!![1].first - 1) * 4000000L + y } } return -1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000, 4000000)) }
0
Kotlin
0
0
f74331778fdd5a563ee43cf7fff042e69de72272
3,158
advent-of-code-2022
Apache License 2.0
src/Day03.kt
hnuttin
572,601,761
false
{"Kotlin": 5036}
fun main() { val priorities = "0abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; part1(readInput("Day03_test"), priorities) part2(readInput("Day03_test"), priorities) // part2(readInput("Day03_example"), priorities) } fun part2(readInput: List<String>, priorities: String) { val priorities = readInput.chunked(3) .map { group -> commonInGroup(group) } .map { commonChar -> toPriority(priorities, commonChar) } println(priorities.sum()); } fun commonInGroup(group: List<String>): Char { return group.first().chars() .filter { char -> group.get(1).contains(char.toChar(), false) && group.get(2).contains(char.toChar(), false) } .findFirst() .asInt .toChar(); } private fun part1(testInput: List<String>, priorities: String) { val commonChars = testInput.map { rawGame -> rawGame.chunked(rawGame.length / 2) } .map { chunked -> Pair(chunked.first(), chunked.last()) } .map { compartments -> compartments.first.chars().filter { char -> compartments.second.contains(char.toChar(), false) }.findFirst() } .filter { commonChar -> commonChar.isPresent } .map { commonChar -> commonChar.asInt } .map { commonChar -> commonChar.toChar() }; val priorities = commonChars.map { commonChar -> toPriority(priorities, commonChar) } println(priorities.sum()); } private fun toPriority(priorities: String, commonChar: Char) = priorities.indexOf(commonChar, 0, false)
0
Kotlin
0
0
53975ed6acb42858be56c2150e573cdbf3deedc0
1,487
aoc-2022
Apache License 2.0
src/Day18.kt
inssein
573,116,957
false
{"Kotlin": 47333}
fun main() { fun List<String>.toCubes(): Set<Triple<Int, Int, Int>> = this.map { val parts = it.split(",").map { s -> s.toInt() } Triple(parts[0], parts[1], parts[2]) }.toSet() fun Triple<Int, Int, Int>.toSides(): List<Triple<Int, Int, Int>> { val (x, y, z) = this return listOf( Triple(x + 1, y, z), Triple(x - 1, y, z), Triple(x, y + 1, z), Triple(x, y - 1, z), Triple(x, y, z + 1), Triple(x, y, z - 1), ) } fun part1(input: List<String>): Int { val cubes = input.toCubes() return cubes.sumOf { it.toSides().count { s -> !cubes.contains(s) } } } fun part2(input: List<String>): Int { val cubes = input.toCubes() val xRange = cubes.minOf { it.first } - 1..cubes.maxOf { it.first } + 1 val yRange = cubes.minOf { it.second } - 1..cubes.maxOf { it.second } + 1 val zRange = cubes.minOf { it.third } - 1..cubes.maxOf { it.third } + 1 val toVisit = mutableListOf(Triple(xRange.first, yRange.first, zRange.first)) val visited = mutableSetOf<Triple<Int, Int, Int>>() var sides = 0 while (toVisit.isNotEmpty()) { val point = toVisit.removeFirst() if (!visited.add(point)) { continue } val sidesInRange = point.toSides().filter { (x, y, z) -> x in xRange && y in yRange && z in zRange } val sidesOut = sidesInRange.filterNot { it in cubes } toVisit.addAll(sidesOut) sides += sidesInRange.size - sidesOut.size } return sides } val testInput = readInput("Day18_test") println(part1(testInput)) // 64 println(part2(testInput)) // 58 val input = readInput("Day18") println(part1(input)) // 3326 println(part2(input)) // 1996 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
1,915
advent-of-code-2022
Apache License 2.0
src/Day11.kt
sabercon
648,989,596
false
null
typealias Seats = List<List<Char>> typealias Point = Pair<Int, Int> typealias Direction = Pair<Int, Int> typealias Rule = (Seats, Point, Direction) -> Boolean fun main() { fun hasAdjacentOccupiedSeats(seats: Seats, point: Point, direction: Direction): Boolean { val (i, j) = point val (di, dj) = direction return seats.getOrNull(i + di)?.getOrNull(j + dj) == '#' } fun hasSeenOccupiedSeats(seats: Seats, point: Point, direction: Direction): Boolean { val (i, j) = point val (di, dj) = direction return generateSequence(i + di to j + dj) { (i, j) -> i + di to j + dj } .map { (i, j) -> seats.getOrNull(i)?.getOrNull(j) } .dropWhile { it == '.' } .first() == '#' } fun seenOccupiedSeats(seats: Seats, point: Point, occupiedRule: Rule): Int { return (-1..1).flatMap { i -> (-1..1).map { j -> i to j } } .filter { (i, j) -> i != 0 || j != 0 } .count { occupiedRule(seats, point, it) } } fun move(seats: Seats, occupiedLimit: Int, occupiedRule: Rule): Seats { return seats.mapIndexed { i, row -> row.mapIndexed { j, seat -> when { seat == 'L' && seenOccupiedSeats(seats, i to j, occupiedRule) == 0 -> '#' seat == '#' && seenOccupiedSeats(seats, i to j, occupiedRule) >= occupiedLimit -> 'L' else -> seat } } } } tailrec fun finalOccupiedSeats(seats: Seats, occupiedLimit: Int, occupiedRule: Rule): Int { val nextSeats = move(seats, occupiedLimit, occupiedRule) return if (nextSeats == seats) { seats.sumOf { row -> row.count { it == '#' } } } else { finalOccupiedSeats(nextSeats, occupiedLimit, occupiedRule) } } val input = readLines("Day11").map { it.toList() } finalOccupiedSeats(input, 4, ::hasAdjacentOccupiedSeats).println() finalOccupiedSeats(input, 5, ::hasSeenOccupiedSeats).println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
2,055
advent-of-code-2020
MIT License
src/main/kotlin/dp/LCIS.kt
yx-z
106,589,674
false
null
package dp import util.get import util.max import util.set // longest common increasing subsequence // given two sequences A[1..m], and B[1..n] // find the length of longest common sequence that is also increasing fun main(args: Array<String>) { val A = intArrayOf(1, 5, 6) val B = intArrayOf(1, 5, 3, 6) println(lcis(A, B)) } fun lcis(A: IntArray, B: IntArray): Int { val m = A.size val n = B.size // let M[1..l] be the sorted sequence of common elements of A and B // then M is strictly increasing val M = (A.toSet() intersect B.toSet()).toMutableList() // sorting costs O(min(m, n) * log min(m, n)) time M.sort() // l is O(min(m, n)) val l = M.size // dp(i, j, k): len of lcis for A[1..i] and B[1..j] : last element = M[k] // we want max_k{ dp(m, n, k) } var max = 0 // memoization structure: 3d array dp[0..m, 0..n, 1..l] : dp[i, j, k] = dp(i, j, k) val dp = Array(m + 1) { Array(n + 1) { IntArray(l) } } // space complexity: O(l + m * n * l) = O(m * n * (m + n)) // assume max{ } = 0 // dp(i, j, k) = 0 if i !in 1..m or j !in 1..n or k !in 1..l // = max{ 1 + max_p{ dp(i - 1, j - 1, p) : p < k }, // dp(i - 1, j, k), // dp(i, j - 1, k) } if A[i] = B[j] = M[k] // = max { dp(i - 1, j, k), dp(i, j - 1, k) } o/w // dependency: dp(i, j, k) depends on entries in the previous table, // and entries to the left and to the upper-left // evaluation order: outermost loop for k from 1 to l for (k in 0 until l) { // middle loop for i from 1 to m (top to down) // no need to touch i = 0 or j = 0 since they are covered in the base case for (i in 1..m) { //innermost loop for i from 1 to n (left to right) for (j in 1..n) { dp[i, j, k] = max(dp[i - 1, j, k], dp[i, j - 1, k]) if (A[i - 1] == B[j - 1] && B[j - 1] <= M[k]) { // O(l) work for some entries dp[i, j, k] = max(dp[i, j, k], 1 + ((0 until k).map { dp[i - 1, j - 1, it] } .max() ?: 0)) } if (i == m && j == n) { max = max(max, dp[i, j, k]) } } } } // time complexity: O(m * n * l^2) = O(m * n * (m + n)^2) return max }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,151
AlgoKt
MIT License
src/main/kotlin/aoc2022/Day12.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2022 import Point import readInput private class Input(val map: Array<IntArray>, val start: Point, val end: Point) private fun parseInput(input: List<String>): Input { lateinit var start: Point lateinit var end: Point val map = input.withIndex().map { row -> row.value.toCharArray().withIndex().map { column -> when (column.value) { 'S' -> { start = Point(column.index, row.index) 0 } 'E' -> { end = Point(column.index, row.index) 'z' - 'a' } else -> column.value - 'a' } }.toIntArray() }.toTypedArray() return Input(map, start, end) } /** * Finds the minimal distance from [current] to a point satisfying the [endCheck] * * @param current the starting point * @param pathLength the path length so far * @param minDistanceMap a map with the current minimal distances from the original start * @param reachableNeighbours a function returning all reachable neighbours of a given point * @param endCheck a check to determine if we reached our end * * @return the minimum distance to the first point satisfying the [endCheck] */ private fun findMinDistance( current: Point, pathLength: Int, minDistanceMap: Array<IntArray>, reachableNeighbours: (Point) -> List<Point>, endCheck: (Point) -> Boolean = { false } ): Int { val pointsToVisit = mutableSetOf<Point>() for (p in reachableNeighbours(current)) { if (minDistanceMap[p.y][p.x] > pathLength + 1) { minDistanceMap[p.y][p.x] = pathLength + 1 if (endCheck(p)) { return pathLength + 1 } pointsToVisit.add(p) } } if (pointsToVisit.isEmpty()) return Integer.MAX_VALUE // dead end return pointsToVisit.minOf { findMinDistance(it, pathLength + 1, minDistanceMap, reachableNeighbours, endCheck) } } private fun part1(input: List<String>): Int { val i = parseInput(input) val minDistanceMap = Array(i.map.size) { IntArray(i.map.first().size) { Int.MAX_VALUE } } minDistanceMap[i.start.y][i.start.x] = 0 val reachableNeighbours = { current: Point -> val neighbours = current.getNeighbours(validGrid = Point(0, 0) to Point(i.map.first().size - 1, i.map.size - 1)) val currentElevation = i.map[current.y][current.x] neighbours.filter { currentElevation >= i.map[it.y][it.x] - 1 } } val endCheck = { point: Point -> point == i.end } return findMinDistance(i.start, 0, minDistanceMap, reachableNeighbours, endCheck) } private fun part2(input: List<String>): Int { val i = parseInput(input) val minDistanceMap = Array(i.map.size) { IntArray(i.map.first().size) { Int.MAX_VALUE } } minDistanceMap[i.end.y][i.end.x] = 0 val reachableNeighbours = { current: Point -> val neighbours = current.getNeighbours(validGrid = Point(0, 0) to Point(i.map.first().size - 1, i.map.size - 1)) val currentElevation = i.map[current.y][current.x] neighbours.filter { currentElevation <= i.map[it.y][it.x] + 1 } } val endCheck = { point: Point -> i.map[point.y][point.x] == 0 } return findMinDistance(i.end, 0, minDistanceMap, reachableNeighbours, endCheck) } fun main() { val testInput = readInput("Day12_test", 2022) check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12", 2022) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,577
adventOfCode
Apache License 2.0
src/Day07.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
data class Directory( val name: String, val parent: Directory? = null, val directories: MutableMap<String, Directory> = mutableMapOf(), val files: MutableList<AdventFile> = mutableListOf(), ) { override fun toString(): String = "name=${name},directories=$directories,files=$files" fun size(): Int = files.sumOf { it.size } + directories.values.sumOf { it.size() } fun sizes(): List<Pair<String, Int>> { var map = directories.values.map { it.name to it.size() } map = map + directories.values.flatMap { it.sizes() } return map } } data class AdventFile( val name: String, val size: Int, ) fun readTree(input: List<String>): Directory { val root = Directory("/") var currentDirectory = root for (command in input) { if (command.startsWith("$")) { if (command.startsWith("$ cd")) { val dirName = command.replace("$ cd ", "") when (dirName) { "/" -> currentDirectory = root ".." -> currentDirectory = currentDirectory.parent!! else -> currentDirectory = currentDirectory.directories[dirName]!! } } } else { if (command.startsWith("dir")) { val dirName = command.replace("dir ", "") val directory = Directory(dirName, currentDirectory) currentDirectory.directories[dirName] = directory } else { val parts = command.split(" ") currentDirectory.files += AdventFile(name = parts[1], size = parts[0].toInt()) } } } return root } fun main() { fun part1(input: List<String>): Int { val tree = readTree(input) val sizes = tree.sizes() return sizes.filter { it.second <= 100000 }.sumOf { it.second }.also { println(it) } } fun part2(input: List<String>): Int { val tree = readTree(input) val size = tree.size() val maxSize = 70000000L val currentTaken = maxSize - size val toFree = 30000000L - (maxSize - size) println("$toFree $size") val totalTree = tree.sizes() + listOf("/" to size) return totalTree.filter { it.second >= toFree }.map { it.second }.min() } // 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
1d7ab334f38a9e260c72725d3f583228acb6aa0e
2,647
advent-2022
Apache License 2.0
src/jvmMain/kotlin/day07/initial/Day07.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day07.initial import java.io.File fun main() { // solvePart1() // Solution: 253910319, time: 08:02 solvePart2() // Solution: 253910319, time: 08:02 } fun solvePart2() { val input = File("src/jvmMain/kotlin/day07/input/input_part1_test.txt") // val input = File("src/jvmMain/kotlin/day07/input/input.txt") val lines = input.readLines() val handList = lines.map { it.split(" ") .filter { it.isNotBlank() } }.map { (handText, bidText) -> Hand(handText, bidText) }.sorted() val message = handList.mapIndexed { index, hand -> "${hand.list.map { it.char }.joinToString("")} ${hand.bid} ${(index + 1)} ${hand.type}" } println(message.joinToString("\n")) println(handList.mapIndexed { index, hand -> hand.bid * (index + 1)}.sum()) } // 254046151 is not right answer fun solvePart1() { // val input = File("src/jvmMain/kotlin/day07/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day07/input/input.txt") val lines = input.readLines() val handList = lines.map { it.split(" ") .filter { it.isNotBlank() } }.map { (handText, bidText) -> Hand(handText, bidText) }.sorted() val message = handList.mapIndexed { index, hand -> "${hand.list.map { it.char }.joinToString("")} ${hand.bid} ${(index + 1)} ${hand.type}" } println(message.joinToString("\n")) println(handList.mapIndexed { index, hand -> hand.bid * (index + 1)}.sum()) } fun Hand(handText: String, bidText: String): Hand { return Hand( list = handText.map { handChar -> Card.values().first { it.char == handChar } }, type = Type.HighCard, bid = bidText.toInt() ).let { hand -> hand.copy(type = Type.values().reversed().first { it.rule(hand) }) } } data class Hand( val list: List<Card>, // 5 cards val type: Type, val bid: Int ) : Comparable<Hand> { override fun compareTo(other: Hand): Int { val firstRuleResult = compareByFirstRule(other) return if (firstRuleResult == 0) { compareBySecondRule(other) } else { firstRuleResult } } private fun compareByFirstRule(other: Hand): Int { val rules = Type.values().reversed() val typeFirst = rules.find { it.rule(this) }!! val typeOther = rules.find { it.rule(other) }!! return typeFirst.ordinal.compareTo(typeOther.ordinal) } private fun compareBySecondRule(other: Hand): Int { val pairs = this.list.zip(other.list) { first, second -> first to second } val pair = pairs.find { pair -> pair.first != pair.second } ?: error("Why are pairs the same? this hand: $this, other hand: $other, pairs: $pairs") return if (pair.first > pair.second) { 1 } else { -1 } } } enum class Type(val rule: (hand: Hand) -> Boolean) { HighCard({ hand -> hand.list.distinct().size == 5 }), OnePair({ hand -> hand.list.distinct().size == 4 }), TwoPair({ hand -> hand.list.distinct().size == 3 }), ThreeOfAKind({ hand -> hand.list.sortedBy { it.char }.windowed(3).any { it.distinct().size == 1 } }), FullHouse({ hand -> hand.list.distinct().size == 2 && hand.list.sortedBy { it.char }.windowed(3).any { it.distinct().size == 1 } }), FourOfAKind({ hand -> hand.list.distinct().size == 2 && hand.list.sortedBy { it.char }.windowed(4).any { it.distinct().size == 1 }}), FiveOfAKind({ hand -> hand.list.distinct().size == 1 }); } // Throws stack overflow for some reason //enum class Type(val rule: (hand: Hand) -> Boolean) { // HighCard({ hand -> // replaceJoker(hand).list.distinct().size == 5 // }), // OnePair({ hand -> replaceJoker(hand).list.distinct().size == 4 }), // TwoPair({ hand -> replaceJoker(hand).list.distinct().size == 3 }), // ThreeOfAKind({ hand -> replaceJoker(hand).list.sortedBy { it.char }.windowed(3).any { it.distinct().size == 1 } }), // FullHouse({ hand -> // val replaced = replaceJoker(hand) // replaced.list.distinct().size == 2 && // replaced.list.sortedBy { it.char }.windowed(3).any { it.distinct().size == 1 } // }), // FourOfAKind({ hand -> // val replaced = replaceJoker(hand) // replaced.list.distinct().size == 2 && // replaced.list.sortedBy { it.char }.windowed(4).any { it.distinct().size == 1 }}), // FiveOfAKind({ hand -> replaceJoker(hand).list.distinct().size == 1 }); // // //} fun replaceJoker(hand: Hand): Hand { return if (hand.list.any { it == Card.Joker }) { // Create all possible hands with Joker replaced val handList = Card.values().map { possibleCard -> val newList = hand.list.map { handCard -> if (handCard == Card.Joker) possibleCard else handCard } Hand(newList, Type.HighCard, hand.bid).run { copy(type = Type.values().reversed().first { it.rule(hand) })} }.sortedByDescending { it }[0] handList } else { hand } } fun Hand.compareByFirst(other: Hand): Int { val fiveOfAKind = other return 0 } fun Hand.compareBySecond(other: Hand): Int { return 0 } enum class Card(val char: Char, val value: Int) { Joker('J', 1), Two('2', 2), Three('3', 3), Four('4', 4), Five('5', 5), Six('6', 6), Seven('7', 7), Eight('8', 8), Nine('9', 9), Ten('T', 10), Queen('Q', 12), King('K', 13), Ace('A', 14); }
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
5,588
advent-of-code
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day16.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution import adventofcode.util.algorithm.transpose object Day16 : AdventSolution(2020, 16, "Ticket Translation") { override fun solvePartOne(input: String): Int { val (fields, _, otherTickets) = parse(input) return otherTickets.flatten() .filter { value -> fields.none { field -> value in field } } .sum() } override fun solvePartTwo(input: String): Any { val p = parse(input).filterInvalidTickets() return p.deduceFieldNameMapping() .filterKeys { it.startsWith("departure") } .values .map { p.yourTicket[it] } .fold(1L, Long::times) } } private fun ProblemData.filterInvalidTickets() = copy(otherTickets = otherTickets.filter { xs -> xs.all { x -> fields.any { range -> x in range } } }) private fun ProblemData.deduceFieldNameMapping(): Map<String, Int> { val dataset = otherTickets.plusElement(yourTicket).transpose() val candidateNames = dataset.map { column -> fields .filter { field -> column.all(field::contains) } .map(Field::name) .toMutableSet() } return buildMap { while (candidateNames.any { it.isNotEmpty() }) { val (i, name) = candidateNames.map { it.singleOrNull() }.withIndex().first { it.value != null } this[name!!] = i for (field in candidateNames) field -= name } } } private fun parse(input: String): ProblemData { fun parseToField(input: String): Field { val propRegex = """([\s\w]+): (\d+)-(\d+) or (\d+)-(\d+)""".toRegex() val (name, l1, h1, l2, h2) = propRegex.matchEntire(input)!!.destructured return Field(name, l1.toInt()..h1.toInt(), l2.toInt()..h2.toInt()) } fun parseToTicket(input: String) = input.split(',').map { it.toInt() } val (fields, yourTicket, otherTickets) = input.split("\n\n") return ProblemData( fields = fields.lines().map(::parseToField), yourTicket = parseToTicket(yourTicket.lines().last()), otherTickets = otherTickets.lines().drop(1).map(::parseToTicket) ) } private data class ProblemData(val fields: List<Field>, val yourTicket: List<Int>, val otherTickets: List<List<Int>>) private data class Field(val name: String, val r1: IntRange, val r2: IntRange) { operator fun contains(i: Int) = i in r1 || i in r2 }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,451
advent-of-code
MIT License
src/Day15.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
import java.util.Date import kotlin.math.abs fun main() { fun parseSensorBeaconPairs(input: List<String>): List<Pair<Coordinates, Coordinates>> { return input .map { it.substring(12).split(": closest beacon is at x=") } .map { val sensorRaw = it[0].split(", y=") val beaconRaw = it[1].split(", y=") val sensor = Coordinates(sensorRaw[1].toInt(), sensorRaw[0].toInt()) val beacon = Coordinates(beaconRaw[1].toInt(), beaconRaw[0].toInt()) Pair(sensor, beacon) } } fun part1(input: List<String>, targetRow: Int): Int { val pairs = parseSensorBeaconPairs(input) val ranges = mutableListOf<InclusiveRange>() for((sensor, beacon) in pairs) { val distanceToBeacon = sensor.manhattanDistance(beacon) val distanceToRow = abs(targetRow - sensor.row) val colsInRow = distanceToBeacon - distanceToRow if (colsInRow >= 0) { val midCol = sensor.col val left = midCol - colsInRow val right = midCol + colsInRow val leftAdjust = left + if(beacon.row == targetRow && left == beacon.col) 1 else 0 val rightAdjust = right - if(beacon.row == targetRow && right == beacon.col) 1 else 0 var range = InclusiveRange(leftAdjust, rightAdjust) var overlaps = ranges.find { it.overlaps(range) } while (overlaps != null) { ranges.remove(overlaps) range = overlaps.merge(range) overlaps = ranges.find { it.overlaps(range) } } ranges.add(range) } } val result = ranges.sumOf { it.y - it.x + 1 } return result } fun part2(input: List<String>, limit: InclusiveRange): Long { val pairs = parseSensorBeaconPairs(input) for(targetRow in limit.x .. limit.y) { val ranges = mutableListOf<InclusiveRange>() for ((sensor, beacon) in pairs) { val distanceToBeacon = sensor.manhattanDistance(beacon) val distanceToRow = abs(targetRow - sensor.row) val colsInRow = distanceToBeacon - distanceToRow if (colsInRow >= 0) { val midCol = sensor.col val left = maxOf(midCol - colsInRow, limit.x) val right = minOf(midCol + colsInRow, limit.y) var range = InclusiveRange(left, right) var overlaps = ranges.find { it.overlaps(range) } while (overlaps != null) { ranges.remove(overlaps) range = overlaps!!.merge(range) overlaps = ranges.find { it.overlaps(range) } } ranges.add(range) } } if (ranges.size > 1) { // Found missing beacon val x = minOf(ranges[0].y, ranges[1].y) + 1 val y = targetRow println(targetRow) return 4000000L * x.toLong() + y.toLong() } } throw IllegalStateException("Didn't find result") } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, InclusiveRange(0, 20)) == 56000011L) val input = readInput("Day15") val start = Date().time println(part1(input, 2000000)) println("Part1 time: ${Date().time - start}ms") val start2 = Date().time println(part2(input, InclusiveRange(0, 4000000))) println("Part2 time: ${Date().time - start2}ms") }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
3,776
aoc2022
Apache License 2.0
src/day11/Day11.kt
andreas-eberle
573,039,929
false
{"Kotlin": 90908}
package day11 import groupByBlankLine import readInput const val day = "11" fun main() { fun calculatePart1Score(input: List<String>): Long { val monkeys = input.groupByBlankLine().values.map { it.toMonkey(3) } val gameRounds = monkeys.runGame(20) return gameRounds.calculateMonkeyBusiness() } fun calculatePart2Score(input: List<String>): Long { val monkeys = input.groupByBlankLine().values.map { it.toMonkey(1) } val worryNormalization = monkeys.map { it.testDivider }.reduce { acc, l -> acc * l } val gameRounds = monkeys.runGame(10000, worryNormalization) return gameRounds.calculateMonkeyBusiness() } // test if implementation meets criteria from the description, like: val testInput = readInput("/day$day/Day${day}_test") val input = readInput("/day$day/Day${day}") val part1TestPoints = calculatePart1Score(testInput) val part1points = calculatePart1Score(input) println("Part1 test points: $part1TestPoints") println("Part1 points: $part1points") check(part1TestPoints == 10605L) val part2TestPoints = calculatePart2Score(testInput) val part2points = calculatePart2Score(input) println("Part2 test points: \n$part2TestPoints") println("Part2 points: \n$part2points") check(part2TestPoints == 2713310158L) } fun List<Monkey>.runGame(rounds: Int, worryNormalization: Long = Long.MAX_VALUE): List<List<Monkey>> { return (1..rounds).runningFold(this) { oldMonkeys, _ -> val newMonkeys = oldMonkeys.toMutableList() repeat(oldMonkeys.size) { monkeyIdx -> val monkey = newMonkeys[monkeyIdx] monkey.itemsWorryLevel.map { monkey.calculateNewWorryLevel(it, worryNormalization) }.forEach { newWorryLevel -> val nextMonkeyIdx = monkey.selectNextMonkey(newWorryLevel) val nextMonkey = newMonkeys[nextMonkeyIdx] newMonkeys[nextMonkeyIdx] = nextMonkey.giveItem(newWorryLevel) } newMonkeys[monkeyIdx] = monkey.copy(itemsWorryLevel = emptyList(), inspectionCounter = monkey.inspectionCounter + monkey.itemsWorryLevel.size) } newMonkeys } } fun List<List<Monkey>>.calculateMonkeyBusiness(): Long { val (monkey1, monkey2) = this.last().sortedByDescending { it.inspectionCounter }.take(2) return monkey1.inspectionCounter * monkey2.inspectionCounter } data class Monkey( val itemsWorryLevel: List<Long>, val operationSymbol: String, val operationAmountString: String, val endOfInspectionWorryDivider: Long, val testDivider: Long, val testTrueMonkey: Int, val testFalseMonkey: Int, val inspectionCounter: Long = 0 ) { fun giveItem(worryLevel: Long): Monkey { return copy(itemsWorryLevel = itemsWorryLevel + listOf(worryLevel)) } fun calculateNewWorryLevel(oldWorryLevel: Long, worryNormalization: Long): Long { val operationAmount = when (operationAmountString) { "old" -> oldWorryLevel else -> operationAmountString.toLong() } return (when (operationSymbol) { "*" -> oldWorryLevel * operationAmount "+" -> oldWorryLevel + operationAmount "-" -> oldWorryLevel - operationAmount "/" -> oldWorryLevel / operationAmount else -> error("Unknown operation $operationSymbol") } / endOfInspectionWorryDivider) % worryNormalization } fun selectNextMonkey(worry: Long): Int { return if (worry % testDivider == 0L) testTrueMonkey else testFalseMonkey } } fun List<String>.toMonkey(worryDivider: Long): Monkey { val startWorryLevel = this[1].substringAfter(" Starting items: ").split(", ").map { it.toLong() } val (operationSymbol, operationAmountString) = this[2].substringAfter(" Operation: new = old ").split(" ") val testDivider = this[3].substringAfter(" Test: divisible by ").toLong() val testTrueMonkey = this[4].substringAfter(" If true: throw to monkey ").toInt() val testFalseMonkey = this[5].substringAfter(" If false: throw to monkey ").toInt() return Monkey(startWorryLevel, operationSymbol, operationAmountString, worryDivider, testDivider, testTrueMonkey, testFalseMonkey) }
0
Kotlin
0
0
e42802d7721ad25d60c4f73d438b5b0d0176f120
4,282
advent-of-code-22-kotlin
Apache License 2.0
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day03.kt
JamJaws
725,792,497
false
{"Kotlin": 30656}
package com.jamjaws.adventofcode.xxiii.day import com.jamjaws.adventofcode.xxiii.readInput class Day03 { fun part1(text: List<String>): Int { val numbers = getNumbers(text) val coordinates = getCoordinates(text, "[^.\\d]").flatMap(::getAdjacentCoordinates) return numbers.filter { it.coordinates.any(coordinates::contains) } .map(Numbers::value) .sum() } fun part2(text: List<String>): Int { val numbers = getNumbers(text) val coordinates = getCoordinates(text, "\\*").map(::getAdjacentCoordinates) return coordinates.map { coordinate -> numbers.filter { number -> number.coordinates.any(coordinate::contains) } }.filter { it.size == 2 } .map { it.map(Numbers::value) } .sumOf { (first, second) -> first * second } } private fun getCoordinates(text: List<String>, pattern: String) = text.map(Regex(pattern)::findAll) .flatMapIndexed { index, match -> match.flatMap(MatchResult::groups) .filterNotNull() .map(MatchGroup::range) .map(IntRange::start) .map { Pair(index, it) } .toList() } private fun getNumbers(text: List<String>) = text.map(Regex("\\d+")::findAll) .flatMapIndexed { index, match -> match.flatMap(MatchResult::groups) .filterNotNull() .map { group -> Numbers( group.value.toInt(), group.range.map { Pair(index, it) } ) }.toList() } private fun getAdjacentCoordinates(coordinate: Pair<Int, Int>): List<Pair<Int, Int>> { val (y, x) = coordinate return (-1..1).flatMap { yDelta -> (-1..1).map { xDelta -> Pair(y + yDelta, x + xDelta) } } } } data class Numbers( val value: Int, val coordinates: List<Pair<Int, Int>>, ) fun main() { val answer1 = Day03().part1(readInput("Day03")) println(answer1) val answer2 = Day03().part2(readInput("Day03")) println(answer2) }
0
Kotlin
0
0
e2683305d762e3d96500d7268e617891fa397e9b
2,279
advent-of-code-2023
MIT License
src/main/kotlin/Day19.kt
gijs-pennings
573,023,936
false
{"Kotlin": 20319}
import kotlin.math.max private const val MAX_TIME = 24 // set MAX_TIME=32 for part 2 fun main() { val recipes = readInput(19).map { line -> val nums = Regex("\\d+").findAll(line).map { it.value.toInt() }.toList() mapOf( RobotType.ORE to Resources(ore = nums[1]), RobotType.CLAY to Resources(ore = nums[2]), RobotType.OBSIDIAN to Resources(ore = nums[3], clay = nums[4]), RobotType.GEODE to Resources(ore = nums[5], obsidian = nums[6]) ) } // for part 2, take only the first three recipes and simply multiply the results of `findMaxGeodes` println(recipes.mapIndexed { i, costs -> println(i+1) globalBest = 0 (i+1) * findMaxGeodes(costs) }.sum()) } private var globalBest = 0 // beware! global variable private fun findMaxGeodes(costs: Map<RobotType, Resources>, state: State = State()): Int { var geodes = 0 for ((type, cost) in costs) { val next = state.build(type, cost) ?: continue if (next.geodeUpperbound <= globalBest) continue // prune geodes = max( geodes, if (next.isFinal) next.resources.geode else findMaxGeodes(costs, next) ) globalBest = max(globalBest, geodes) } return geodes } private enum class RobotType( val indicator: Resources ) { ORE (Resources(ore = 1)), CLAY (Resources(clay = 1)), OBSIDIAN(Resources(obsidian = 1)), GEODE (Resources(geode = 1)) } private data class Resources( val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0 ) : AbstractList<Int>() { operator fun minus(r: Resources) = plus(-1 * r) operator fun plus(r: Resources) = Resources(ore + r.ore, clay + r.clay, obsidian + r.obsidian, geode + r.geode) override val size = 4 override fun get(index: Int): Int = when (index) { 0 -> ore 1 -> clay 2 -> obsidian 3 -> geode else -> throw IndexOutOfBoundsException() } } private operator fun Int.times(r: Resources) = Resources(this * r.ore, this * r.clay, this * r.obsidian, this * r.geode) private class State( val time: Int = 0, val resources: Resources = Resources(), val robots: Resources = Resources(ore = 1) ) { val isFinal get() = time == MAX_TIME val geodeUpperbound: Int get() { val t = MAX_TIME - time return resources.geode + t * robots.geode + (t-1) * t / 2 // last term: no. geodes if we could build new robot each minute } init { if (time > MAX_TIME) println("too late") } fun build(type: RobotType, cost: Resources): State? { var t = 0 cost.forEachIndexed { i, c -> if (c > 0) if (robots[i] > 0) t = max(t, (c - resources[i] + robots[i] - 1) / robots[i]) // time to gather resources (ceil) else return null // impossible } t++ // time to build return if (time + t < MAX_TIME) State(time + t, resources + t * robots - cost, robots + type.indicator) else State(MAX_TIME, resources + (MAX_TIME - time) * robots, robots) } }
0
Kotlin
0
0
8ffbcae744b62e36150af7ea9115e351f10e71c1
3,258
aoc-2022
ISC License
src/day16/Day16.kt
gr4cza
572,863,297
false
{"Kotlin": 93944}
package day16 import readInput fun main() { fun parse(input: List<String>): List<Valve> { val split = input.map { val (valves, connections) = it.split(";") valves to connections } val valveList = split.map { (valves, _) -> val (_, name, _, _, rate) = valves.split(" ") Valve(name, rate.split("=").last().toInt()) } split.map { (_, connections) -> when { connections.startsWith(" tunnels lead to valves ") -> { connections .removePrefix(" tunnels lead to valves ").split(", ") } else -> { listOf( connections .removePrefix(" tunnel leads to valve ") ) } } }.forEachIndexed { index, names -> names.forEach { n -> valveList[index].connections.add(valveList.first { it.name == n }) } } return valveList } fun part1(input: List<String>): Int { val valves = parse(input) val remainingTime = 30 val currentValve = valves.first { it.name == "AA" } val calculateValues = currentValve.calculateRoutes( remainingTime = remainingTime, closedValves = valves, ).sortedByDescending { it.value } return calculateValues.maxOf { it.value } } fun part2(input: List<String>): Int { val valves = parse(input) val remainingTime = 26 val currentValve = valves.first { it.name == "AA" } val calculateValues = currentValve.calculateRoutes( remainingTime = remainingTime, closedValves = valves, ).sortedByDescending { it.value } val val2 = calculateValues.find { it.valves.intersect(calculateValues.first().valves.toSet()).isEmpty() } return calculateValues.maxOf { it.value } + (val2?.value ?: 0) } // test if implementation meets criteria from the description, like: val testInput = readInput("day16/Day16_test") val input = readInput("day16/Day16") // check((part1(testInput)).also { println(it) } == 1651) check((part1(input)).also { println(it) } == 1873) // check(part2(testInput).also { println(it) } == 1707) check((part2(input)).also { println(it) } == 2425) } private fun Valve.calculateRoutes( remainingTime: Int, closedValves: List<Valve>, previous: Valve? = null ): List<Route> { if (remainingTime <= 0 || closedValves.none { it.flowRate > 0 }) return listOf(Route(0)) val possibleConnections = getPossibleConnections(previous) return if (this.checkOpenableValve(closedValves)) { val value = this.flowRate * (remainingTime - 1) val newClosedValves = newValves(closedValves) val subRoutes = this.calculateRoutes(remainingTime - 1, newClosedValves, this) subRoutes.map { Route(it.value + value, listOf(this.name) + it.valves) } } else { possibleConnections.map { it.calculateRoutes(remainingTime - 1, closedValves, this) }.flatten() } } private fun Valve.newValves( closedValves: List<Valve>, ): MutableList<Valve> { return closedValves.toMutableList().also { it.remove(this) } } private fun Valve.checkOpenableValve(closedValves: List<Valve>) = this.flowRate > 0 && closedValves.contains(this) private fun Valve.getPossibleConnections(previous: Valve?): List<Valve> { return if (this.connections.size == 1) { this.connections } else { this.connections.filter { it != previous } } } data class Valve( val name: String, val flowRate: Int, val connections: MutableList<Valve> = mutableListOf() ) { override fun toString(): String { return "day16.Valve(name='$name', flowRate=$flowRate, connections=${connections.map { it.name }})" } } data class Route( val value: Int, val valves: List<String> = listOf(), )
0
Kotlin
0
0
ceca4b99e562b4d8d3179c0a4b3856800fc6fe27
4,115
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/pl/jpodeszwik/aoc2023/Day07.kt
jpodeszwik
729,812,099
false
{"Kotlin": 55101}
package pl.jpodeszwik.aoc2023 private val cardValues = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2, ) private fun rank(cards: String): Int { val groups = cards.groupBy { it }.map { it.value.size }.sortedDescending() if (groups[0] == 3 && groups[1] == 2) { return 7 } if (groups[0] == 2 && groups[1] == 2) { return 5 } return groups[0] * 2 } fun compareCards(cards: String, cards2: String, cardValues: Map<Char, Int>): Int { for (i in cards.indices) { val value = cardValues[cards[i]]!! - cardValues[cards2[i]]!! if (value != 0) { return value } } println("warning, same cards") return 0 } data class CardSet(val cards: String, val bid: Long, val rank: Int) private fun part1(lines: List<String>) { val sorted = lines.map { val parts = it.split(" ") CardSet(parts[0], java.lang.Long.parseLong(parts[1]), rank(parts[0])) }.sortedWith { a, b -> val rankDiff = a.rank - b.rank if (rankDiff == 0) compareCards(a.cards, b.cards, cardValues) else rankDiff } val value = sorted.map { it.bid } .reduceIndexed { index, acc, l -> acc + (index + 1).toLong() * l } println(value) } private val cardValues2 = mapOf( 'A' to 14, 'K' to 13, 'Q' to 12, 'J' to 1, 'T' to 10, '9' to 9, '8' to 8, '7' to 7, '6' to 6, '5' to 5, '4' to 4, '3' to 3, '2' to 2, ) private fun rank2(cards: String): Int { val jokers = cards.filter { 'J' == it }.count() if (jokers == 5) { return 10 } val groups = cards.filter { 'J' != it } .groupBy { it } .map { it.value.size } .sortedDescending() .toMutableList() groups[0] += jokers if (groups[0] == 3 && groups[1] == 2) { return 7 } if (groups[0] == 2 && groups[1] == 2) { return 5 } return groups[0] * 2 } private fun part2(lines: List<String>) { val sorted = lines.map { val parts = it.split(" ") CardSet(parts[0], java.lang.Long.parseLong(parts[1]), rank2(parts[0])) }.sortedWith { a, b -> val rankDiff = a.rank - b.rank if (rankDiff == 0) compareCards(a.cards, b.cards, cardValues2) else rankDiff } val value = sorted.map { it.bid } .reduceIndexed { index, acc, l -> acc + (index + 1).toLong() * l } println(value) } fun main() { val lines = loadFile("/aoc2023/input7") part1(lines) part2(lines) }
0
Kotlin
0
0
2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63
2,648
advent-of-code
MIT License
src/poyea/aoc/mmxxii/day14/Day14.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day14 import kotlin.math.abs import kotlin.math.sign import poyea.aoc.utils.readInput fun lineBetween(p1: Pair<Int, Int>, p2: Pair<Int, Int>): List<Pair<Int, Int>> { val dx = (p2.first - p1.first).sign val dy = (p2.second - p1.second).sign val steps = maxOf(abs(p1.first - p2.first), abs(p1.second - p2.second)) return (1..steps).scan(p1) { last, _ -> Pair(last.first + dx, last.second + dy) } } fun solve(input: String, infinite: Boolean = false): Int { val rocks = input .split("\n") .flatMap { path -> path .split(" -> ") .map { it.split(",") } .map { (x, y) -> Pair(x.toInt(), y.toInt()) } .zipWithNext() .flatMap { (p1, p2) -> lineBetween(p1, p2) } } .toSet() val rests = mutableSetOf<Pair<Int, Int>>() val initial = Pair(500, 0) val last = rocks.maxOf { it.second } var current = initial if (!infinite) { while (current.second != last) { val next_possible = listOf( Pair(current.first, current.second + 1), Pair(current.first - 1, current.second + 1), Pair(current.first + 1, current.second + 1) ) .firstOrNull { it !in rocks && it !in rests } current = next_possible ?: initial.also { rests.add(current) } } } else { val floor = 2 + rocks.maxOf { it.second } while (initial !in rests) { val next_possible = listOf( Pair(current.first, current.second + 1), Pair(current.first - 1, current.second + 1), Pair(current.first + 1, current.second + 1) ) .firstOrNull { it !in rocks && it !in rests } current = when (next_possible == null || next_possible.second == floor) { true -> initial.also { rests.add(current) } else -> next_possible } } } return rests.size } fun part1(input: String): Int { return solve(input) } fun part2(input: String): Int { return solve(input, true) } fun main() { println(part1(readInput("Day14"))) println(part2(readInput("Day14"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
2,453
aoc-mmxxii
MIT License
src/main/kotlin/Day11.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun calculate(monkeys: List<Monkey>, numberOfRounds: Int, worryLevel: (Long) -> Long): Long { val inspections = monkeys.associate { it.name to MonkeyInspections(it.name, it.items) } .toMutableMap() val rounds = mutableMapOf<Int, Map<String, MonkeyInspections>>() (1..numberOfRounds).forEach { round -> monkeys.forEach { monkey -> val monkeyInspections = inspections[monkey.name]!! val items = monkeyInspections.items var count = monkeyInspections.count items.forEach { item -> count++ val value = when (monkey.operation.type) { Operation.Type.MULTIPLE -> item * monkey.operation.value!! Operation.Type.PLUS -> item + monkey.operation.value!! else -> item * item } val level = worryLevel(value) val toMonkeyName = if (level % monkey.divisible.toLong() == 0L) { monkey.trueMonkey } else { monkey.falseMonkey } val toMonkey = inspections[toMonkeyName]!! inspections[toMonkeyName] = toMonkey.copy(items = toMonkey.items + level) } inspections[monkey.name] = monkeyInspections.copy(items = emptyList(), count = count) rounds[round] = inspections.toMap() } } return inspections.values .sortedByDescending { it.count } .take(2) .map { it.count } .reduce(Long::times) } fun part1(input: List<Monkey>): Long = calculate(input, 20) { it / 3 } fun part2(input: List<Monkey>): Long { val divisible = input.map { it.divisible }.reduce(Int::times) return calculate(input, 10000) { it % divisible } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test").toMonkeys() check(part1(testInput) == 10605L) println(part2(testInput)) val input = readInput("Day11").toMonkeys() println(part1(input)) println(part2(input)) } fun List<String>.toMonkeys(): List<Monkey> { return this.filter { it.isNotBlank() } .chunked(6) .map { monkey -> val name = monkey[0].substringBefore(":").lowercase() val items = monkey[1].substringAfter(": ").split(",").toList().map { it.trim().toLong() } val operationRaw = monkey[2].substringAfter(" Operation: new = ") val operation = when { operationRaw == "old * old" -> { Operation(Operation.Type.DOUBLE) } operationRaw.startsWith("old +") -> { Operation(Operation.Type.PLUS, operationRaw.substringAfter("old + ").toLong()) } operationRaw.startsWith("old *") -> { Operation(Operation.Type.MULTIPLE, operationRaw.substringAfter("old * ").toLong()) } else -> { error("Not supported: $operationRaw") } } val divisible = monkey[3].substringAfter("Test: divisible by ").toInt() val trueMonkey = monkey[4].substringAfter("If true: throw to ") val falseMonkey = monkey[5].substringAfter("If false: throw to ") Monkey(name, items, operation, divisible, trueMonkey, falseMonkey) } } data class Monkey( val name: String, val items: List<Long>, val operation: Operation, val divisible: Int, val trueMonkey: String, val falseMonkey: String ) data class Operation(val type: Type, val value: Long? = null) { enum class Type { PLUS, MULTIPLE, DOUBLE } } data class MonkeyInspections(val name: String, val items: List<Long>, val count: Long = 0L)
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
4,045
KotlinAdventOfCode2022
Apache License 2.0
src/Day08.kt
roxanapirlea
572,665,040
false
{"Kotlin": 27613}
import kotlin.math.max private data class Tree( val height: Int, val maxLeft: Int = -1, val maxRight: Int = -1, val maxTop: Int = -1, val maxBottom: Int = -1 ) fun main() { fun List<String>.toTrees(): List<List<Tree>> { return map { line -> line.toCharArray().map { c -> Tree(c.digitToInt()) } } } fun List<List<Tree>>.getVisibleTrees(): List<List<Tree>> { val trees: MutableList<MutableList<Tree>> = mutableListOf() forEach { line -> trees.add(line.toMutableList()) } for (i in 0 until trees.size) { for (j in 0 until trees[i].size) { val maxTop = if (i == 0) -1 else max(trees[i - 1][j].maxTop, trees[i - 1][j].height) val maxLeft = if (j == 0) -1 else max(trees[i][j - 1].maxLeft, trees[i][j - 1].height) trees[i][j] = trees[i][j].copy(maxLeft = maxLeft, maxTop = maxTop) } } for (i in trees.size - 1 downTo 0) { for (j in trees[i].size - 1 downTo 0) { val maxBottom = if (i == trees.size - 1) -1 else max(trees[i + 1][j].maxBottom, trees[i + 1][j].height) val maxRight = if (j == trees[i].size - 1) -1 else max(trees[i][j + 1].maxRight, trees[i][j + 1].height) trees[i][j] = trees[i][j].copy(maxRight = maxRight, maxBottom = maxBottom) } } return trees } fun List<List<Tree>>.getMaxScenicScore(): Int { var max = 0 for (i in 1 until size -1) { for (j in 1 until this[i].size -1 ) { var cl = 0 for (jl in j-1 downTo 0) { cl++ if (this[i][jl].height >= this[i][j].height) break } var cr = 0 for (jr in j+1 until this[i].size) { cr++ if (this[i][jr].height >= this[i][j].height) break } var ct = 0 for (itop in i-1 downTo 0) { ct++ if (this[itop][j].height >= this[i][j].height) break } var cb = 0 for (ib in i+1 until size) { cb++ if (this[ib][j].height >= this[i][j].height) break } val score = cl * cr * ct * cb if (max < score) max = score } } return max } fun part1(input: List<String>): Int { return input.toTrees().getVisibleTrees().flatten().count { it.height > it.maxLeft || it.height > it.maxRight || it.height > it.maxTop || it.height > it.maxBottom } } fun part2(input: List<String>): Int { return input.toTrees().getMaxScenicScore() } // 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
6c4ae6a70678ca361404edabd1e7d1ed11accf32
3,077
aoc-2022
Apache License 2.0
src/main/kotlin/adventofcode2023/day12/day12.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day12 import adventofcode2023.readInput import kotlin.time.measureTime fun main() { println("Day 12") val input = readInput("day12") val puzzle1Duration = measureTime { println("Puzzle 1 ${puzzle1(input)}") } println("Puzzle 1 took $puzzle1Duration") val puzzle1ParalelStreamDuration = measureTime { println("Puzzle 1 ParallelStream ${puzzle1ParallelStream(input)}") } println("Puzzle 1 ParallelStream took $puzzle1ParalelStreamDuration") // println("Puzzle 2") // val puzzle2Duration = measureTime { // println("Puzzle 2 ${puzzle2(input)}") // } // println("Puzzle 2 took $puzzle1Duration") } fun puzzle1(input: List<String>): Int { return input.sumOf { l -> countArrangements(l) } } fun puzzle1ParallelStream(input: List<String>): Int { return input.stream().parallel().map { l -> countArrangements(l) }.toList().sum() } fun countArrangements(line: String): Int { val (p,checkSum) = parseLine(line) return findArrangements(p, checkSum).size } fun parseLine(line: String): Pair<String, IntArray> = line.split(' ').let { (first, second) -> Pair( first, second.split(',').map { it.toInt() }.toTypedArray().toIntArray() ) } fun findArrangements(pattern: String, checkSum: IntArray): Collection<String> { tailrec fun generateCandidates(pattern: String, index: Int = 0, candidates: Collection<String> = emptySet()): Collection<String> { if (index == pattern.length) { return candidates } val character = pattern[index] val newCandidates = if (character == '?') { if (candidates.isEmpty()) { setOf(".", "#") } else { candidates.flatMap { listOf("$it.", "$it#") } } } else { if (candidates.isEmpty()) { setOf(character.toString()) } else { candidates.map { it + character } } } return generateCandidates(pattern, index + 1, newCandidates) } fun List<String>.checker(): Boolean { if(this.size != checkSum.size) return false for ((i,s) in this.withIndex()) { if(s.length != checkSum[i]) return false } return true } val candidates = generateCandidates(pattern) return candidates.filter { p -> p.split('.').filter { it.isNotEmpty() }.checker() } } fun countArrangements2(line: String): Long { val (p,checkSum) = parseLine(line).let {(l,c) -> "$l?$l?$l?$l?$l" to c + c + c + c + c } val minLenght = checkSum.sum() + checkSum.size - 1 return if(p.last() == '.') { val first = findArrangements(p, checkSum).size.toLong() val additional = findArrangements("?$p", checkSum).size.toLong() first * additional * additional * additional * additional } else { val first = findArrangements("$p?", checkSum).size.toLong() val additional = findArrangements("?$p", checkSum).size.toLong() first * additional * additional * additional * additional } } fun puzzle2(input: List<String>): Long { return input.sumOf { l -> countArrangements2(l) } }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
3,257
adventofcode2023
MIT License
src/day07/Day07.kt
pnavais
574,712,395
false
{"Kotlin": 54079}
package day07 import readInput private const val TOTAL_DISK_SIZE: Long = 70000000 private const val REQUIRED_UNUSED_SPACE: Long = 30000000 private const val MAX_SIZE_LIMIT: Int = 100000 class File(val name: String, val size: Long) { } class Directory(val name: String, val parent: Directory?) { val subDirectories = mutableMapOf<String, Directory>() val files = mutableListOf<File>() fun computeSize(): Long { var size = files.sumOf { f -> f.size } for (dir in subDirectories.values) { size += dir.computeSize() } return size } fun getAllDirs(): List<Directory> { val dirList = mutableListOf<Directory>() dirList.add(this) for (d in subDirectories.values) { dirList.addAll(d.getAllDirs()) } return dirList } } class DirTree { var root: Directory = Directory("/", null) var currentDir: Directory = root fun getAllDirs(): List<Directory> { return root.getAllDirs() } } fun buildTree(input: List<String>): DirTree { val dirTree = DirTree() for (line in input) { if (line.startsWith("$ cd ")) { // Prepare directory val dir = line.removePrefix("$ cd ") if (dir == "/") { dirTree.currentDir = dirTree.root } else if (dir == "..") { dirTree.currentDir = dirTree.currentDir.parent!! } else { dirTree.currentDir = dirTree.currentDir.subDirectories[dir]!! } } else if (!line.startsWith("$")) { // Read files and dirs if (line.startsWith("dir ")) { val dir = line.removePrefix("dir ") dirTree.currentDir.subDirectories[dir] = Directory(dir, dirTree.currentDir) } else { val (size, name) = line.split(" ") dirTree.currentDir.files.add(File(name, size.toLong())) } } } dirTree.currentDir = dirTree.root return dirTree } fun part1(input: List<String>): Long { val dirTree = buildTree(input) val totalSize = dirTree.getAllDirs().filter { directory -> directory.computeSize() <= MAX_SIZE_LIMIT }.sumOf { d -> d.computeSize() } return totalSize } fun part2(input: List<String>): Long { val dirTree = buildTree(input) val neededSpace = REQUIRED_UNUSED_SPACE - (TOTAL_DISK_SIZE - dirTree.root.computeSize()) return dirTree.getAllDirs().map { d -> d.computeSize() }.filter { s -> s >= neededSpace }.minOf { it } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day07/Day07_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
ed5f521ef2124f84327d3f6c64fdfa0d35872095
2,867
advent-of-code-2k2
Apache License 2.0
advent-of-code-2022/src/Day12.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
fun main() { "Part 1" { val testInput = readInput("Day12_test") val input = readInput("Day12") part1(testInput) shouldBe 31 answer(part1(input)) } "Part 2" { val testInput = readInput("Day12_test") val input = readInput("Day12") part2(testInput) shouldBe 29 answer(part2(input)) } } private fun part1(field: Array<CharArray>): Int = climbDown(field) private fun part2(field: Array<CharArray>): Int = climbDown(field, shouldStop = { it == 'a' }) // Time - O(N*M), Space - O(N*M) // where, N - number of rows, M - number of columns private fun climbDown(field: Array<CharArray>, shouldStop: (Char) -> Boolean = { false }): Int { // Remember start and end position and then replace it with 'a' and 'z' val (startR, startC) = field.findPositionOf('S') field[startR][startC] = 'a' val (endR, endC) = field.findPositionOf('E') field[endR][endC] = 'z' // Record shortest distance to each val distance = mutableMapOf((endR to endC) to 0) // Here we will place blocks which we climbed down to. // Yes, we climb down instead of climb up - it is more suitable for Part 2 solution val queue = ArrayDeque<Pair<Int, Int>>() queue += endR to endC // And then, for each block we found, search the next block possible to step down while (queue.isNotEmpty()) { val (r, c) = queue.removeFirst() // We found the shortest path to the start point. Stop if (r == startR && c == startC) break // Check if we should stop earlier val char = field[r][c] if (shouldStop(char)) return distance.getValue(r to c) // For each neighbor for (neighbor in field.neighbors(r, c)) { // Check if we can climb down to the neighbor block // or, if this neighbor was not already checked before val (neighborR, neighborC) = neighbor if (char > field[neighborR][neighborC] + 1 || neighbor in distance) continue // Record distance to this neighbor distance[neighbor] = distance.getValue(r to c) + 1 // and add it to the queue to check its neighbors queue.addLast(neighbor) } } return distance.getValue(startR to startC) } // Search the given char position for O(N*M) time private fun Array<CharArray>.findPositionOf(char: Char): Pair<Int, Int> { for (r in indices) { for (c in first().indices) { if (this[r][c] == char) return r to c } } error("Given char not found!") } /** Creates sequence of neighbors around the given [r], [c] */ private fun Array<CharArray>.neighbors(r: Int, c: Int) = sequence { if (r > 0) yield(r - 1 to c) if (r < lastIndex) yield(r + 1 to c) if (c > 0) yield(r to c - 1) if (c < first().lastIndex) yield(r to c + 1) } private fun readInput(name: String) = readLines(name).map { it.toCharArray() }.toTypedArray()
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,976
advent-of-code
Apache License 2.0
src/Day11.kt
andrewgadion
572,927,267
false
{"Kotlin": 16973}
import java.util.LinkedList fun Long.isDivisible(other: Long) = this % other == 0L class Monkey(val inspect: Command, val divisor: Long, val ifTrueMonkey: Int, val ifFalseMonkey: Int) { private val items = LinkedList<Long>() var inspectCount = 0 private set fun addItem(item: Long) = items.add(item) fun run(allMonkeys: List<Monkey>, decreaseWorryLevel: (Long) -> Long) { while (items.isNotEmpty()) { val item = decreaseWorryLevel(inspect.run(items.poll())) inspectCount++ val monkey = if (item.isDivisible(divisor)) ifTrueMonkey else ifFalseMonkey allMonkeys[monkey].addItem(item) } } } class Command(val arg: Long?, val operation: (Long, Long) -> Long) { fun run(old: Long) = operation(old, arg ?: old) } fun parseCommand(command: String): Command { val (_, op, arg) = command.split("=")[1].trim().split(" ").map(String::trim) return Command( arg.takeIf { it != "old" }?.toLong(), when (op) { "+" -> Long::plus "*" -> Long::times else -> throw Exception("unknown operation") } ) } fun main() { fun parseMonkey(input: List<String>): Monkey { val items = input[1].substringAfter("Starting items:").split(",").map { it.trim().toLong() } val operation = parseCommand(input[2]) val divisor = input[3].substringAfter("divisible by").trim().toLong() val ifTrueMonkey = input[4].substringAfter("monkey").trim().toInt() val ifFalseMonkey = input[5].substringAfter("monkey").trim().toInt() return Monkey(operation, divisor, ifTrueMonkey, ifFalseMonkey).also { items.forEach(it::addItem) } } fun part1(input: List<String>): Long { val monkeys = input.chunked(7).map(::parseMonkey) repeat(20) { monkeys.forEach { it.run(monkeys) { v -> v / 3 } } } return monkeys.map { it.inspectCount }.sortedDescending().take(2).fold(1L, Long::times) } fun part2(input: List<String>): Long { val monkeys = input.chunked(7).map(::parseMonkey) val allDivisorsMultiplication = monkeys.fold(1L) { acc, cur -> acc * cur.divisor } repeat(10000) { monkeys.forEach { it.run(monkeys) { v -> v % allDivisorsMultiplication} } } return monkeys.map { it.inspectCount }.sortedDescending().take(2).fold(1L, Long::times) } val input = readInput("day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4d091e2da5d45a786aee4721624ddcae681664c9
2,472
advent-of-code-2022
Apache License 2.0
src/Day08.kt
tomoki1207
572,815,543
false
{"Kotlin": 28654}
import kotlin.math.min fun main() { fun withGrid(input: List<String>, operation: (Int, List<Int>, List<Int>, List<Int>, List<Int>) -> Unit) { val grid = input.map { line -> line.toList().map { it.digitToInt() } } val rowSize = grid.size val colSize = grid[0].size for (row in 0 until rowSize) { for (col in 0 until colSize) { val ups = if (row == 0) emptyList() else grid.take(row).map { it[col] }.reversed() val downs = if (row == rowSize - 1) emptyList() else grid.drop(row + 1).map { it[col] } val lefts = if (col == 0) emptyList() else grid[row].take(col).reversed() val rights = if (col == colSize - 1) emptyList() else grid[row].drop(col + 1) val tree = grid[row][col] operation(tree, ups, downs, lefts, rights) } } } fun part1(input: List<String>): Int { val visibleTrees = mutableListOf<Int>() withGrid(input) { tree, ups, downs, lefts, rights -> val visible = listOf(ups, downs, lefts, rights).any { direction -> direction.isEmpty() || direction.max() < tree } if (visible) { visibleTrees.add(tree) } } return visibleTrees.size } fun part2(input: List<String>): Int { val scores = mutableListOf<Int>() withGrid(input) { tree, ups, downs, lefts, rights -> listOf(ups, downs, lefts, rights) .map { direction -> direction.takeWhile { it < tree }.count().let { min(it + 1, direction.size) } } .fold(1) { cur, value -> cur * value } .let { scores.add(it) } } return scores.max() } 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
2ecd45f48d9d2504874f7ff40d7c21975bc074ec
2,018
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
StephenVinouze
572,377,941
false
{"Kotlin": 55719}
data class Square( val x: Int, val y: Int, val height: Int, val isStart: Boolean, val isEnd: Boolean, ) fun main() { fun Char.toHeight(): Int = when (this) { 'S' -> 0 'E' -> 26 else -> this - 'a' } fun List<String>.toSquares(): List<List<Square>> = mapIndexed { columnIndex, line -> line.toCharArray().toList().mapIndexed { rowIndex, char -> Square( x = rowIndex, y = columnIndex, height = char.toHeight(), isStart = char == 'S', isEnd = char == 'E', ) } } fun breadthFirstSearch( squares: List<List<Square>>, startSquare: Square, ): Int { val visitedSquares = mutableSetOf<Square>() val flattenSquares = squares.flatten() val endSquare = flattenSquares.first { it.isEnd } val toVisitSquares = mutableListOf(startSquare) val costs = MutableList(squares.size) { MutableList(squares.first().size) { 1000 } } costs[startSquare.y][startSquare.x] = 0 while (toVisitSquares.isNotEmpty()) { val visitedSquare = toVisitSquares.removeFirst() listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) .map { (diffY, diffX) -> (visitedSquare.y + diffY) to (visitedSquare.x + diffX) } .forEach { (neighborY, neighborX) -> flattenSquares .firstOrNull { it.y == neighborY && it.x == neighborX } ?.let { neighborSquare -> if (neighborSquare.height <= visitedSquare.height + 1) { costs[neighborY][neighborX] = minOf( costs[neighborY][neighborX], costs[visitedSquare.y][visitedSquare.x] + 1 ) if (neighborSquare !in toVisitSquares && neighborSquare !in visitedSquares) { toVisitSquares.add(neighborSquare) } } } } visitedSquares.add(visitedSquare) } return costs[endSquare.y][endSquare.x] } fun part1(input: List<String>): Int { val squares = input.toSquares() val startSquare = squares.flatten().first { it.isStart } return breadthFirstSearch(squares, startSquare) } fun part2(input: List<String>): Int { val squares = input.toSquares() val startSquares = squares.flatten().filter { it.height == 0 } return startSquares.minOf { breadthFirstSearch(squares, it) } } check(part1(readInput("Day12_test")) == 31) check(part2(readInput("Day12_test")) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
11b9c8816ded366aed1a5282a0eb30af20fff0c5
3,014
AdventOfCode2022
Apache License 2.0
src/Day13.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
fun <T : Comparable<T>> List<T>.compareTo(other: List<T>) = zip(other) .map { (a, b) -> a.compareTo(b) } .firstOrNull { it != 0 } ?: size.compareTo(other.size) fun <T : Comparable<T>> Iterable<T>.isSorted() = zipWithNext().all { (a, b) -> a < b } sealed interface Packet: Comparable<Packet> { companion object { val DIVIDERS = setOf( parsePacket("[[2]]"), parsePacket("[[6]]"), ) } } fun ListIterator<Char>.getNextInt(): Int { val value = asSequence().takeWhile(Char::isDigit).joinToString("").toInt() previous() return value } fun parseNextPacket(description: ListIterator<Char>): Packet = if (description.next() == '[') { ListPacket(parsePacketList(description)) } else { description.previous() NumPacket(description.getNextInt()) } fun parsePacketList(description: ListIterator<Char>): List<Packet> { if (description.next() == ']') { return emptyList() } description.previous() return buildList { add(parseNextPacket(description)) while (description.next() != ']') { add(parseNextPacket(description)) } } } fun parsePacket(description: String): Packet { val iter = description.toList().listIterator() val packet = parseNextPacket(iter) assert(!iter.hasNext()) return packet } class ListPacket(val values: List<Packet>): Packet { override fun compareTo(other: Packet) = when (other) { is ListPacket -> values.compareTo(other.values) is NumPacket -> values.compareTo(listOf(other)) } } class NumPacket(val value: Int): Packet { override fun compareTo(other: Packet) = when (other) { is NumPacket -> value.compareTo(other.value) is ListPacket -> listOf(this).compareTo(other.values) } } fun main() { val packetPairs = readInput("Day13") .split(String::isBlank) .map { it.map(::parsePacket) } println( packetPairs.mapIndexed { index, packets -> (index + 1) to packets }.filter { (_, packets) -> packets.isSorted() }.sumOf { (index, _) -> index } ) val packetList = packetPairs.flatten() + Packet.DIVIDERS println( packetList .sorted() .mapIndexed { index, packet -> (index + 1) to packet }.filter { (_, packet) -> packet in Packet.DIVIDERS }.productOf { (index, _) -> index } ) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
2,595
advent-of-code-2022
Apache License 2.0
src/Day03.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
data class Rucksack(val firstCompartment: String, val secondCompartment: String) data class RucksackGroup(val firstRucksack: String, val secondRucksack: String, val thirdRucksack: String) fun createRucksack(allTypes: String): Rucksack { val firstCompartment = allTypes.take(allTypes.length / 2) val secondCompartment = allTypes.takeLast(allTypes.length / 2) return Rucksack(firstCompartment, secondCompartment) } fun getCommonType(rucksack: Rucksack): Int { val commonChar = rucksack.firstCompartment.find { rucksack.secondCompartment.contains(it) } ?: throw IllegalArgumentException("This rucksack (${rucksack}) must contain a common type") return charToPriority(commonChar) } fun charToPriority(char: Char): Int { return if (char.isUpperCase()) char.code - 'A'.code + 27 else char.code - 'a'.code + 1 } fun getCommonType(rucksackGroup: RucksackGroup): Int { val commonChar = rucksackGroup.firstRucksack .find { rucksackGroup.secondRucksack.contains(it) && rucksackGroup.thirdRucksack.contains(it) } ?: throw IllegalArgumentException("This rucksack group (${rucksackGroup}) must contain a common type") return charToPriority(commonChar) } fun main() { fun part1(input: List<String>): Int { return input .map { createRucksack(it) } .sumOf { getCommonType(it) } } fun part2(input: List<String>): Int { return input.chunked(3) .map { RucksackGroup(it[0], it[1], it[2]) } .sumOf { getCommonType(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
1,842
advent-of-code-2022
Apache License 2.0
src/Day19.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
data class Blueprint( val ID: Int, val oreCost: Int, val clayCost: Int, val obsidianCost: Pair<Int, Int>, val geodeCost: Pair<Int, Int>, ) data class RobotNode( val ore: Int, val oreRobots: Int, val clay: Int, val clayRobots: Int, val obsidian: Int, val obsidianRobots: Int, val geodes: Int, val geodeRobots: Int, val minute: Int, ) class RobotGraph(val blueprint: Blueprint, val timeLimit: Int) : Graph<RobotNode> { override fun neighbors(node: RobotNode): List<Pair<Int, RobotNode>> { if (node.minute >= timeLimit) { return emptyList() } return buildList { if (node.ore >= blueprint.oreCost) { add(node.copy( ore = node.ore - blueprint.oreCost, oreRobots = node.oreRobots + 1 )) } if (node.ore >= blueprint.clayCost) { add(node.copy( ore = node.ore - blueprint.clayCost, clayRobots = node.clayRobots + 1 )) } if (node.ore >= blueprint.obsidianCost.first && node.clay >= blueprint.obsidianCost.second) { add(node.copy( ore = node.ore - blueprint.obsidianCost.first, clay = node.clay - blueprint.obsidianCost.second, obsidianRobots = node.obsidianRobots + 1 )) } if (node.ore >= blueprint.geodeCost.first && node.obsidian >= blueprint.geodeCost.second) { add(node.copy( ore = node.ore - blueprint.geodeCost.first, obsidian = node.obsidian - blueprint.geodeCost.second, geodeRobots = node.geodeRobots + 1 )) } add(node) }.map { neighbor -> (timeLimit - node.geodeRobots) to neighbor.copy( ore = neighbor.ore + node.oreRobots, clay = neighbor.clay + node.clayRobots, obsidian = neighbor.obsidian + node.obsidianRobots, geodes = neighbor.geodes + node.geodeRobots, minute = node.minute + 1 ) } } fun heuristic(node: RobotNode): Int { if (node.minute == timeLimit) { return 0 } val remainingTime = timeLimit - node.minute val first = timeLimit - node.geodeRobots val last = first - remainingTime + 1 return (first + last) * remainingTime / 2 } } fun main() { val blueprints = readInput("Day19") .parseAllInts() .map { Blueprint(it[0], it[1], it[2], it[3] to it[4], it[5] to it[6]) } val start = listOf(RobotNode( ore = 0, oreRobots = 1, clay = 0, clayRobots = 0, obsidian = 0, obsidianRobots = 0, geodes = 0, geodeRobots = 0, minute = 0, )) val sum = blueprints.sumOf{ blueprint -> val graph = RobotGraph(blueprint, 24) val (_, path) = `A*`(graph, start, { it.minute == graph.timeLimit }, graph::heuristic)!! blueprint.ID * path.last().geodes } println(sum) val product = blueprints.take(3).productOf { blueprint -> val graph = RobotGraph(blueprint, 32) val (_, path) = `A*`(graph, start, { it.minute == graph.timeLimit }, graph::heuristic)!! path.last().geodes } println(product) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
3,494
advent-of-code-2022
Apache License 2.0
src/Day18.kt
michaelYuenAE
573,094,416
false
{"Kotlin": 74685}
fun main() { data class Point(val x: Int, val y: Int, val z: Int) fun List<String>.parse(): Set<Point> { val pointRegex = "(\\d+),(\\d+),(\\d+)".toRegex() return this .mapNotNull { line -> pointRegex.matchEntire(line)?.groupValues } .map { gv -> Point(gv[1].toInt(), gv[2].toInt(), gv[3].toInt()) } .toSet() } fun Point.getAdjacent() = listOf( copy(x = x - 1), copy(x = x + 1), copy(y = y - 1), copy(y = y + 1), copy(z = z - 1), copy(z = z + 1), ) fun getSurrounding(points: Set<Point>): Set<Point> { val xRange = (points.minOf { it.x } - 1 .. points.maxOf { it.x } + 1) val yRange = (points.minOf { it.y } - 1 .. points.maxOf { it.y } + 1) val zRange = (points.minOf { it.z } - 1 .. points.maxOf { it.z } + 1) tailrec fun expand(surrounding: Set<Point>): Set<Point> { val newSurrounding = surrounding .flatMap { it.getAdjacent() + it } .filter { it.x in xRange && it.y in yRange && it.z in zRange && it !in points } .toSet() return if (surrounding.size == newSurrounding.size) { surrounding } else { expand(newSurrounding) } } val initialSurrounding = run { val boundaries = listOf( xRange.flatMap { x -> yRange.map { y -> Point(x, y, zRange.first) } }, xRange.flatMap { x -> yRange.map { y -> Point(x, y, zRange.last) } }, xRange.flatMap { x -> zRange.map { z -> Point(x, yRange.first, z) } }, xRange.flatMap { x -> zRange.map { z -> Point(x, yRange.last, z) } }, yRange.flatMap { y -> zRange.map { z -> Point(zRange.first, y, z) } }, yRange.flatMap { y -> zRange.map { z -> Point(zRange.last, y, z) } }, ) boundaries.flatten().toSet() } return expand(initialSurrounding) } fun part1(input: List<String>): Int { val points = input.parse() return points .flatMap { p -> p.getAdjacent().map { p2 -> (p to p2) } } .count { (_, p2) -> p2 !in points } } fun part2(input: List<String>): Int { val points = input.parse() val surrounding = getSurrounding(points) return points .flatMap { p -> p.getAdjacent().map { p2 -> (p to p2) } } .count { (_, p2) -> p2 in surrounding } } val input = readInput("day18_input") println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
ee521263dee60dd3462bea9302476c456bfebdf8
2,660
advent22
Apache License 2.0
src/Day07.kt
Jessenw
575,278,448
false
{"Kotlin": 13488}
data class Node<T>( val value: T, val children: MutableList<Node<T>> = mutableListOf() ) fun Node<Directory>.calculateSize(): Int = children.sumOf { it.calculateSize() } + value.fileSize() data class File( val name: String, val size: Int ) data class Directory( val name: String, val files: MutableList<File> = mutableListOf() ) { fun fileSize() = files.sumOf { it.size } } fun deleteCandidates( currentNode: Node<Directory>, limit: Int, list: MutableList<Int> = mutableListOf(), filter: (Int, Int) -> Boolean ) : List<Int> { val size = currentNode.calculateSize() if (filter(size, limit)) list.add(size) currentNode.children.forEach { deleteCandidates(it, limit, list, filter) } return list.toList() } fun buildTree(input: List<String>): Node<Directory> { val root = Node(Directory("/")) val currentPath = ArrayDeque<String>().also { it.add(root.value.name) } var inputIndex = 0 while (inputIndex in input.indices) { val currentLine = input[inputIndex] val tokens = currentLine.split(" ").toMutableList() // Commands begin with "$" if (tokens.first() == "$") { tokens.removeFirst() when(tokens.removeFirst()) { "cd" -> { when (val path = tokens.first()) { ".." -> currentPath.removeLast() "/" -> { } else -> currentPath.addLast(path) } inputIndex++ } "ls" -> { // Get all files output from ls (until we hit the next command) inputIndex++ // Skip to next line while(inputIndex < input.size && !input[inputIndex].contains("$")) { val lsSplit = input[inputIndex].split(" ") val currentDirectory = findDirectory(root, currentPath) if (lsSplit.first() == "dir") currentDirectory.children.add(Node(Directory(lsSplit[1]))) else currentDirectory.value.files.add(File(lsSplit[1], lsSplit[0].toInt())) inputIndex++ } } } } } return root } fun findDirectory(currentNode: Node<Directory>, path: MutableList<String>): Node<Directory> { val copiedPath = path.toMutableList() // Create a clone of the path val dirName = copiedPath.removeFirst() val nextNode = currentNode.children .firstOrNull { it.value.name == dirName } ?: currentNode return if (copiedPath.size == 0) nextNode else findDirectory(nextNode, copiedPath) } fun main() { fun part1(input: List<String>) = deleteCandidates(buildTree(input), 100000) { size, limit -> size <= limit }.sumOf { it } fun part2(input: List<String>): Int { val root = buildTree(input) // Storage required = update_size - (disk_space - space_used) val storageRequired = 30000000 - (70000000 - root.calculateSize()) return deleteCandidates(root, storageRequired) { size, limit -> size > limit }.minOf { it } } val testInput = readInputLines("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInputLines("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
05c1e9331b38cfdfb32beaf6a9daa3b9ed8220a3
3,580
aoc-22-kotlin
Apache License 2.0
2021/src/day14/day14.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day14 import java.io.File fun main() { val data = parseInput(File("src/day14", "day14input.txt").readLines()) var chain = data.first var rules = data.second for (i in 1..10) { chain = runStep(chain, rules) } println(getQuantityDifference(chain)) val countMap = runStepExtended(data.first, data.second, 40) with(countMap.values.sortedByDescending { it }) { println(first() - last()) } } fun parseInput(input: List<String>): Pair<String, Map<String, Char>> { with(input.filter { it.isNotBlank() } .partition { !it.contains(" -> ") }) { return Pair(first.first(), buildMap { second.forEach { with(it.split(" -> ")) { put(get(0), get(1).toCharArray().first()) } } }) } } fun runStep(chain: String, rules: Map<String, Char>): String { val insertionMap = mutableMapOf<Int, Char>() for ((index, window) in chain.windowed(2).withIndex()) { if (rules.contains(window)) { insertionMap[index + 1] = rules!![window] as Char } } // Now create a new string with the characters inserted val mutableChain = chain.toMutableList() for ((insertOffset, insertIndex) in insertionMap.keys.withIndex()) { insertionMap[insertIndex]?.let { mutableChain.add(insertIndex + insertOffset, it) } } return mutableChain.joinToString(separator = "", postfix = "") } fun getQuantityDifference(chain: String): Long { val grouped = chain.groupingBy { it }.fold(0L) { acc, _ -> acc + 1 } .entries.sortedByDescending { it.value } return grouped.first().value - grouped.last().value } /** * Runs the number of steps with the rules * @return Map of character to frequency */ fun runStepExtended(chain: String, rules: Map<String, Char>, steps: Int): Map<Char, Long> { val returnMap = chain.groupingBy { it }.fold(0L) { acc, _ -> acc + 1 }.toMutableMap() var pairCount = chain.windowed(2).groupingBy { it }.fold(0L) { acc, _ -> acc + 1 }.toMutableMap() (1..steps).forEach { _ -> val newPairCount = mutableMapOf<String, Long>() for (entry in pairCount.entries) { if (rules.contains(entry.key)) { val char = rules[entry.key]!! returnMap[char] = returnMap.getOrPut(char) { 0L } + (entry.value) for (newEntry in getEntries(char, entry.key)) { newPairCount[newEntry] = newPairCount.getOrDefault(newEntry, 0L) + entry.value } } else { newPairCount[entry.key] = newPairCount.getOrDefault(entry.key, 0L) + entry.value } } pairCount = newPairCount } return returnMap } fun getEntries(char: Char, pair: String): List<String> { return listOf(pair.substring(0, 1) + char, char + pair.substring(1, 2)) }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
2,958
adventofcode
Apache License 2.0
src/Day13.kt
Excape
572,551,865
false
{"Kotlin": 36421}
fun main() { fun findMatchingBracket(input: String): Int { var counter = 1 input.substring(1) .forEachIndexed { i, c -> when (c) { '[' -> counter++ ']' -> counter -- } if (counter == 0) return i + 1 } throw IllegalStateException("unbalanced brackets") } fun parseRecursively(input: String, list: MutableList<Any>) { if (input.isBlank()) { return } if (input.startsWith("[")) { val subList = mutableListOf<Any>() list.add(subList) val listEnd = findMatchingBracket(input) val content = input.substring(1 until listEnd) parseRecursively(content, subList) if (listEnd < input.lastIndex) { parseRecursively(input.substring(listEnd + 2), list) } } else if (input[0].isDigit()) { val nextComma = input.indexOf(',') val end = if (nextComma == -1) input.length else nextComma val number = input.substring(0 until end).toInt() list.add(number) if (nextComma == -1) { return } parseRecursively(input.substring(nextComma + 1), list) } } fun parsePackage(input: String): Any { val rootList = mutableListOf<Any>() parseRecursively(input, rootList) return rootList[0] } fun comparePackage(first: Any, second: Any): Int { return when { first is Int && second is Int -> first - second first is List<*> && second is List<*> -> (first zip second).map { comparePackage(it.first!!, it.second!!) } .firstOrNull { it != 0 } ?: (first.size - second.size) else -> if (first is Int) comparePackage(listOf(first), second) else comparePackage(first, listOf(second)) } } fun part1(input: String): Int { val pairs = input .split("\n\n") .map { it.split("\n").map { line -> parsePackage(line) } } return pairs .map { comparePackage(it[0], it[1]) } .map { it < 0 } .foldIndexed(0) { i, acc, isOrdered -> if (isOrdered) acc + i + 1 else acc } } fun part2(input: String): Int { val allInputPackages = input.split("\n") .filter { it.isNotBlank() } .map { parsePackage(it) } val divider1 = listOf(listOf(2)) val divider2 = listOf(listOf(6)) val allPackages = allInputPackages + listOf(divider1) + listOf(divider2) val sortedPackages = allPackages.sortedWith(::comparePackage) return (sortedPackages.indexOf(divider1) + 1) * (sortedPackages.indexOf(divider2) + 1) } val testInput = readInputAsString("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInputAsString("Day13") val part1Answer = part1(input) val part2Answer = part2(input) println("part 1: $part1Answer") println("part 2: $part2Answer") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
3,156
advent-of-code-2022
Apache License 2.0