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/Day15.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | import kotlin.math.abs
data class Beacon(val x: Int, val y: Int) {
fun toTuningFrequency(): Long = x * 4_000_000L + y
}
data class Sensor(val x: Int, val y: Int, val closestBeacon: Beacon) {
fun intoRange(yLine: Int): IntRange {
val distance = abs(x - closestBeacon.x) + abs(y - closestBeacon.y)
val xRange = distance - abs(y - yLine)
return x - xRange..x + xRange
}
companion object {
fun of(string: String): Sensor {
val (_, strX, strY, strBeaconX, strBeaconY) =
Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
.matchEntire(string)!!.groupValues
return Sensor(strX.toInt(), strY.toInt(), Beacon(strBeaconX.toInt(), strBeaconY.toInt()))
}
}
}
fun main() {
val day = 15
fun prepareInput(input: List<String>) = input.map { Sensor.of(it) }
fun <T> MutableMap<T, Int>.addSafe(key: T, add: Int) {
this[key] = this.getOrDefault(key, 0) + add
}
fun List<IntRange>.intersection(): Int {
val mapPositions = sortedMapOf<Int, Int>()
for (range in this) {
mapPositions.addSafe(range.first, 1)
mapPositions.addSafe(range.last, -1)
}
var intersectionLength = 0
var balance = 0
var previousIndex: Int? = null
for ((index, balanceAdd) in mapPositions) {
if (previousIndex == null)
previousIndex = index
if (balance > 0)
intersectionLength += index - previousIndex!!
balance += balanceAdd
previousIndex = index
}
return intersectionLength
}
fun List<IntRange>.findEmptyCell(possiblePositions: IntRange): Int? {
val mapPositions = sortedMapOf<Int, Int>()
for (range in this) {
mapPositions.addSafe(range.first, 1)
mapPositions.addSafe(range.last + 1, -1)
}
mapPositions.addSafe(possiblePositions.first, 0)
mapPositions.addSafe(possiblePositions.last, 0)
var balance = 0
for ((index, balanceAdd) in mapPositions) {
balance += balanceAdd
if (balance == 0 && index in possiblePositions)
return index
}
return null
}
fun part1(input: List<String>, searchY: Int): Int {
val sensors = prepareInput(input)
val ranges = sensors.map { it.intoRange(searchY) }.filterNot { it.isEmpty() }
return ranges.intersection()
}
fun part2(input: List<String>, rangeX: IntRange, rangeY: IntRange): Long {
val sensors = prepareInput(input)
for (searchY in rangeY) {
val xPosition = sensors.map { it.intoRange(searchY) }.filterNot { it.isEmpty() }.findEmptyCell(rangeX)
if (xPosition != null)
return Beacon(xPosition, searchY).toTuningFrequency()
}
return 0L
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day}_test")
check(part1(testInput, 10) == 26)
check(part2(testInput, 0..20, 0..20) == 56000011L)
val input = readInput("Day${day}")
println(part1(input, 2000000))
println(part2(input, 0..4_000_000, 0..4_000_000))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 3,299 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/year2023/Day7.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2023
import readLines
fun main() {
val input = parseInput(readLines("2023", "day7"))
val testInput = parseInput(readLines("2023", "day7_test"))
check(CamelCards("T55J5", 0).cardType(false) == 4)
check(CamelCards("T55J5", 0).cardType(true) == 6)
check(CamelCards("KTJJT", 0).cardType(false) == 3)
check(CamelCards("KTJJT", 0).cardType(true) == 6)
check(CamelCards("QQQJA", 0).cardType(false) == 4)
check(CamelCards("QQQJA", 0).cardType(true) == 6)
check(part1(testInput) == 6440)
println("Part 1:" + part1(input))
check(part2(testInput) == 5905)
println("Part 2:" + part2(input))
}
private fun parseInput(lines: List<String>): List<CamelCards> {
return lines
.map { it.split(" ") }
.map { splittedLine -> CamelCards(splittedLine[0], splittedLine[1].toInt()) }
}
private fun part1(input: List<CamelCards>): Int {
fun cardStrength(char: Char): Int = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2').indexOf(char)
val comparator: Comparator<CamelCards> =
compareByDescending<CamelCards> { it.cardType(false) }
.thenBy { cardStrength(it.cards[0]) }
.thenBy { cardStrength(it.cards[1]) }
.thenBy { cardStrength(it.cards[2]) }
.thenBy { cardStrength(it.cards[3]) }
.thenBy { cardStrength(it.cards[4]) }
val cardsByRang = input.sortedWith(comparator).reversed()
return cardsByRang.mapIndexed { index, camelCard -> (index + 1) * camelCard.bid }.sum()
}
private fun part2(input: List<CamelCards>): Int {
fun cardStrength(char: Char): Int = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J').indexOf(char)
val comparator: Comparator<CamelCards> =
compareByDescending<CamelCards> { it.cardType(true) }
.thenBy { cardStrength(it.cards[0]) }
.thenBy { cardStrength(it.cards[1]) }
.thenBy { cardStrength(it.cards[2]) }
.thenBy { cardStrength(it.cards[3]) }
.thenBy { cardStrength(it.cards[4]) }
val cardsByRang = input.sortedWith(comparator).reversed()
return cardsByRang.mapIndexed { index, camelCard -> (index + 1) * camelCard.bid }.sum()
}
private data class CamelCards(val cards: String, val bid: Int) {
fun cardType(jokerEnabled: Boolean): Int {
val groupCountBySameLabel = cards.toCharArray().groupBy { it }.mapValues { it.value.size }
val numberOfJokers = groupCountBySameLabel.getOrDefault('J', 0)
val jokersHaveToBeConsidered = jokerEnabled && numberOfJokers > 0
val fiveOfAKind = groupCountBySameLabel.size == 1
val groupSizes =
if (jokersHaveToBeConsidered && !fiveOfAKind) {
val groups = groupCountBySameLabel.filter { it.key != 'J' }.values.sortedDescending().toMutableList()
groups[0] += numberOfJokers
groups
} else {
groupCountBySameLabel.values.sortedDescending()
}
return when {
groupSizes == listOf(5) -> 7
groupSizes == listOf(4, 1) -> 6
groupSizes == listOf(3, 2) -> 5
groupSizes == listOf(3, 1, 1) -> 4
groupSizes == listOf(2, 2, 1) -> 3
groupSizes.contains(2) -> 2
else -> 1
}
}
}
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 3,346 | advent_of_code | MIT License |
src/Day02.kt | pmatsinopoulos | 730,162,975 | false | {"Kotlin": 10493} | // I need to parse one line and retrieve the following information:
// Game index
// Number of Sets
// For Each Set the number of blue, red, and green cubes
// All sets in a game should be possible for the game to be possible.
//
enum class Color {
RED,
GREEN,
BLUE
}
data class SetOfCubes(
val numbersForColors: MutableMap<Color, Int> = mutableMapOf() // e.g. RED -> 4, GREEN -> 5, BLUE -> 6
) {
fun possible(input: Input): Boolean = numbersForColors.getOrDefault(Color.RED, 0) <= input.red &&
numbersForColors.getOrDefault(Color.GREEN, 0) <= input.green &&
numbersForColors.getOrDefault(Color.BLUE, 0) <= input.blue
fun powerOfColor(color: Color): Int = numbersForColors.getOrDefault(color, 1)
companion object {
fun build(input: String): SetOfCubes {
val numbersForColors = input.split(",").map { it.trim() }
val setOfCubes = numbersForColors.fold(SetOfCubes()) { acc, numberForColor ->
val (number, color) = numberForColor.split(" ").map { it.trim() }
acc.numbersForColors[Color.valueOf(color.uppercase())] = number.toInt()
acc
}
return setOfCubes
}
}
}
data class Game(
val index: Int,
val sets: List<SetOfCubes>
) {
fun possible(input: Input): Boolean = sets.all { set -> set.possible(input) }
fun power(): Int =
maxPowerOfColor(Color.RED) * maxPowerOfColor(Color.GREEN) * maxPowerOfColor(Color.BLUE)
private fun maxPowerOfColor(color: Color): Int = sets.map { set -> set.powerOfColor(color) }.max()
companion object {
fun build(input: String): Game {
val (game, setsString) = input.split(":").map { it.trim() }
val gameIndex = game.replace("Game ", "").toInt()
val sets = setsString.split(";").map { set -> set.trim() }
val setsOfCubes = sets.map { s -> SetOfCubes.build(s) }
return Game(index = gameIndex, sets = setsOfCubes)
}
}
}
data class Input(
val red: Int,
val green: Int,
val blue: Int
)
fun main() {
val input = Input(red = 12, green = 13, blue = 14)
val resultPart1 = readInput("Day02").sumOf { inputGame ->
val game = Game.build(inputGame)
if (game.possible(input)) {
game.index
} else {
0
}
}
println("part 1 result = $resultPart1") // Should be 2447
val resultPart2 = readInput("Day02").sumOf { inputGame ->
val game = Game.build(inputGame)
game.power()
}
print("part 2 result = $resultPart2") // Should be 56322
}
| 0 | Kotlin | 0 | 0 | f913207842b2e6491540654f5011127d203706c6 | 2,643 | advent-of-code-kotlin-template | Apache License 2.0 |
src/year2023/day02/Day02.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day02
import check
import readInput
fun main() {
val testInput = readInput("2023", "Day02_test")
check(part1(testInput), 8)
check(part2(testInput), 2286)
val input = readInput("2023", "Day02")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.map { it.parseGame() }
.filter { it.isValid() }
.sumOf { it.id }
private fun Game.isValid() = combinations.all { it.red <= 12 && it.green <= 13 && it.blue <= 14 }
private fun part2(input: List<String>) = input.map { it.parseGame() }
.sumOf { game ->
val maxRed = game.combinations.maxOf { it.red }
val maxGreen = game.combinations.maxOf { it.green }
val maxBlue = game.combinations.maxOf { it.blue }
maxRed * maxGreen * maxBlue
}
private data class Game(
val id: Int,
val combinations: List<Combination>,
)
private data class Combination(
val red: Int,
val green: Int,
val blue: Int,
)
private fun String.parseGame(): Game {
val (gameString, rounds) = split(": ")
val combinations = rounds.split("; ").map { round ->
val cubesByColor = round.split(", ").associate { c ->
val (n, color) = c.split(" ")
color to n.toInt()
}
Combination(
red = cubesByColor["red"] ?: 0,
green = cubesByColor["green"] ?: 0,
blue = cubesByColor["blue"] ?: 0,
)
}
return Game(
id = gameString.substringAfterLast(" ").toInt(),
combinations = combinations,
)
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,568 | AdventOfCode | Apache License 2.0 |
src/Day02.kt | mcdimus | 572,064,601 | false | {"Kotlin": 32343} | import util.readInput
fun main() {
fun part1(input: List<String>) = input.asSequence()
.map { it.split(' ') }
.map { RPSType.of(it[0].single()) to RPSType.of(it[1].single()) }
.map { (opponentSign, mySign) -> mySign to mySign.match(opponentSign) }
.map { (mySign, result) -> mySign.score + result.score }
.sum()
fun part2(input: List<String>) = input.asSequence()
.map { it.split(' ') }
.map { RPSType.of(it[0].single()) to RPSResult.of(it[1].single()) }
.map { (opponentSign, expectedResult) -> opponentSign.match(expectedResult) to expectedResult }
.map { (mySign, result) -> mySign.score + result.score }
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
private enum class RPSType(val score: Int, private vararg val chars: Char) {
ROCK(score = 1, 'A', 'X') {
override val winsAgainst by lazy { SCISSORS }
},
PAPER(score = 2, 'B', 'Y') {
override val winsAgainst by lazy { ROCK }
},
SCISSORS(score = 3, 'C', 'Z') {
override val winsAgainst by lazy { PAPER }
};
companion object {
fun of(char: Char) = values().single { it.chars.contains(char) }
}
abstract val winsAgainst: RPSType
fun match(other: RPSType) = when {
this == other -> RPSResult.DRAW
this.winsAgainst == other -> RPSResult.WIN
else -> RPSResult.LOSE
}
fun match(result: RPSResult) = when (result) {
RPSResult.LOSE -> this.winsAgainst
RPSResult.DRAW -> this
RPSResult.WIN -> RPSType.values().single { it.winsAgainst == this }
}
}
private enum class RPSResult(val score: Int, private val char: Char) {
WIN(6, 'Z'),
DRAW(3, 'Y'),
LOSE(0, 'X');
companion object {
fun of(char: Char) = values().single { it.char == char }
}
}
| 0 | Kotlin | 0 | 0 | dfa9cfda6626b0ee65014db73a388748b2319ed1 | 2,079 | aoc-2022 | Apache License 2.0 |
src/Day11.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun part1(monkeys: List<Monkey>): Long {
val rounds = 20
repeat(rounds) { _ ->
monkeys.sortedBy { it.id }.forEach { monkey ->
while (monkey.worryLevels.isNotEmpty()) {
val (item, id) = monkey.inspectNext { it / 3 }
monkeys.firstOrNull { it.id == id }?.apply { receive(item) }
?: error("Monkey with $id id not found")
}
}
}
return monkeys.map { it.inspectCount }.sortedDescending().take(2).reduce { acc, elem -> acc * elem }
}
fun part2(monkeys: List<Monkey>): Long {
val rounds = 10_000
val stress = monkeys.map { it.testNumber }.reduce(Long::times)
repeat(rounds) { _ ->
monkeys.sortedBy { it.id }.forEach { monkey ->
while (monkey.worryLevels.isNotEmpty()) {
val (item, id) = monkey.inspectNext { it % stress }
monkeys.firstOrNull { it.id == id }?.apply { receive(item) }
?: error("Monkey with $id id not found")
}
}
}
return monkeys.map { it.inspectCount }.sortedDescending().take(2).reduce(Long::times)
}
fun parse(stringList: List<String>): List<Monkey> {
return stringList.windowed(6, 7).map { line -> line.map { it.trim() } }.map { monkeyLines ->
val id = monkeyLines[0].removeSuffix(":").split(" ").last().toInt()
val worryLevels = monkeyLines[1].substring(monkeyLines[1].indexOfFirst { it == ':' } + 1)
.split(", ")
.map { it.trim().toLong() }
val (arg1, op, arg2) = monkeyLines[2].split(" ").takeLast(3)
val levelChange = { level: Long ->
val operand1 = if (arg1 == "old") level else arg1.toLong()
val operand2 = if (arg2 == "old") level else arg2.toLong()
when (op) {
"*" -> operand1 * operand2
"+" -> operand1 + operand2
else -> error("Operation for $op not defined")
}
}
val testNum = monkeyLines[3].split(" ").last().toLong()
val testTrue = monkeyLines[4].split(" ").last().toInt()
val testFalse = monkeyLines[5].split(" ").last().toInt()
val next = { level: Long -> if (level % testNum == 0L) testTrue else testFalse }
Monkey(id, worryLevels.toMutableList(), levelChange, next, testNum)
}
}
val testInput = readInput("Day11_test")
check(part1(parse(testInput)) == 10_605L)
check(part2(parse(testInput)) == 2_713_310_158)
val input = readInput("Day11_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
class Monkey(
val id: Int,
var worryLevels: MutableList<Long>,
private val levelChange: (Long) -> Long,
val next: (Long) -> Int,
val testNumber: Long
) {
var inspectCount = 0L
fun inspectNext(reliefFunc: (Long) -> Long): Pair<Long, Int> {
val item = reliefFunc(levelChange(worryLevels.removeFirst()))
inspectCount += 1
return item to next(item)
}
fun receive(item: Long) {
worryLevels.add(item)
}
} | 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 3,274 | aoc-2022 | Apache License 2.0 |
archive/2022/Day13.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 13
private const val EXPECTED_2 = 140
fun parse(data: String): Any {
if (data[0] != '[') {
return data.toInt()
}
var nesting = 0
var lastIndex = 1
return buildList {
for ((i, ch) in data.withIndex()) {
when (ch) {
'[' -> nesting++
']' -> nesting--
',' -> if (nesting == 1) {
add(parse(data.substring(lastIndex, i)))
lastIndex = i + 1
}
}
}
check(nesting == 0)
if (lastIndex < data.length - 1) {
add(parse(data.substring(lastIndex, data.length - 1)))
}
}
}
fun compare(a: Any?, b: Any?): Int {
if (a is Int && b is Int) {
return a - b
}
val left = if (a is Int) listOf(a) else a as List<*>
val right = if (b is Int) listOf(b) else b as List<*>
return left.zip(right, ::compare).firstOrNull { it != 0 } ?: (left.size - right.size)
}
private class Day13(isTest: Boolean) : Solver(isTest) {
fun part1(): Any {
val parts = readAsString().split("\n\n").map { it.split("\n") }
return parts.withIndex().sumOf { (index, lines) ->
val (a, b) = lines.map(::parse)
if (compare(a, b) < 0) index + 1 else 0
}
}
fun part2(): Any {
val a = listOf(listOf(2))
val b = listOf(listOf(6))
val all = (listOf(a, b) + readAsLines().filter { it.trim().isNotEmpty() }.map(::parse)).sortedWith(::compare)
return (all.indexOf(a) + 1) * (all.indexOf(b) + 1)
}
}
fun main() {
val testInstance = Day13(true)
val instance = Day13(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,981 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | import java.util.PriorityQueue
import kotlin.math.abs
fun main() {
println(Day15.solvePart1())
println(Day15.solvePart2())
}
object Day15 {
private val risks = readInput("day15").map { it.map(Char::digitToInt) }
fun solvePart1() = findMinRisk(risks)
fun solvePart2() = findMinRisk(tile(risks, 5))
private fun findMinRisk(risks: List<List<Int>>): Int {
val start = Point(0, 0)
val end = Point(risks.lastIndex, risks.first().lastIndex)
val cameFrom = mutableMapOf<Point, Point>()
val gscore = mutableMapOf(start to 0)
val fscore = mutableMapOf(start to manhattanDist(start, end))
val frontier = PriorityQueue<Point> { a, b -> manhattanDist(b, end) compareTo manhattanDist(a, end) }
frontier.add(start)
fun Point.adjacent() = listOf(
Point(x - 1, y),
Point(x + 1, y),
Point(x, y - 1),
Point(x, y + 1)
).filter { it.x in 0..end.x && it.y in 0..end.y }
while (frontier.isNotEmpty()) {
val cur = frontier.poll()
if (cur == end) {
return pathRisk(end, risks, cameFrom)
}
cur.adjacent().forEach { neighbour ->
val tentativeGscore = gscore[cur]!! + risks[neighbour.x][neighbour.y]
if (tentativeGscore < (gscore[neighbour] ?: Int.MAX_VALUE)) {
cameFrom[neighbour] = cur
gscore[neighbour] = tentativeGscore
fscore[neighbour] = tentativeGscore + manhattanDist(neighbour, end)
frontier.remove(neighbour)
frontier.add(neighbour)
}
}
}
error("xoxoxo")
}
private fun pathRisk(end: Point, risks: List<List<Int>>, cameFrom: Map<Point, Point>): Int {
var risk = 0
var n: Point? = end
while (n != null) {
risk += risks[n.x][n.y]
n = cameFrom[n]
}
return risk - risks[0][0]
}
private fun tile(src: List<List<Int>>, tiles: Int): List<List<Int>> {
val tmp = src.map { list ->
(0 until tiles).flatMap { tile ->
list.map { addRisk(it, tile) }
}
}
return (0 until tiles).flatMap { tile ->
tmp.map { list ->
list.map { addRisk(it, tile) }
}
}
}
private fun addRisk(a: Int, b: Int) = (a + b).let {
if (it > 9) it - 9 else it
}
private fun manhattanDist(a: Point, b: Point) = abs(a.x - b.x) + abs(a.y - b.y)
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 2,602 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
2015/Day09/src/main/kotlin/Main.kt | mcrispim | 658,165,735 | false | null | import java.io.File
class Graph(input: List<String>) {
data class Edge(val from: String, val to: String, val distance: Int)
var nodes = mutableSetOf<String>()
var shortestEdge: Edge? = null
val edges = mutableMapOf<String, List<Edge>>()
init {
input.forEach {
val (city1, _, city2, _, distanceStr) = it.split(" ")
val distance = distanceStr.toInt()
nodes += city1
nodes += city2
val edge1 = Edge(city1, city2, distance)
val edge2 = Edge(city2, city1, distance)
edges[city1] = edges.getOrDefault(city1, emptyList()) + edge1
edges[city2] = edges.getOrDefault(city2, emptyList()) + edge2
if (shortestEdge == null || edge1.distance < shortestEdge!!.distance) {
shortestEdge = edge1
}
}
}
fun traverseLongeststPath(): Int {
var longestDistance = Int.MIN_VALUE
for(startCity in nodes) {
var distance = 0
var thisNode = startCity
val citiesVisited = mutableSetOf<String>(thisNode)
while (citiesVisited.size < nodes.size) {
val nextEdge = edges[thisNode]!!.filter { !citiesVisited.contains(it.to) }.maxByOrNull { it.distance }!!
distance += nextEdge.distance
citiesVisited += nextEdge.to
thisNode = nextEdge.to
}
if (distance > longestDistance) {
longestDistance = distance
}
}
return longestDistance
}
fun traverseShortestPath(): Int {
var shortestDistance = Int.MAX_VALUE
for(startCity in nodes) {
var distance = 0
var thisNode = startCity
val citiesVisited = mutableSetOf<String>(thisNode)
while (citiesVisited.size < nodes.size) {
val nextEdge = edges[thisNode]!!.filter { !citiesVisited.contains(it.to) }.minByOrNull { it.distance }!!
distance += nextEdge.distance
citiesVisited += nextEdge.to
thisNode = nextEdge.to
}
if (distance < shortestDistance) {
shortestDistance = distance
}
}
return shortestDistance
}
}
fun main() {
fun part1(input: List<String>): Int {
val graph = Graph(input)
return graph.traverseShortestPath()
}
fun part2(input: List<String>): Int {
val graph = Graph(input)
return graph.traverseLongeststPath()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 605)
check(part2(testInput) == 982)
val input = readInput("Day09_data")
println("Part 1 answer: ${part1(input)}")
println("Part 2 answer: ${part2(input)}")
}
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
| 0 | Kotlin | 0 | 0 | 2f4be35e78a8a56fd1e078858f4965886dfcd7fd | 3,019 | AdventOfCode | MIT License |
src/Day12.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | const val BIG = 100_000_000_000
fun main() {
fun parsed(lines: List<String>): List<List<Int>> =
lines.map { line ->
line.map {
when (it) {
'S' -> -1
'E' -> 26
else -> it - 'a'
}
}
}
fun List<List<Long>>.printMap() {
this.forEach { line ->
line.map { if (it == BIG) 0 else it }
.joinToString(",")
.println()
}
print('\n')
}
infix fun Pair<Int, Int>.inside(maxIndices: Pair<Int, Int>): Boolean =
(first in (0 until maxIndices.first)) and (second in (0 until maxIndices.second))
fun <T> MutableList<MutableList<T>>.replace(point: Pair<Int, Int>, item: T) {
this[point.first].removeAt(point.second)
this[point.first].add(point.second, item)
}
fun MutableList<MutableList<Long>>.dfs(heightBoard: List<List<Int>>, point: Pair<Int, Int>, dist: Long, endValue: Int = -1) {
// println("cur: $point, dist: $dist, here: ${this[point]}")
// this.printMap()
val here = this[point]
if (dist < here) {
replace(point, dist)
} else return
if (heightBoard[point] == endValue) return
listOf(
Pair(point.first - 1, point.second),
Pair(point.first + 1, point.second),
Pair(point.first, point.second - 1),
Pair(point.first, point.second + 1),
).filter { it inside (this.size to this[0].size) }
.filter { heightBoard[it] + 1 >= heightBoard[point] }
.filter { dist + 1 < this[it] }
.forEach { dfs(heightBoard, it, dist + 1, endValue) }
}
fun List<List<Number>>.findPoint(number: Number): Pair<Int, Int> {
val i = indexOfFirst { line -> line.contains(number) }
val j = this[i].indexOf(number)
return Pair(i, j)
}
fun getDists(board: List<List<Int>>, endValue: Int = -1): List<List<Long>> {
val end = board.findPoint(26)
val dists = (board.indices).map {
(board[0].indices).map { BIG }.toMutableList()
}.toMutableList()
dists.dfs(board, end, 0, endValue)
return dists
}
fun part1(input: List<String>): Int {
val board = parsed(input)
val start = board.findPoint(-1)
val dists = getDists(board)
return dists[start].toInt()
}
fun part2(input: List<String>): Int {
val board = parsed(input)
val dists = getDists(board, 0)
var minDist = BIG
dists.indices.forEach { i ->
dists[0].indices.forEach { j ->
run {
Pair(i, j).let {
if (board[it] == 0 && dists[it] < minDist) {
minDist = dists[it]
}
}
}
}
}
return minDist.toInt()
}
val testInput = readInput("Day12_test")
checkEquals(part1(testInput), 31)
checkEquals(part2(testInput), 29)
val input = readInput("Day12")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 3,196 | advent-of-code-kotlin | Apache License 2.0 |
src/Day08.kt | Miguel1235 | 726,260,839 | false | {"Kotlin": 21105} | private fun createNodes(input: List<String>): Map<String, Pair<String, String>> {
val nodeRegex = Regex("""[A-Z0-9]+""")
val nodes: MutableMap<String, Pair<String, String>> = mutableMapOf()
for (i in 2..<input.size) {
val results = nodeRegex.findAll(input[i])
val (name, left, right) = results.map { it.value }.toList()
nodes[name] = Pair(left, right)
}
return nodes
}
private fun part1(
nodes: Map<String, Pair<String, String>>,
instructions: Sequence<Char>,
start: String,
onlyLast: Boolean
): Int {
var curr = start
val target = "ZZZ"
var node = nodes[start]
var steps = 0
for (instruction in instructions) {
if (!onlyLast && curr == target) break
if (onlyLast && curr.endsWith('Z')) break
if (instruction == 'L') curr = node!!.first
if (instruction == 'R') curr = node!!.second
node = nodes[curr]
steps++
}
return steps
}
fun findLCM(n1: Long, n2: Long): Long {
val steps = if (n1 > n2) n1 else n2
val maxLcm = (n1 * n2)
var lcm = steps
while (lcm <= maxLcm) {
if (lcm % n1 == 0L && lcm % n2 == 0L) return lcm
lcm += steps
}
return maxLcm
}
fun findLCMS(numbers: List<Long>): Long {
var result: Long = numbers[0]
for (i in 1 until numbers.size) result = findLCM(result, numbers[i])
return result
}
private fun part2(nodes: Map<String, Pair<String, String>>, instructions: Sequence<Char>): Long {
val startingNodes = nodes.filter { n -> n.key.endsWith('A') }
val steps: List<Long> = mutableListOf()
for (startNode in startingNodes) {
steps.addLast(part1(nodes, instructions, startNode.key, true).toLong())
}
return findLCMS(steps)
}
private fun createInstructions(instructions: String): Sequence<Char> {
return sequence { while (true) instructions.forEach { char -> yield(char) } }
}
fun main() {
val testInput = readInput("Day08_test")
val testNodes = createNodes(testInput)
val testInstructions = createInstructions(testInput[0])
// check(part1(testNodes, testInstructions) == 2)
part2(testNodes, testInstructions)
val input = readInput("Day08")
val nodes = createNodes(input)
val instructions = createInstructions(input[0])
check(part1(nodes, instructions, "AAA", false) == 18023)
check(part2(nodes, instructions) == 14449445933179)
}
| 0 | Kotlin | 0 | 0 | 69a80acdc8d7ba072e4789044ec2d84f84500e00 | 2,411 | advent-of-code-2023 | MIT License |
src/Day07.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 6440
private const val EXPECTED_2 = 5905
private class Day07(isTest: Boolean) : Solver(isTest) {
var withJokers = false
val order
get() = if(withJokers) listOf("A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J")
else listOf("A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2")
inner class Hand(val cards: String) {
fun typeScore(): Int {
val same = if (withJokers) {
val jokerCount = cards.count { it == 'J' }
val same = cards.filter { it != 'J' }.groupBy { it }.map { it.value.size }
.sortedDescending().toMutableList()
if (same.size == 0) {
listOf(jokerCount)
} else {
same.also { it[0] += jokerCount }
}
} else {
cards.groupBy { it }.map { it.value.size }.sortedDescending()
}
return if (same.size == 1) {
20
} else if (same.size == 2) {
if (same[0] == 4) {
19
} else {
18
}
} else if (same.size == 3) {
if (same[0] == 3) {
17 // 3 of a k
} else {
16 // 2 pair
}
} else if (same.size ==4) {
15 // pair
} else {
14 // high card
}
}
val orderScore by lazy {
var sum = 0
for (ch in cards) {
sum *= 20
sum += 20 - order.indexOf(ch.toString())
}
sum + typeScore() * 5_000_000
}
}
fun rankScore(): Int {
val hands = readAsLines().map { it.split(" ").let { Hand(it[0]) to it[1].toInt() } }
val sorted = hands.sortedBy { it.first.orderScore }
var sum = 0
for ((index, hb) in sorted.withIndex()) {
sum += hb.second * (index+1)
}
return sum
}
fun part1(): Any {
withJokers = false
return rankScore()
}
fun part2(): Any {
withJokers = true
return rankScore()
}
}
fun main() {
val testInstance = Day07(true)
val instance = Day07(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 2,644 | advent-of-code-2022 | Apache License 2.0 |
lib/src/main/kotlin/aoc/day08/Day08.kt | Denaun | 636,769,784 | false | null | package aoc.day08
import aoc.AocGrammar
import com.github.h0tk3y.betterParse.combinators.use
import com.github.h0tk3y.betterParse.grammar.parseToEnd
import kotlin.math.max
fun part1(input: String): Int = countAllVisible(parse(input))
fun part2(input: String): Int = bestScenicScore(parse(input))
object Day08Grammar : AocGrammar<List<List<Int>>>() {
override val rootParser by lineList(numberToken use { text.map { it.digitToInt() } })
}
fun parse(data: String): List<List<Int>> = Day08Grammar.parseToEnd(data)
fun countAllVisible(trees: List<List<Int>>): Int {
val rows = trees.size
val columns = trees[0].size
val visibleDirections = List(rows) { MutableList(columns) { false } }
for ((i, row) in trees.withIndex()) {
for ((j, isVisible) in visibleTrees(row).withIndex()) {
visibleDirections[i][j] = visibleDirections[i][j] || isVisible
}
for ((j, isVisible) in visibleTrees(row.reversed()).reversed().withIndex()) {
visibleDirections[i][j] = visibleDirections[i][j] || isVisible
}
}
for (j in 0 until columns) {
val column = trees.map { it[j] }
for ((i, isVisible) in visibleTrees(column).withIndex()) {
visibleDirections[i][j] = visibleDirections[i][j] || isVisible
}
for ((i, isVisible) in visibleTrees(column.reversed()).reversed().withIndex()) {
visibleDirections[i][j] = visibleDirections[i][j] || isVisible
}
}
return visibleDirections.sumOf { row -> row.count { it } }
}
fun visibleTrees(trees: Iterable<Int>): List<Boolean> =
trees.runningFold(Int.MIN_VALUE, ::max).windowed(2, 1)
.map { (first, second) -> first != second }
fun bestScenicScore(trees: List<List<Int>>): Int = trees.indices.maxOf { row ->
trees[row].indices.maxOf { column -> scenicScore(row, column, trees) }
}
fun scenicScore(row: Int, column: Int, trees: List<List<Int>>): Int {
val rows = trees.size
val columns = trees[row].size
val height = trees[row][column]
val leftEdge = (0 until column).lastOrNull { trees[row][it] >= height } ?: 0
val rightEdge =
(column + 1 until columns).firstOrNull { trees[row][it] >= height } ?: (columns - 1)
val upEdge = (0 until row).lastOrNull { trees[it][column] >= height } ?: 0
val downEdge = (row + 1 until rows).firstOrNull { trees[it][column] >= height } ?: (rows - 1)
val left = column - leftEdge
val right = rightEdge - column
val up = row - upEdge
val down = downEdge - row
return left * right * up * down
} | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 2,568 | aoc-2022 | Apache License 2.0 |
src/Day18.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun pts(): List<C3> {
return readInput("Day18").map { it.split(",").map(String::toInt) }.map { C3(it[0], it[1], it[2]) }
.also { ptsSet = HashSet(it) }
}
lateinit var ptsSet: HashSet<C3>
private fun part1(pts: List<C3>): Int {
val total = pts.size * 6
val covered = pts.sumOf { p -> getAdjacent(p).count { ptsSet.contains(it) } }
return total - covered
}
var xBounds = 0..19
var yBounds = 1..19
var zBounds = 0..19
private fun part2(pts: List<C3>): Int {
val trapped = HashMap<C3, Boolean>()
for (x in xBounds) {
for (y in yBounds) {
for (z in zBounds) {
val p = C3(x, y, z)
if (ptsSet.contains(p) || trapped.contains(p)) continue
markTrapped(p, checkTrapped(p), trapped)
}
}
}
val total = pts.size * 6
val coveredOrTrapped = pts.sumOf { p ->
getAdjacent(p).filter { withinBounds(it) }.count { ptsSet.contains(it) || trapped[it]!! }
}
return total - coveredOrTrapped
}
private fun withinBounds(p: C3) = xBounds.contains(p.x) && yBounds.contains(p.y) && zBounds.contains(p.z)
fun getAdjacent(p: C3): List<C3> =
listOf(p.shiftX(1), p.shiftX(-1), p.shiftY(1), p.shiftY(-1), p.shiftZ(1), p.shiftZ(-1))
fun checkTrapped(start: C3): Boolean {
val visited = HashSet<C3>()
visited.add(start)
val q = ArrayDeque<C3>()
q.add(start)
while (q.isNotEmpty()) {
val cur = q.removeFirst()
if (!withinBounds(cur)) return false
getAdjacent(cur).filter { !ptsSet.contains(it) && !visited.contains(it) }.forEach { w ->
visited.add(w)
q.add(w)
}
}
return true
}
fun markTrapped(start: C3, isTrapped: Boolean, trapped: HashMap<C3, Boolean>) {
val q = ArrayDeque<C3>()
trapped[start] = isTrapped
q.add(start)
while (q.isNotEmpty()) {
val cur = q.removeFirst()
getAdjacent(cur).filter { withinBounds(it) && !ptsSet.contains(it) && !trapped.contains(it) }.forEach { w ->
trapped[w] = isTrapped
q.add(w)
}
}
}
fun main() {
println(part1(pts()))
println(part2(pts()))
}
data class C3(val x: Int, val y: Int, val z: Int) {
fun shiftX(diff: Int): C3 = C3(x + diff, y, z)
fun shiftY(diff: Int): C3 = C3(x, y + diff, z)
fun shiftZ(diff: Int): C3 = C3(x, y, z + diff)
} | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 2,378 | advent-of-code-2022 | Apache License 2.0 |
src/year2023/day12/Day12.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day12
import check
import readInput
fun main() {
val testInput = readInput("2023", "Day12_test")
check(part1(testInput), 21)
check(part2(testInput), 525152L)
val input = readInput("2023", "Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.toConditionRecords().sumOf { it.combinations() }
private fun part2(input: List<String>): Long {
return input.toConditionRecords().sumOf { it.unfold(5).combinations() }
}
private data class ConditionRecord(
val record: String,
val groups: List<Int>,
)
private fun List<String>.toConditionRecords() = map {
ConditionRecord(
record = it.split(' ').first(),
groups = it.split(' ').last().split(',').map(String::toInt),
)
}
private fun ConditionRecord.unfold(factor: Int) = ConditionRecord(
record = (1..factor).joinToString("?") { record },
groups = (1..factor).flatMap { groups },
)
private fun ConditionRecord.combinations() = combinations(record = record, groups = groups)
private fun combinations(
record: String,
groups: List<Int>,
cache: MutableMap<Pair<String, List<Int>>, Long> = HashMap(),
): Long {
if (groups.isEmpty()) return if ("#" in record) 0 else 1
if (record.isEmpty()) return 0
return cache.getOrPut(record to groups) {
var result = 0L
if (record.first() in ".?") {
result += combinations(record = record.drop(1), groups = groups, cache = cache)
}
if (record.first() in "#?" && record.length >= groups.first() && "." !in record.take(groups.first()) && record.getOrNull(groups.first()) != '#') {
result += combinations(record = record.drop(groups.first() + 1), groups = groups.drop(1), cache = cache)
}
result
}
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,814 | AdventOfCode | Apache License 2.0 |
src/Day11.kt | mkfsn | 573,042,358 | false | {"Kotlin": 29625} | fun main() {
data class Decision(val to: Int, val item: Long)
class Monkey(spec: List<String>) {
val id: Int
val items: MutableList<Long>
val operateFn: (Long) -> Long
val testFn: (Long) -> Boolean
val dividedBy: Long
val ifTrue: Int
val ifFalse: Int
var inspectCount = 0L
init {
id = spec[0].replace("Monkey ", "").trim(':').toInt()
items = spec[1].replace("Starting items:", "").trimIndent()
.split(", ").map { it.toLong() }.toMutableList()
spec[2].replace("Operation: new = old", "").trimIndent()
.split(" ").let {
operateFn = { old ->
when (it[0]) {
"*" -> if (it[1] == "old") old * old else old * it[1].toLong()
"+" -> if (it[1] == "old") old + old else old + it[1].toLong()
else -> old
}
}
}
dividedBy = spec[3].replace("Test: divisible by", "").trimIndent().toLong().apply {
testFn = { it % this == 0L }
}
ifTrue = spec[4].replace("If true: throw to monkey", "").trimIndent().toInt()
ifFalse = spec[5].replace("If false: throw to monkey", "").trimIndent().toInt()
}
fun inspect(dividedBy: Long = 3L): List<Decision> {
val decisions: MutableList<Decision> = mutableListOf()
this.items.forEach { item ->
this.operateFn(item).div(dividedBy).let {
decisions.add(if (testFn(it)) Decision(this.ifTrue, it) else Decision(this.ifFalse, it))
}
this.inspectCount++
}.also { this.items.clear() }
return decisions
}
fun addItem(item: Long) = this.items.add(item)
}
fun part1(input: List<String>): Long {
val monkeys = input.chunkedBy { it == "" }.map { Monkey(it) }
repeat(20) {
monkeys.forEach { monkey ->
monkey.inspect(3L).forEach { decision ->
monkeys[decision.to].addItem(decision.item)
}
}
}
return monkeys.map { it.inspectCount }.sortedDescending().take(2).reduce(Long::times)
}
fun part2(input: List<String>): Long {
val monkeys = input.chunkedBy { it == "" }.map { Monkey(it) }
val upBound = monkeys.map { it.dividedBy }.reduce(Long::times)
repeat(10000) {
monkeys.forEach { monkey ->
monkey.inspect(1L).forEach { decision ->
monkeys[decision.to].addItem(decision.item % upBound)
}
}
}
return monkeys.map { it.inspectCount }.sortedDescending().take(2).reduce(Long::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
check(part1(input) == 55930L) // [9, 228, 228, 225, 235, 11, 238, 21]
println(part1(input))
check(part2(input) == 14636993466L)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 3,279 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day15/Day15.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day15
import utils.*
import kotlin.math.absoluteValue
val COORDS_REGEX = """x=(-?\d+), y=(-?\d+)""".toRegex()
data class Coords(var x: Int, var y: Int) {
val manhattanDelta: Int get() = x.absoluteValue + y.absoluteValue
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)
override operator fun equals(other: Any?): Boolean =
other is Coords
&& other.x == x
&& other.y == y
override fun hashCode(): Int = x * 31 + y
}
fun parseInput(input: List<String>): List<Pair<Coords, Int>> =
input
.flatMap { line ->
val (sensorCoords, beaconCoords) = COORDS_REGEX
.findAll(line)
.map { match ->
val (x, y) = match.groupValues.drop(1).map(String::toInt)
Coords(x, y)
}.toList()
val sensorRange = (sensorCoords - beaconCoords).manhattanDelta
listOf(
Pair(sensorCoords, sensorRange),
Pair(beaconCoords, 0)
)
}
.distinct()
fun getSensorRangesOnRow(
sensors: List<Pair<Coords, Int>>,
y: Int
): List<IntRange> =
sensors
.mapNotNull { (sensor, range) ->
val delta = range - (sensor.y - y).absoluteValue
(sensor.x - delta..sensor.x + delta).takeUnless(IntRange::isEmpty)
}
.sortedBy { it.first }
fun getMergedRangesOnRow(
sensors: List<Pair<Coords, Int>>,
y: Int
): List<IntRange> =
getSensorRangesOnRow(sensors, y).fold(listOf()) { ranges, range ->
ranges
.lastOrNull()
?.takeIf { range.first <= it.last + 1 }
?.let { prev ->
ranges.dropLast(1) + listOf(
(prev.first..maxOf(prev.last, range.last))
)
}
?: (ranges + listOf(range))
}
fun splitRowAt(ranges: List<IntRange>, i: Int): List<IntRange> =
ranges.flatMap { range ->
if (i in range)
listOf(
(range.first until i),
(i + 1..range.last)
).filter { !it.isEmpty() }
else
listOf(range)
}
fun part1(input: List<String>, y: Int): Int {
val sensors = parseInput(input)
var ranges = getMergedRangesOnRow(sensors, y)
sensors.forEach { (coords, _) ->
if (coords.y == y)
ranges = splitRowAt(ranges, coords.x)
}
return ranges.sumOf { it.last - it.first + 1 }
}
fun getHoleFrom(ranges: List<IntRange>, start: Int): Int =
ranges
.dropWhile { it.last < start }
.firstOrNull()
?.takeIf { it.first <= start }
?.let { it.last + 1 }
?: start
fun part2(input: List<String>, size: Int): Long {
val sensors = parseInput(input)
return (0..size)
.mapNotNull { y ->
val ranges = getMergedRangesOnRow(sensors, y)
val x = getHoleFrom(ranges, 0)
Coords(x, y).takeIf { x <= size }
}
.single()
.let { it.x * 4000000L + it.y }
}
fun main() {
val testInput = readInput("Day15_test")
expect(part1(testInput, 10), 26)
expect(part2(testInput, 20), 56000011)
val input = readInput("Day15")
println(part1(input, 2000000))
println(part2(input, 4000000))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 3,406 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day08.kt | undermark5 | 574,819,802 | false | {"Kotlin": 67472} | fun main() {
fun part1(input: List<String>): Int {
val trees = input.map {
it.toCharArray().map {
it.digitToInt()
}
}
val transposed = MutableList(
trees.first().size
) { col ->
MutableList(trees.size) { row ->
trees[row][col]
}
}
var count = 0
for (i in trees.indices) {
for (j in trees[i].indices) {
val value = trees[i][j]
val row = trees[i]
val col = transposed[j]
val rowFor = row.slice(0..j)
val colFor = col.slice(0..i)
val rowRev = row
.slice(j..row.lastIndex)
.reversed()
val colRev = col
.slice(i..col.lastIndex)
.reversed()
val views = listOf(
rowFor, colFor, rowRev, colRev
)
if (views.any {
it.slice(0 until it.lastIndex)
.all { it < value }
}) {
count++
}
}
}
return count
}
fun part2(input: List<String>): Int {
val trees = input.map {
it.toCharArray().map {
it.digitToInt()
}
}
val transposed = MutableList(
trees.first().size) { col ->
MutableList(trees.size){ row ->
trees [row][col]
}
}
var max = 0
for (i in trees.indices) {
for (j in trees[i].indices) {
val value=trees [i][j]
val row = trees [i]
val col = transposed[j]
val rowFor = row.slice(0..j).reversed()
val colFor = col.slice(0..i).reversed()
val rowRev = row
.slice(j..row.lastIndex)
val colRev = col
.slice(i..col.lastIndex)
val views = listOf(
rowFor,colFor,rowRev,colRev
)
val cur = views.map {
if (it.size == 1) return@map 0
val view = it.slice(1..it.lastIndex)
val index = view
.indexOfFirst {
it >= value
}
if (index < 0)
view.size
else
view.slice(0..index).size
}.reduce {a, b -> a * b}
if (cur > max) max = cur
}
}
return max
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e9cf715b922db05e1929f781dc29cf0c7fb62170 | 3,022 | AoC_2022_Kotlin | Apache License 2.0 |
src/day15/Day15.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day15
import Coordinate
import flatten
import readInput
import java.lang.Integer.max
import java.lang.Integer.min
import kotlin.math.absoluteValue
const val day = "15"
fun main() {
fun calculatePart1Score(input: List<String>, y: Int): Int {
val sensorsAndBeacons = input.parseInputs()
val blockedPositions = sensorsAndBeacons.flatMap { (sensor, beacon) ->
val beaconDistance = sensor.manhattanDistanceTo(beacon)
val yDistance = (sensor.y - y).absoluteValue
val remainingDistance = beaconDistance - yDistance
(sensor.x - remainingDistance..sensor.x + remainingDistance)
}
.distinct()
.sorted()
.subtract(sensorsAndBeacons.flatten().filter { it.y == y }.map { it.x }.toSet())
return blockedPositions.size
}
fun calculatePart2Score(input: List<String>, searchArea: Int): Long {
val sensorsAndBeacons = input.parseInputs()
(0..searchArea).map { x ->
sensorsAndBeacons.asSequence().map { (sensor, beacon) ->
val maxDistance = sensor.manhattanDistanceTo(beacon)
val xDistance = (sensor.x - x).absoluteValue
val remainingYDistance = maxDistance - xDistance
max(0, sensor.y - remainingYDistance)..min(searchArea, sensor.y + remainingYDistance)
}
.filter { !it.isEmpty() }
.sortedBy { it.first }
.fold(0) { y, range ->
if (y < range.first) {
return x * 4000000L + y
}
max(y, range.last + 1)
}
}
return -1
}
// 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, 10)
val part1points = calculatePart1Score(input, 2000000)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1points")
check(part1TestPoints == 26)
val part2TestPoints = calculatePart2Score(testInput, 20)
val part2points = calculatePart2Score(input, 4000000)
println("Part2 test points: \n$part2TestPoints")
println("Part2 points: \n$part2points")
check(part2TestPoints == 56000011L)
}
fun List<String>.parseInputs(): List<Pair<Coordinate, Coordinate>> = map { it.parseInput() }
fun String.parseInput(): Pair<Coordinate, Coordinate> {
val (sensorText, beaconText) = split(":")
val sensorX = sensorText.substringAfter("x=").substringBefore(", y=")
val sensorY = sensorText.substringAfter("y=")
val beaconX = beaconText.substringAfter("x=").substringBefore(", y=")
val beaconY = beaconText.substringAfter("y=")
return Coordinate(sensorX, sensorY) to Coordinate(beaconX, beaconY)
}
| 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 2,927 | advent-of-code-22-kotlin | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2023/Day03.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2023
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val problem = readInput(2023, 3).useLines { lines ->
val grid = lines.toList()
val numberIndices = mutableMapOf<Index, NumberInfo>()
for (y in grid.indices) {
val row = grid[y]
for (x in row.indices) {
val cell = row[x]
val cellIndex = Index(x, y)
if (cellIndex in numberIndices || !cell.isDigit()) continue
var span = 0
while (row.getOrNull(x + span + 1)?.isDigit() == true) span++
val numberInfo = NumberInfo(y, x..x + span)
for (i in numberInfo.xRange) numberIndices[Index(i, y)] = numberInfo
}
}
Problem(grid, numberIndices)
}
part1(problem)
part2(problem)
}
private fun part1(problem: Problem) {
val validNumbers = mutableSetOf<NumberInfo>()
val neighbors = intArrayOf(-1, 0, 1)
for (y in problem.grid.indices) {
val row = problem.grid[y]
for (x in row.indices) {
val cell = row[x]
if (cell.isSymbol()) {
for (j in neighbors) for (i in neighbors) {
val index = Index(x+i, y+j)
problem.numberIndices[index]?.let { validNumbers.add(it) }
}
}
}
}
val sum = validNumbers.fold(0) { acc, n -> acc + n.evaluate(problem.grid) }
println(sum)
}
private fun part2(problem: Problem) {
var sumOfRatios = 0
val neighbors = intArrayOf(-1, 0, 1)
for (y in problem.grid.indices) {
val row = problem.grid[y]
for (x in row.indices) {
val cell = row[x]
if (cell == '*') {
val numbers = mutableSetOf<NumberInfo>()
for (j in neighbors) for (i in neighbors) {
val index = Index(x+i, y+j)
problem.numberIndices[index]?.let { numbers.add(it) }
}
if (numbers.size == 2) {
val ratio = numbers.fold(1) { acc, n -> acc * n.evaluate(problem.grid) }
sumOfRatios += ratio
}
}
}
}
println(sumOfRatios)
}
// Alternative Solution (doesn't conform to part 2)
// Find all symbols and locate all their accessible number indices (single digit numbers only)
// Traverse this set of indices and attempt to recover the actual numbers
// Once a number is found, remove all its indices from the indices set <<- REPEAT
// Calculate the sum of numbers to get your answer
class Problem(val grid: List<String>, val numberIndices: Map<Index, NumberInfo>)
data class NumberInfo(val y: Int, val xRange: IntRange) {
fun evaluate(grid: List<String>) = grid[y].substring(xRange).toInt()
}
fun Char.isSymbol() = this !in '0'..'9' && this != '.'
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 2,915 | adventofcode | Apache License 2.0 |
src/year_2022/day_13/Day13.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_13
import readInput
object Day13 {
val compare: (String, String) -> Int = { s1: String, s2: String ->
if (inOrder(s1.toMutableList(), s2.toMutableList())){
-1
} else {
1
}
}
/**
* @return
*/
fun solutionOne(text: List<String>): Int {
return parseText(text)
.mapIndexed { index, (left, right) ->
val inOrder = compare(left, right)
if (inOrder != 1) {
index + 1
} else {
0
}
}
.sum()
}
/**
* @return
*/
fun solutionTwo(text: List<String>): Int {
val pairs = parseText(text)
val two = "[[2]]"
val six = "[[6]]"
val sorted = (pairs.flatten() + two + six).sortedWith(compare)
return (sorted.indexOf(two) + 1) * (sorted.indexOf(six) + 1)
}
private fun parseText(text: List<String>): List<List<String>> {
return text
.filter { it.isNotEmpty() }
.windowed(2, 2)
}
private fun inOrder(l: MutableList<Char>, r: MutableList<Char>): Boolean {
val (lk, rk) = l.getNumber() to r.getNumber()
if (l[0] == '[' && rk != null) {
r.addBrackets(1+rk/10)
}
if (r[0] == '[' && lk != null) {
l.addBrackets(1+lk/10)
}
return when {
(l[0] == ']' && r[0] != ']') -> true
(l[0] != ']' && r[0] == ']') -> false
(lk == (rk ?: -1)) -> inOrder(l.subList(1+lk/10, l.size), r.subList(1+rk!!/10, r.size))
(lk != null && rk != null) -> lk < rk
else -> inOrder(l.subList(1, l.size), r.subList(1, r.size))
}
}
}
fun main() {
val inputText = readInput("year_2022/day_13/Day13.txt")
val solutionOne = Day13.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day13.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
}
fun MutableList<Char>.addBrackets(len: Int) {
add(len, ']')
add(0, '[')
}
fun List<Char>.getNumber(): Int? {
return when (first().isDigit()) {
true -> takeWhile { it.isDigit() }.joinToString("").toInt()
else -> null
}
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 2,297 | advent_of_code | Apache License 2.0 |
src/Day09.kt | Soykaa | 576,055,206 | false | {"Kotlin": 14045} | import kotlin.math.*
private operator fun Pair<Int, Int>.plus(b: Pair<Int, Int>) = Pair((first + b.first), (second + b.second))
private fun processInstructions(direction: String): Pair<Int, Int>? = when (direction) {
"R" -> Pair(1, 0)
"L" -> Pair(-1, 0)
"U" -> Pair(0, 1)
"D" -> Pair(0, -1)
else -> null
}
private fun getDistance(fst: Pair<Int, Int>, snd: Pair<Int, Int>): Int =
max(abs(fst.first - snd.first), (abs(fst.second - snd.second)))
private fun diagonalStep(rope: MutableList<Pair<Int, Int>>, i: Int): MutableList<Pair<Int, Int>> {
val visited = mutableListOf<Pair<Int, Int>>()
while (getDistance(rope[i], rope[i + 1]) > 1) {
val move = Pair((rope[i].first - rope[i + 1].first).sign, (rope[i].second - rope[i + 1].second).sign)
rope[i + 1] += move
visited.add(rope[rope.size - 1])
}
return visited
}
private fun countAtLeastOnceVisited(input: List<String>, ropeSize: Int): Int {
val rope = MutableList(ropeSize) { Pair(0, 0) }
val visited = mutableListOf<Pair<Int, Int>>()
input.forEach { line ->
val (direction, numOfSteps) = line.split(" ")
repeat(numOfSteps.toInt()) {
val move = processInstructions(direction)!!
rope[0] += move
visited.add(rope[rope.size - 1])
for (i in 0 until rope.size - 1) visited.addAll(diagonalStep(rope, i))
}
}
return visited.toSet().size
}
fun main() {
fun part1(input: List<String>): Int = countAtLeastOnceVisited(input, 2)
fun part2(input: List<String>): Int = countAtLeastOnceVisited(input, 10)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1e30571c475da4db99e5643933c5341aa6c72c59 | 1,699 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day12/Day12.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day12
import com.jacobhyphenated.advent2022.Day
import java.util.PriorityQueue
/**
* Day 12: Hill Climbing Algorithm
*
* The terrain is given as a 2d map of characters. 'S' is the start position, 'E' is the end position.
* The characters indicate the height of the terrain with 'a' being the lowest and 'z' being the highest.
* You can always climb down, but you can only climb up to a position 1 higher ( b -> c but not c -> e).
* S is the equivalent of 'a' and E is the equivalent of 'z'.
*/
class Day12: Day<List<List<Char>>> {
override fun getInput(): List<List<Char>> {
return readInputFile("day12")
.lines()
.map { it.toCharArray().asList() }
}
/**
* Find the path that takes the fewest number of steps to get from S to E
*/
override fun part1(input: List<List<Char>>): Any {
val startPosition = findStartPosition(input)
return shortestPath(startPosition, input)
}
/**
* In the future, we might want to create a trail.
* Look at all 'a' locations as possible starting points.
* Find the path that takes the fewest number of steps to get to E
*/
override fun part2(input: List<List<Char>>): Int {
val startingPositions = input.flatMapIndexed { r, row ->
row.mapIndexed { index, value -> Pair(index, value) }
.filter { (_, character) -> character == 'a' }
.map { (c, _) -> Pair(r, c) }
}
return startingPositions.map { shortestPath(it, input) }
.filter { it >= 0 } // Filter out unreachable paths
.min()
}
/**
* Dijkstra's algorithm to find the shortest path from a given starting point to the 'E' character.
*/
private fun shortestPath(startPosition: Pair<Int,Int>, input: List<List<Char>>): Int {
val distances: MutableMap<Pair<Int,Int>, Int> = mutableMapOf()
// Use a priority queue implementation - min queue sorted by lowest "cost"
val queue = PriorityQueue<PathCost> { a, b -> a.cost - b.cost }
queue.add(PathCost(startPosition, 0))
distances[startPosition] = 0
var current: PathCost
do {
current = queue.remove()
// If we already found a less expensive way to reach this position
if (current.cost > (distances[current.location] ?: Int.MAX_VALUE)) {
continue
}
val (r,c) = current.location
// if this the end position, we've found the answer
if (input[r][c] == 'E') {
return current.cost
}
// From the current position, look in each direction for a valid move
findAdjacent(r, c, input).forEach {
// cost is the number of steps taken, increases by 1 for each move
val cost = distances.getValue(current.location) + 1
// If the cost to this space is less than what was previously known, put this on the queue
if (cost < (distances[it] ?: Int.MAX_VALUE)) {
distances[it] = cost
queue.add(PathCost(it, cost))
}
}
} while (queue.size > 0)
return -1
}
// Get adjacent positions to the current position (no diagonals) that are reachable from the current position
// a position is reachable if its height is not more than 1 greater than the current height
private fun findAdjacent(row: Int, col: Int, grid: List<List<Char>>): List<Pair<Int,Int>> {
val result = mutableListOf<Pair<Int,Int>>()
for (r in (row - 1).coerceAtLeast(0) .. (row + 1).coerceAtMost(grid.size - 1)) {
if (r == row) {
continue
}
result.add(Pair(r, col))
}
for (c in (col - 1).coerceAtLeast(0) .. (col + 1).coerceAtMost(grid[row].size - 1)) {
if (c == col) {
continue
}
result.add(Pair(row, c))
}
val currentHeight = getCharHeight(grid[row][col])
return result.filter { (r,c) -> getCharHeight(grid[r][c]) <= currentHeight + 1 }
}
private fun getCharHeight(c: Char): Int {
if (c == 'S') {
return 'a'.code
}
if (c == 'E') {
return 'z'.code
}
return c.code
}
private fun findStartPosition(input: List<List<Char>>): Pair<Int,Int> {
for (r in input.indices) {
val c = input[r].indexOfFirst { it == 'S' }
if (c >= 0) {
return Pair(r,c)
}
}
throw NotImplementedError("Could not find Start Position")
}
}
data class PathCost(val location: Pair<Int,Int>, val cost: Int) | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 4,799 | advent2022 | The Unlicense |
src/day19/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day19
import assert
import println
import readInput
import kotlin.math.min
import kotlin.math.max
fun main() {
data class Rule(val name: String, val operation: Char?, val limit: Int?, val destination: String?) {
constructor(name: String) : this(name, null, null, null)
}
data class Workflow(val name: String, val rules: List<Rule>)
data class Part(val params: Map<Char, Int>)
data class PartRanges(val ranges: MutableMap<Char, Pair<Int, Int>>) {
fun sum() = ranges.values.fold(1L) { acc, range ->
if (range.first > range.second) throw Exception("!!!!")
acc * (range.first..range.second).count()
}
fun lessThan(key: Char, limit: Int) {
ranges[key] = ranges[key]!!.first to min(limit, ranges[key]!!.second)
}
fun moreThan(key: Char, limit: Int) {
ranges[key] = max(limit, ranges[key]!!.first) to ranges[key]!!.second
}
fun copy(): PartRanges = PartRanges("xmas".toCharArray().associateWith { ranges[it]!!.copy() }.toMutableMap())
}
fun parse(input: List<String>): Pair<List<Workflow>, List<Part>> {
val workflows = input.takeWhile { it.isNotEmpty() }.map { it->
val name = it.takeWhile { it != '{' }
val rules = it.substring(name.length + 1..<it.length - 1).split(",")
.map {rule ->
val name = rule.takeWhile { !"<>".contains(it) }
var result = Rule(name)
if (rule.length > name.length) {
val sign = rule[name.length]
val parts = rule.substring(name.length + 1..<rule.length).split(":")
val limit = parts[0].toInt()
val destination = parts[1]
result = Rule(name, sign, limit, destination)
}
result
}
Workflow(name, rules)
}
val parts = input.takeLastWhile { it.isNotEmpty() }.map { it->
Part(it.substring(1..it.length - 2).split(",").associate {
val (key, value) = it.split("=")
key.first() to value.toInt()
})
}
return workflows to parts
}
fun nextWorkflow(list: List<Workflow>, step: String, part: Part): String {
if (listOf("A", "R").contains(step)) return step
val workflow = list.find { it.name == step }!!
for (rule in workflow.rules) {
if (rule.operation == null) {
return nextWorkflow(list, rule.name, part)
}
val partParamCategory = rule.name.first()
if (rule.operation == '>') {
if (part.params[partParamCategory]!! > rule.limit!!) {
return nextWorkflow(list, rule.destination!!, part)
}
} else {
if (part.params[partParamCategory]!! < rule.limit!!) {
return nextWorkflow(list, rule.destination!!, part)
}
}
}
return ""
}
fun processOne(workflows: List<Workflow>, part: Part): Long {
if (nextWorkflow(workflows, "in", part) == "R") return 0
return part.params.values.sum().toLong()
}
fun process(input: Pair<List<Workflow>, List<Part>>): Long {
return input.second.sumOf { processOne(input.first, it) }
}
fun nextWorkflow2(workflows: List<Workflow>, step: String, ranges: PartRanges): Long {
if ("R" == step) return 0L
if ("A" == step) return ranges.sum()
val workflow = workflows.find { it.name == step }!!
val invertedRange = ranges.copy()
var result = 0L
for (rule in workflow.rules) {
if (rule.operation == null) {
result += nextWorkflow2(workflows, rule.name, invertedRange)
continue
}
val partParamCategory = rule.name.first()
val nextRange = invertedRange.copy()
result += if (rule.operation == '>') {
nextRange.moreThan(partParamCategory, rule.limit!! + 1)
invertedRange.lessThan(partParamCategory, rule.limit)
nextWorkflow2(workflows, rule.destination!!, nextRange)
} else {
nextRange.lessThan(partParamCategory, rule.limit!! - 1)
invertedRange.moreThan(partParamCategory, rule.limit)
nextWorkflow2(workflows, rule.destination!!, nextRange)
}
}
return result
}
fun processAllVariations(workflows: List<Workflow>): Long {
val result = PartRanges("xmas".toCharArray().associateWith { (1 to 4000) }.toMutableMap())
return nextWorkflow2(workflows, "in", result)
}
process(parse(readInput("day19/test1")))
.assert(19114L)
"Part 1:".println()
process(parse(readInput("day19/input")))
.assert(342650L)
.println()
processAllVariations(parse(readInput("day19/test1")).first)
.assert(167409079868000L)
"Part 2:".println()
processAllVariations(parse(readInput("day19/input")).first)
.assert(130303473508222L)
.println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 5,243 | advent-of-code-2023 | Apache License 2.0 |
src/commonMain/kotlin/advent2020/day17/Day17Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day17
fun part1(input: String): String = common(input) { x, y -> listOf(x, y, 0) }
fun part2(input: String): String = common(input) { x, y -> listOf(x, y, 0, 0) }
private fun common(input: String, init: (Int, Int) -> List<Int>): String {
var pocket = input.trim().lines()
.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, c -> if (c == '#') init(x, y) else null } }
.toSet()
val dim = pocket.first().size
val neighbours = neighbours(dim).filterNot { it.all { v -> v == 0 } }
repeat(6) { pocket = cycle(pocket, neighbours) }
return pocket.size.toString()
}
private fun neighbours(dim: Int): List<List<Int>> = when (dim) {
0 -> listOf(emptyList())
else -> neighbours(dim - 1).flatMap { l -> (-1..1).map { l + it } }
}
private fun cycle(
pocket: Set<List<Int>>,
neighbours: Iterable<List<Int>>,
): Set<List<Int>> {
val counts = mutableMapOf<List<Int>, Int>()
pocket.forEach { p ->
neighbours.map { p.move(it) }.forEach { counts[it] = (counts[it] ?: 0) + 1 }
}
return counts.mapNotNull { (pos, count) ->
val prevState = pos in pocket
val nextState = if (prevState) count == 2 || count == 3 else count == 3
if (nextState) pos else null
}.toSet()
}
private fun List<Int>.move(v: List<Int>) = mapIndexed { index, i -> i + v[index] }
private fun display(iter: Int, pocket: Set<List<Int>>) {
println("After $iter cycle(s):")
(-iter..+iter).forEach { z ->
println("z=$z")
(-iter..2 + iter).forEach { y ->
(-iter..2 + iter).forEach { x ->
print(if (listOf(x, y, z) in pocket) "#" else ".")
}
println()
}
println()
}
println()
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 1,755 | advent-of-code-2020 | MIT License |
src/Day08.kt | MisterTeatime | 560,956,854 | false | {"Kotlin": 37980} | fun main() {
fun part1(input: List<String>): Int {
val cols = (0 until input[0].length)
.map { input.fold("") {acc, s -> acc + s[it] } }
return input.mapIndexed { rIndex, row ->
row.mapIndexed { cIndex, c ->
isVisible(row, cIndex, c.digitToInt()) || isVisible(cols[cIndex], rIndex, c.digitToInt())
}
}.sumOf { row -> row.count { it } }
}
fun part2(input: List<String>): Int {
val cols = (0 until input[0].length)
.map { input.fold("") {acc, s -> acc + s[it] } }
val scenicScores = input.mapIndexed { rIndex, row ->
row.mapIndexed { cIndex, _ ->
getScenicScore(row, cIndex) * getScenicScore(cols[cIndex], rIndex)
}
}
return scenicScores.maxOf { row -> row.maxOf { it } }
}
// 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 isVisible(group: String, pos: Int, item: Int): Boolean {
val before = group.take(pos).map { it.digitToInt() }
val after = group.takeLast(group.length - 1 -pos).map { it.digitToInt() }
return before.all { it < item } || after.all { it < item }
}
fun getScenicScore(group: String, pos: Int): Int {
val item = group[pos].digitToInt()
val before = group.take(pos).map { it.digitToInt() }
val after = group.takeLast(group.length - 1 - pos).map { it.digitToInt() }
val testBefore = before.reversed().takeWhile { it < item }.count()
val testAfter = after.takeWhile { it < item }.count()
return (if (testBefore < before.count()) testBefore + 1 else testBefore) *
(if (testAfter < after.count()) testAfter + 1 else testAfter)
} | 0 | Kotlin | 0 | 0 | 8ba0c36992921e1623d9b2ed3585c8eb8d88718e | 1,904 | AoC2022 | Apache License 2.0 |
src/Day16.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
class Node(val rate: Int, var paths: List<Node> = emptyList())
val inputLineRegex = """Valve ([A-Z]+) has flow rate=(\d+)""".toRegex()
val input2LineRegex = """([A-Z]+)""".toRegex()
fun parseData(input: List<String>): Map<String, Node> {
val nodes = mutableMapOf<String, Node>()
for (line in input)
line.split(";").first().destructured(inputLineRegex).let { (name, rate) -> nodes[name] = Node(rate.toInt()) }
for (line in input) {
val (name) = line.split(";").first().destructured(inputLineRegex)
val paths = input2LineRegex.findAll(line.split(";").last()).map { nodes[it.value]!! }.toList()
nodes[name]!!.paths = paths
}
return nodes
}
fun bestPath(startNode: Node, targetNodesLeft: Set<Node>, minutes: Int): Pair<Int, List<Node>> {
fun visitNode(node: Node, minutesLeft: Int, pressureReleased: Int, opened: Set<Node>, closed: Set<Node>, visited: List<Node>): Pair<Int, List<Node>> {
val dp = opened.sumOf { it.rate }
val reachableClosed = closed.map { Pair(it, aStar(node, {end -> end == it}, { 0 }, { n -> n.paths })) }
.filter { (_, steps) -> steps.size <= minutesLeft }
if (reachableClosed.isEmpty() || minutesLeft == 0)
return Pair(pressureReleased + (minutesLeft - 1) * dp, visited)
return reachableClosed.map { (candidate, path) ->
visitNode(candidate, minutesLeft - path.size, pressureReleased + path.size * dp + candidate.rate, opened + candidate, closed - candidate, visited + candidate)
}.maxBy { it.first }
}
return visitNode(startNode, minutes, 0, emptySet(), targetNodesLeft, listOf())
}
fun part1(input: List<String>): Int {
val nodes = parseData(input)
val nonZeroClosedNodes = nodes.values.filter { it.rate != 0 }.toSet()
val bestPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes, 30)
return bestPath.first
}
fun part2(input: List<String>): Int {
val nodes = parseData(input)
val nonZeroClosedNodes = nodes.values.filter { it.rate != 0 }.toSet()
val myPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes, 26)
val elephantPath = bestPath(nodes["AA"]!!, nonZeroClosedNodes - myPath.second.toSet(), 26)
return myPath.first + elephantPath.first
}
test(
day = 16,
testTarget1 = 1651,
testTarget2 = 1327, // should be 1707??
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 2,586 | aoc2022 | Apache License 2.0 |
src/Day08.kt | RobvanderMost-TomTom | 572,005,233 | false | {"Kotlin": 47682} | fun main() {
fun readMatrix(input: List<String>) =
input
.map { row ->
row.map { it.digitToInt() }
}
fun List<List<Int>>.leftOf(x: Int, y: Int) =
this[y].subList(0, x)
fun List<List<Int>>.rightOf(x: Int, y: Int) =
this[y].subList(x+1, this[y].size)
fun List<List<Int>>.above(x: Int, y: Int) =
subList(0, y).map { it[x] }
fun List<List<Int>>.below(x: Int, y: Int) =
subList(y+1, size).map { it[x] }
fun List<List<Int>>.isVisible(x: Int, y: Int) =
leftOf(x, y).all { it < this[y][x] } ||
rightOf(x, y).all { it < this[y][x] } ||
above(x, y).all { it < this[y][x] } ||
below(x, y).all { it < this[y][x] }
fun List<Int>.visibleCount(height: Int) =
indexOfFirst { it >= height }
.let {
if (it == -1) size else it+1
}
fun List<List<Int>>.scenicScore(x: Int, y: Int) =
leftOf(x, y).reversed().visibleCount(this[y][x]) *
rightOf(x, y).visibleCount(this[y][x]) *
above(x, y).reversed().visibleCount(this[y][x]) *
below(x, y).visibleCount(this[y][x])
fun part1(input: List<String>): Int {
val trees = readMatrix(input)
return (1 until trees.lastIndex)
.sumOf {y ->
(1 until trees[y].lastIndex)
.count {x ->
trees.isVisible(x, y)
}
} + trees.size * 2 + trees.first().size + trees.last().size - 4
}
fun part2(input: List<String>): Int {
val trees = readMatrix(input)
return (0 .. trees.lastIndex)
.maxOf {y ->
(0..trees[y].lastIndex)
.maxOf {x ->
trees.scenicScore(x, y)
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
val trees = readMatrix(testInput)
check(trees.isVisible(1, 1))
check(trees.isVisible(2, 1))
check(!trees.isVisible(3, 1))
check(trees.isVisible(1, 2))
check(!trees.isVisible(2, 2))
check(trees.isVisible(3, 2))
check(!trees.isVisible(1, 3))
check(trees.isVisible(2, 3))
check(!trees.isVisible(3, 3))
check(part1(testInput) == 21)
check(trees.scenicScore(2, 1) == 4)
check(trees.scenicScore(2, 3) == 8)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 5 | Kotlin | 0 | 0 | b7143bceddae5744d24590e2fe330f4e4ba6d81c | 2,596 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day12/day12.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day12
import eu.janvdb.aocutil.kotlin.readLines
//private const val FILENAME = "input12-test.txt"
private const val FILENAME = "input12.txt"
private val BLOCK_REGEX = Regex("#+")
fun main() {
val puzzles = readLines(2023, FILENAME).map { Puzzle.parse(it) }
val counts = puzzles.map { it.countSolutions() }
val sum1 = counts.sum()
println(sum1)
val puzzles2 = puzzles.map { it.unfold() }
val counts2 = puzzles2.map { it.countSolutions() }
val sum2 = counts2.sum()
println(sum2)
}
private const val REPETITIONS = 5
data class Puzzle(val pattern: String, val blocks: List<Int>) {
private val cache = mutableMapOf<Pair<String, List<Int>>, Long>()
fun unfold(): Puzzle {
val pattern = (1..REPETITIONS).joinToString("?") { pattern }
val blocks = (1..REPETITIONS).asSequence().flatMap { blocks }.toList()
return Puzzle(pattern, blocks)
}
fun countSolutions(): Long {
return countSolutions(pattern, blocks)
}
private fun countSolutions(pattern: String, blocks: List<Int>): Long {
val key = Pair(pattern, blocks)
return cache.getOrPut(key) { doCountSolutions(pattern, blocks) }
}
private fun doCountSolutions(pattern: String, blocks: List<Int>): Long {
fun getCh(i: Int) = if (i < 0 || i >= pattern.length) '.' else pattern[i]
// Check if still occurrences
if (blocks.isEmpty()) return if (pattern.none { it == '#' }) 1L else 0L
// Check if the solution can fit here
if (pattern.length < blocks.sum() + blocks.size - 1) return 0L
// Start by finding the largest fixated block
val largestFixedBlock =
BLOCK_REGEX.findAll(pattern).map { Pair(it.range.first, it.range.last - it.range.first + 1) }
.sortedByDescending { it.second }
.firstOrNull()
if (largestFixedBlock != null) {
// Find the blocks that fit and split there
val possibleBlocks = blocks.mapIndexed { index, occurrence -> Pair(index, occurrence) }
.filter { it.second >= largestFixedBlock.second }
return possibleBlocks.sumOf { block ->
val requiredWildcards = block.second - largestFixedBlock.second
(largestFixedBlock.first - requiredWildcards..largestFixedBlock.first)
.filter { index ->
(index..<index + block.second).none { getCh(it) == '.' }
&& getCh(index - 1) != '#' && getCh(index + block.second) != '#'
}
.sumOf { index ->
val remainderLeft = if (index > 0) pattern.substring(0, index - 1) else ""
val remainderRight =
if (index + block.second + 1 < pattern.length) pattern.substring(index + block.second + 1) else ""
val blocksLeft = if (block.first != 0) blocks.subList(0, block.first) else emptyList()
val blocksRight =
if (block.first != blocks.size - 1) blocks.subList(
block.first + 1,
blocks.size
) else emptyList()
val solutionsLeft = countSolutions(remainderLeft, blocksLeft)
val solutionsRight = countSolutions(remainderRight, blocksRight)
solutionsLeft * solutionsRight
}
}
}
// Only wildcards
return countSolutionsWithOnlyWildcards(pattern, blocks)
}
private fun countSolutionsWithOnlyWildcards(pattern: String, blocks: List<Int>): Long {
val key = Pair(pattern, blocks)
return cache.getOrPut(key) { doCountSolutionsWithOnlyWildcards(pattern, blocks) }
}
private fun doCountSolutionsWithOnlyWildcards(pattern: String, blocks: List<Int>): Long {
// Check if still occurrences
if (blocks.isEmpty()) return if (pattern.none { it == '#' }) 1L else 0L
// Check if the solution can fit here
if (pattern.length < blocks.sum() + blocks.size - 1) return 0L
// Handle empty case
val startingWithSpace = countSolutionsWithOnlyWildcards(pattern.substring(1), blocks)
if (pattern[0] == '.') return startingWithSpace
// Block starting here should match first block
val blockSize = blocks[0]
if (!(0..<blockSize).all { pattern[it] == '?' }) return startingWithSpace
val newPattern = if (pattern.length != blockSize) pattern.substring(blockSize + 1) else ""
return startingWithSpace + countSolutionsWithOnlyWildcards(newPattern, blocks.subList(1, blocks.size))
}
companion object {
fun parse(line: String): Puzzle {
val parts = line.split(" ")
return Puzzle(parts[0], parts[1].split(",").map { it.toInt() })
}
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 5,115 | advent-of-code | Apache License 2.0 |
src/day08/Day08.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day08
import println
import readInput
fun main() {
fun part1(input: List<String>) =
input.sumOf { it.split("|")[1].split(" ").count { word -> listOf(2, 3, 4, 7).contains(word.length) } }
fun String.intersect(decoded: String?) = decoded!!.toCharArray().count { c -> contains(c) }
fun List<String>.decode(decoded: Array<String?>, length: Int, charsIn1: Int, charsIn4: Int, charsIn7: Int) =
first {
it.length == length
&& it.intersect(decoded[1]) == charsIn1
&& it.intersect(decoded[4]) == charsIn4
&& it.intersect(decoded[7]) == charsIn7
}
fun part2(input: List<String>): Int {
return input.sumOf { line ->
line.split(" | ").let { (before, after) ->
val numbers = before.split(" ").map { String(it.toCharArray().sorted().toCharArray()) }
val output = after.split(" ").map { String(it.toCharArray().sorted().toCharArray()) }
val decoded = arrayOfNulls<String>(10)
decoded[1] = numbers.first { it.length == 2 }
decoded[4] = numbers.first { it.length == 4 }
decoded[7] = numbers.first { it.length == 3 }
decoded[8] = numbers.first { it.length == 7 }
decoded[0] = numbers.decode(decoded, 6, 2, 3, 3)
decoded[2] = numbers.decode(decoded, 5, 1, 2, 2)
decoded[3] = numbers.decode(decoded, 5, 2, 3, 3)
decoded[5] = numbers.decode(decoded, 5, 1, 3, 2)
decoded[6] = numbers.decode(decoded, 6, 1, 3, 2)
decoded[9] = numbers.decode(decoded, 6, 2, 4, 3)
output.fold("") { acc, s -> acc + decoded.indexOf(s) }.toInt()
}
}
}
val testInput = readInput("day08/input_test")
check(part1(testInput) == 26)
check(part2(testInput) == 61229)
val input = readInput("day08/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 2,022 | advent-of-code-2021 | Apache License 2.0 |
src/y2015/Day15.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
import kotlin.math.max
data class Ingredient(
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
)
/**
* generate all possible ways [total] can be a sum of [n] non-negative integers, taking order into account
*/
fun generateSplits(total: Int, n: Int) : Sequence<List<Int>> = sequence {
if (n <= 1) {
yield(listOf(total))
} else if (n == 2) {
(0..total).forEach {
yield(listOf(it, total - it))
}
} else {
(0..total).forEach { first ->
generateSplits(total - first, n - 1).forEach {
yield(listOf(first) + it)
}
}
}
}
object Day15 {
private fun parse(input: List<String>): List<Ingredient> {
return input.map { str ->
val els = str.replace(",", "").split(' ')
Ingredient(
els[2].toInt(),
els[4].toInt(),
els[6].toInt(),
els[8].toInt(),
els.last().toInt()
)
}
}
fun part1(input: List<String>): Int {
val ingredients = parse(input)
val numIngredients = ingredients.size
val total = 100
return generateSplits(total, numIngredients).maxOf { amounts ->
val cookie = cookie(amounts, ingredients)
goodness(cookie)
}
}
private fun cookie(amounts: List<Int>, ingredients: List<Ingredient>): Ingredient {
return amounts.zip(ingredients).fold(Ingredient(0, 0, 0, 0, 0)) { acc, (amount, ingredient)->
Ingredient(
acc.capacity + amount * ingredient.capacity,
acc.durability + amount * ingredient.durability,
acc.flavor + amount * ingredient.flavor,
acc.texture + amount * ingredient.texture,
acc.calories + amount * ingredient.calories,
)
}
}
private fun goodness(cookie: Ingredient): Int {
return max(0, cookie.capacity) * max(0, cookie.durability) * max(0, cookie.flavor) * max(0, cookie.texture)
}
fun part2(input: List<String>): Int {
val ingredients = parse(input)
val numIngredients = ingredients.size
val total = 100
return generateSplits(total, numIngredients).map { amounts ->
cookie(amounts, ingredients)
}.filter {
it.calories == 500
}.maxOf {
goodness(it)
}
}
}
fun main() {
val testInput = """
Butterscotch: capacity -1, durability -2, flavor 6, texture 3, calories 8
Cinnamon: capacity 2, durability 3, flavor -2, texture -1, calories 3
""".trimIndent().split("\n")
println("------Tests------")
println(Day15.part1(testInput))
println(Day15.part2(testInput))
println("------Real------")
val input = readInput("resources/2015/day15")
println(Day15.part1(input))
println(Day15.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 3,017 | advent-of-code | Apache License 2.0 |
src/day12/Day12.kt | pocmo | 433,766,909 | false | {"Kotlin": 134886} | package day12
import java.io.File
data class Cave(
val name: String
) {
fun isEnd() = name == "end"
fun isStart() = name == "start"
fun isLarge(): Boolean = name[0].isUpperCase()
fun isSmall() = !isStart() && !isEnd() && name[0].isLowerCase()
}
fun readCavesFromFile(fileName: String): Map<Cave, MutableList<Cave>> {
return readCavesFromString(File(fileName)
.readText())
}
fun readCavesFromString(input: String): Map<Cave, MutableList<Cave>> {
val caveMap = mutableMapOf<Cave, MutableList<Cave>>()
input.lines()
.map { line ->
val (a, b) = line.split("-")
Pair(a, b)
}
.forEach { (a, b) ->
val caveA = Cave(a)
val caveB = Cave(b)
val connectionsA = caveMap.getOrDefault(caveA, mutableListOf())
connectionsA.add(caveB)
caveMap[caveA] = connectionsA
val connectionB = caveMap.getOrDefault(caveB, mutableListOf())
connectionB.add(caveA)
caveMap[caveB] = connectionB
}
return caveMap
}
fun List<Cave>.visitedOnlyOnce(cave: Cave): Boolean {
return count { current -> current == cave } == 1
}
fun Map<Cave, MutableList<Cave>>.continuePath(
cave: Cave,
path: List<Cave>,
visited: List<Cave>,
smallCaveToVisitAgain: Cave? = null
): List<List<Cave>> {
val newPath = path + cave
if (cave.isEnd()) {
return listOf(newPath)
}
val connections = (get(cave) ?: throw IllegalStateException("No connection from $cave"))
.filter { current ->
val onlyVisitedOnce = visited.visitedOnlyOnce(current)
val isSpecialSmallCave = current == smallCaveToVisitAgain
current.isLarge() || current !in visited || (isSpecialSmallCave && onlyVisitedOnce)
}
if (connections.isEmpty()) {
return emptyList()
}
val paths = mutableListOf<List<Cave>>()
for (current in connections) {
val newPaths = continuePath(
current,
newPath,
visited + cave,
smallCaveToVisitAgain
)
paths.addAll(newPaths)
}
return paths
}
fun Map<Cave, MutableList<Cave>>.findPaths(): List<List<Cave>> {
return continuePath(
Cave("start"),
listOf(),
listOf()
)
}
fun Map<Cave, MutableList<Cave>>.findPathsSpecial(): List<List<Cave>> {
val paths = mutableListOf<List<Cave>>()
keys.filter { cave -> cave.isSmall() }
.forEach { cave ->
val currentPaths = continuePath(
Cave("start"),
listOf(),
listOf(),
cave
)
paths.addAll(currentPaths)
}
return paths.distinct()
}
fun part1() {
val caveMap = readCavesFromFile("day12.txt")
val paths = caveMap.findPaths()
println("Paths = ${paths.size}")
}
fun part2() {
val caveMap = readCavesFromFile("day12.txt")
val paths = caveMap.findPathsSpecial()
println("Paths = ${paths.size}")
}
fun main() {
part2()
}
| 0 | Kotlin | 1 | 2 | 73bbb6a41229e5863e52388a19108041339a864e | 3,088 | AdventOfCode2021 | Apache License 2.0 |
src/Day12.kt | mkfsn | 573,042,358 | false | {"Kotlin": 29625} | import java.util.Queue
import java.util.LinkedList
enum class DIRECTION { UP, RIGHT, DOWN, LEFT }
fun main() {
data class Point(val x: Int, val y: Int) {
fun move(d: DIRECTION) = when (d) {
DIRECTION.UP -> Point(x - 1 , y)
DIRECTION.DOWN -> Point(x + 1, y)
DIRECTION.LEFT -> Point(x, y - 1)
DIRECTION.RIGHT -> Point(x, y + 1)
}
}
fun findIndexes(map: List<List<Char>>, value: Char): List<Point> {
val result: MutableList<Point> = mutableListOf()
map.forEachIndexed { i, row ->
row.forEachIndexed { j, col ->
if (col == value) result.add(Point(i, j))
}
}
return result
}
fun findIndex(map: List<List<Char>>, value: Char): Point? {
map.forEachIndexed { i, row -> row.indexOf(value).also { j -> if (j != -1) return Point(i, j) } }
return null
}
class Solution(input: List<String>) {
val heightMap: List<List<Char>>
init {
this.heightMap = input.map { it.toCharArray().toList() }
}
fun result(from: Char, to: Char): Int {
val startPoints = findIndexes(this.heightMap, from)
val end = findIndex(this.heightMap, to)!!
return startPoints.map { start -> findShortestPaths(start, end) }.filter { it != -1 }.min()
}
private fun findShortestPaths(start: Point, end: Point): Int {
val travelMap = this.heightMap.map { MutableList(it.size) { -1 } }
val queue: Queue<Point> = LinkedList<Point>()
val (row, col) = listOf(this.heightMap.size, this.heightMap[0].size)
fun movable(from: Point, to: Point): Boolean = when {
to.x < 0 || to.x >= row || to.y < 0 || to.y >= col -> false
from == end -> false
heightMap[from.x][from.y] == 'S' -> true
to == end && this.heightMap[from.x][from.y] == 'z' -> true
else -> to != end && this.heightMap[to.x][to.y] - this.heightMap[from.x][from.y] <= 1
}
queue.add(start).run { travelMap[start.x][start.y] = 0 }
while (queue.isNotEmpty()) {
val cur = queue.remove()!!
val step = travelMap[cur.x][cur.y] + 1
arrayOf(DIRECTION.UP, DIRECTION.RIGHT, DIRECTION.DOWN, DIRECTION.LEFT)
.map { cur.move(it) }
.filter { next -> movable(cur, next) }
.filter { next -> !(travelMap[next.x][next.y] != -1 && travelMap[next.x][next.y] < step) }
.forEach { next ->
travelMap[next.x][next.y] = step
if (!queue.contains(next)) queue.add(next)
}
}
return travelMap[end.x][end.y]
}
}
fun part1(input: List<String>) = Solution(input).result('S', 'E')
fun part2(input: List<String>) = Solution(input).result('a', 'E')
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
check(part1(input) == 408)
println(part1(input))
check(part2(input) == 399)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 3,349 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day15/Day15.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day15
import nl.sanderp.aoc.common.*
import java.util.*
import kotlin.math.min
fun main() {
val input = parse(readResource("Day15.txt"))
val (answer1, duration1) = measureDuration<Int> { shortestPath(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val input2 = expand(input)
val (answer2, duration2) = measureDuration<Int> { shortestPath(input2) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private fun parse(input: String): Map<Point2D, Int> {
val rows = input.lines()
return buildMap {
rows.forEachIndexed { y, row ->
row.forEachIndexed { x, c ->
put(x to y, c.asDigit())
}
}
}
}
private fun expand(input: Map<Point2D, Int>) = buildMap {
val (w, h) = (input.keys.maxOf { it.x } + 1) to (input.keys.maxOf { it.y } + 1)
for (x in 0 until (w * 5)) {
for (y in 0 until (h * 5)) {
val cx = x / w
val cy = y / h
val original = (x % w) to (y % h)
val risk = input[original]!! + cx + cy
put(x to y, if (risk > 9) risk - 9 else risk)
}
}
}
private data class Risk(val point: Point2D, val risk: Int) : Comparable<Risk> {
override fun compareTo(other: Risk): Int = compareValues(risk, other.risk)
}
private fun shortestPath(input: Map<Point2D, Int>): Int {
val end = input.keys.maxOf { it.x } to input.keys.maxOf { it.y }
val remaining = input.keys.toMutableSet()
val queue = PriorityQueue<Risk>()
queue.add(Risk(0 to 0, 0))
while (queue.isNotEmpty()) {
val next = queue.poll()
if (next.point == end) {
return next.risk
}
val neighbours = next.point.pointsNextTo().filter { remaining.contains(it) }
for (neighbour in neighbours) {
val risk = next.risk + input[neighbour]!!
val existing = queue.firstOrNull { it.point == neighbour }
if (existing != null) {
queue.remove(existing)
}
queue.add(Risk(neighbour, min(risk, existing?.risk ?: Int.MAX_VALUE)))
}
remaining.remove(next.point)
queue.removeAll { it.point == next.point }
}
return -1
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 2,292 | advent-of-code | MIT License |
src/Day03.kt | mcdimus | 572,064,601 | false | {"Kotlin": 32343} | import util.readInput
fun main() {
fun part1(input: List<String>) = input
.map { it.substring(0, it.length / 2) to it.substring(it.length / 2, it.length) }
.map { (first, second) -> first.first(second::contains) }
.sumOf { priority(it) }
fun part2(input: List<String>): Int {
return input
.windowed(size = 3, step = 3)
.map { group ->
group.map { rucksack -> rucksack.groupingBy { it }.eachCount() }
.fold(initial = mutableMapOf<Char, MutableList<Int>>()) { acc, map ->
map.forEach { (char, count) ->
acc.compute(char) { _, l -> (l ?: mutableListOf()).also { it.add(count) } }
}
acc
}
.filter { it.value.size == 3 }
.map { it.key to it.value.sum() }
.sortedBy { it.second }
.last()
.first
}.map { priority(it) }
.sum()
}
// 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))
}
private fun priority(it: Char) = when (it) {
in 'a'..'z' -> it.code - 96
in 'A'..'Z' -> it.code - 64 + 26
else -> 0
}
| 0 | Kotlin | 0 | 0 | dfa9cfda6626b0ee65014db73a388748b2319ed1 | 1,482 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | kuolemax | 573,740,719 | false | {"Kotlin": 21104} | fun main() {
fun parseGroupStringToRange(group: String): Pair<IntRange, IntRange> {
val pairs = group.split(",")
val pair1: IntRange = (pairs[0].split("-")[0].toInt()..pairs[0].split("-")[1].toInt())
val pair2: IntRange = (pairs[1].split("-")[0].toInt()..pairs[1].split("-")[1].toInt())
return pair1 to pair2
}
fun listContains(list1: IntRange, list2: IntRange): Boolean {
// 1. list1 ⊂ list2
// 2. list2 ⊂ list1
return (list1.first() >= list2.first() && list1.last() <= list2.last())
|| (list1.first() <= list2.first() && list1.last() >= list2.last())
}
fun listOverlap(group: String): Boolean {
val (pair1, pair2) = parseGroupStringToRange(group)
return pair1.first in pair2 || pair2.first in pair1
}
fun part1(input: List<String>): Int {
var totalScore = 0
input.forEach { group ->
val pairs = parseGroupStringToRange(group)
listContains(pairs.first, pairs.second).let {
if (it) totalScore++
}
}
return totalScore
}
fun part2(input: List<String>): Int {
val lambda = { group: String ->
if (listOverlap(group)) 1 else 0
}
return input.sumOf(lambda)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 1,584 | aoc2022--kotlin | Apache License 2.0 |
src/year2021/day10/Day10.kt | fadi426 | 433,496,346 | false | {"Kotlin": 44622} | package year2021.day01.day10
import util.assertTrue
import util.read2021DayInput
fun main() {
fun task1(input: List<String>, chunks: List<Pair<Char, Char>>): Int {
val lastCharsInCorruptedLines = input.mapNotNull { isCorrupted(it, chunks) }
return calculateCorruptedScore(lastCharsInCorruptedLines)
}
fun task2(input: List<String>, chunks: List<Pair<Char, Char>>): Long {
val incompleteLines = input.filter { isCorrupted(it, chunks) == null }
val lineCompletions = incompleteLines.map { completeLines(it, chunks) }
return calculateIncompleteScore(lineCompletions)
}
val input = read2021DayInput("Day10")
val chunks = mutableListOf(
Pair('(', ')'),
Pair('[', ']'),
Pair('{', '}'),
Pair('<', '>')
)
assertTrue(task1(input, chunks) == 413733)
assertTrue(task2(input, chunks) == 3354640192)
}
fun completeLines(line: String, chunks: List<Pair<Char, Char>>): List<Char> {
val lastChunks = mutableListOf<Char>()
for (i in line.indices) {
if (chunks.any { it.first == line[i] }) lastChunks.add(line[i])
if (chunks.any { it.second == line[i] }) {
if (chunks.first { it.second == line[i] }.first == lastChunks.last()) lastChunks.removeAt(lastChunks.size - 1)
}
}
return lastChunks.map { chunk -> chunks.first { it.first == chunk }.second }
}
fun isCorrupted(line: String, chunks: List<Pair<Char, Char>>): Char? {
val lastChunks = mutableListOf<Char>()
for (i in line.indices) {
if (chunks.any { it.first == line[i] }) lastChunks.add(line[i])
if (chunks.any { it.second == line[i] }) {
if (chunks.first { it.second == line[i] }.first == lastChunks.last()) lastChunks.removeAt(lastChunks.size - 1)
else return line[i]
}
}
return null
}
fun calculateCorruptedScore(list: List<Char>): Int {
val pointsSystem = mutableListOf(
Pair(')', 3),
Pair(']', 57),
Pair('}', 1197),
Pair('>', 25137)
)
return list.sumOf { char -> pointsSystem.first { char == it.first }.second }
}
fun calculateIncompleteScore(list: List<List<Char>>): Long {
val pointsSystem = mutableListOf(
Pair(')', 1L),
Pair(']', 2L),
Pair('}', 3L),
Pair('>', 4L)
)
val scoreList = list.map { chars ->
chars.reversed().map { char ->
pointsSystem.first { it.first == char }.second
}.reduce { acc, scorePoints -> acc * 5L + scorePoints }
}
return scoreList.sortedDescending()[scoreList.size / 2]
}
| 0 | Kotlin | 0 | 0 | acf8b6db03edd5ff72ee8cbde0372113824833b6 | 2,600 | advent-of-code-kotlin-template | Apache License 2.0 |
src/y2023/Day02.kt | a3nv | 574,208,224 | false | {"Kotlin": 34115, "Java": 1914} | package y2023
import utils.readInput
fun main() {
fun part1(input: List<String>): Int {
val limits = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14
)
var sum = 0
input.forEach { gameString ->
val gameData = gameString.split("Game")
gameData.filter { it.isNotBlank() }.forEach { game ->
val gameNumber = game.substringBefore(":").trim().toInt()
val gameSets = game.substringAfter(":").split(";")
var valid = true
gameSets.forEach { set ->
set.split(",").forEach { cubes: String ->
val cube: List<String> = cubes.split("\\s+".toRegex()).filter { it.isNotBlank() }
val color: String = cube.last()
val count: Int = cube.first().toInt()
if (count > limits[color]!!) {
valid = false
}
}
}
if (valid) {
sum += gameNumber
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sumOfPowers = 0
input.forEach { gameString ->
val gameData = gameString.split("Game")
gameData.filter { it.isNotBlank() }.forEach { game ->
val gameSets = game.substringAfter(":").split(";")
val max = mutableMapOf<String, Int>()
gameSets.forEach { set ->
set.split(",").forEach { cubes: String ->
val cube: List<String> = cubes.split("\\s+".toRegex()).filter { it.isNotBlank() }
val color: String = cube.last()
val count: Int = cube.first().toInt()
if (!max.containsKey(color) || max[color]!! < count) {
max[color] = count
}
}
}
val reduce = max.values.reduce { acc, i -> acc * i }
println("Reduced: $reduce")
sumOfPowers += reduce
}
}
println("Sum of powers: $sumOfPowers")
return sumOfPowers
}
// test if implementation meets criteria from the description, like:
var testInput = readInput("y2023", "Day02_test_part1")
check(part1(testInput) == 8)
println(part1(testInput))
check(part2(testInput) == 2286)
println(part2(testInput))
val input = readInput("y2023", "Day02")
check(part1(input) == 2563)
println(part1(input))
check(part2(input) == 70768)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ab2206ab5030ace967e08c7051becb4ae44aea39 | 2,735 | advent-of-code-kotlin | Apache License 2.0 |
src/Day07.kt | razvn | 573,166,955 | false | {"Kotlin": 27208} | fun main() {
val day = "Day07"
fun part1(input:List<String>): Long {
val root = dirTree(input)
val maxSize = 100000
val validDirs = getSubDirs(listOf(root), emptyList()) { it.size() <= maxSize } // getSubDirs(emptyList(), root) { it.size() <= maxSize }
// println("Valid dirs: $validDirs")
return validDirs.sumOf { it.size() }
}
fun part2(input: List<String>): Long {
val root = dirTree(input)
val diskSize = 70000000
val updateSize = 30000000
val freeSpace = diskSize - root.size()
// println("Free space: $freeSpace")
val needSpace = updateSize - freeSpace
// println("Need space: $needSpace")
val validDirs = getSubDirs(listOf(root), emptyList()) { it.size() >= needSpace }
// println("Valid dirs: $validDirs")
return validDirs.minOf { it.size() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
// println(part1(testInput))
// println(part2(testInput))
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
private tailrec fun getSubDirs(check: List<Dir>, result: List<Dir>, fn: (d: Dir) -> Boolean): List<Dir> {
return when {
check.isEmpty() -> result
else -> {
val head = check.first()
val newResult = if (fn(head)) result + head else result
getSubDirs(check.drop(1) + head.subDirs, newResult, fn)
}
}
}
private tailrec fun chDir(name: String, dir: Dir): Dir {
return when(name) {
"/" -> if (dir.name == "/" || dir.parentDir == null) dir else chDir(name, dir.parentDir)
".." -> dir.parentDir!!
else -> dir.subDirs.firstOrNull { it.name == name } ?: dir
}
}
private data class File(val name: String, val size: Int) {
constructor(line: String): this(line.split(" ").last(), line.split(" ").first().toInt())
}
private data class Dir(val name: String, val parentDir: Dir? = null) {
val subDirs: MutableList<Dir> = mutableListOf()
val files: MutableList<File> = mutableListOf()
fun size(): Long = files.sumOf { it.size } + subDirs.sumOf { it.size() }
}
private fun dirTree(input: List<String>): Dir {
val rootDir = Dir("/")
var currentDir: Dir = rootDir
input.forEach { line ->
// println("line: $line - $currentDir")
when {
line.startsWith("$ cd") -> currentDir = chDir(line.substringAfter("$ cd "), currentDir)
line.startsWith("$ ls") -> Unit
line.startsWith("dir ") -> with(Dir(line.substringAfter("dir "), currentDir)) {
currentDir.subDirs.add(this)
}
else -> currentDir.files.add(File(line))
}
}
return rootDir
}
| 0 | Kotlin | 0 | 0 | 73d1117b49111e5044273767a120142b5797a67b | 2,899 | aoc-2022-kotlin | Apache License 2.0 |
src/Day11.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class VirtualGalaxy(
val input: Input,
val exRows: List<Int>,
val exCols: List<Int>,
val expandSize: Long,
)
fun String.canExpand() = this.all { it == '.' }
fun Input.canExpand(i: Int) = this.map { it[i] }.joinToString("").canExpand()
fun String.expand(l: List<Int>): String {
return l.reversed().fold(this) { acc, i ->
acc.substring(0, i) + "." + acc.substring(i)
}
}
fun Input.expand(l: List<Int>): Input {
val row = CharArray(this[0].length) { '.' }.joinToString("")
return l.reversed().fold(this) { acc, i ->
acc.toMutableList().apply { add(i + 1, row) }
}
}
fun Input.expand(): Input {
val expandableCols = this[0].indices.filter { canExpand(it) }
val expandableRows = this.indices.filter { this[it].canExpand() }.also { println(it) }
return this.map { it.expand(expandableCols) }.expand(expandableRows)
}
fun RowCol.distance(rc: RowCol): Long {
return (abs(first - rc.first) + abs(second - rc.second)).toLong()
.also { println("$this -> $rc = $it") }
}
fun VirtualGalaxy.calcDistance(rc1: RowCol, rc2: RowCol): Long {
val rowRange = min(rc1.first, rc2.first)..max(rc1.first, rc2.first)
val colRange = min(rc1.second, rc2.second)..max(rc1.second, rc2.second)
val e1 = this.exRows.count { rowRange.contains(it) }
val d1 = (rowRange.last() - rowRange.first()) - e1 + (e1 * this.expandSize)
val e2 = this.exCols.count { colRange.contains(it) }
val d2 = (colRange.last() - colRange.first()) - e2 + (e2 * this.expandSize)
return (d1 + d2).also { println("$rc1 -> $rc2 = $it") }
}
fun main() {
fun part1(input: List<String>): Long {
val galaxy = input.expand()
// .onEach { println(it) }
val stars = mutableListOf<RowCol>()
galaxy.indices.forEach { i ->
galaxy[0].indices.forEach { j ->
if (galaxy.get(i to j) == '#')
stars.add(i to j)
}
}
return stars.indices.sumOf { i ->
val origin = stars[i]
(i..<stars.size).sumOf { origin.distance(stars[it]) }
}
}
fun part2(input: List<String>): Long {
val galaxy = VirtualGalaxy(
input = input,
exRows = input.indices.filter { input[it].canExpand() },
exCols = input[0].indices.filter { input.canExpand(it) },
expandSize = 1000000
)
val stars = mutableListOf<RowCol>()
input.indices.forEach { i ->
input[0].indices.forEach { j ->
if (input.get(i to j) == '#')
stars.add(i to j)
}
}
return stars.indices.sumOf { i ->
val origin = stars[i]
(i..<stars.size).sumOf { galaxy.calcDistance(origin, stars[it]) }
}
}
val input = readInput("Day11")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 2,980 | aoc-2023 | Apache License 2.0 |
src/Day19.kt | sabercon | 648,989,596 | false | null | private fun matchRule(ruleMap: Map<String, List<List<String>>>, message: String, rules: List<List<String>>): List<Int> {
return rules.flatMap { rs ->
rs.fold(listOf(0)) { acc, rule ->
acc.flatMap { size -> matchRule(ruleMap, message.substring(size), rule).map { size + it } }
}
}
}
private fun matchRule(ruleMap: Map<String, List<List<String>>>, message: String, rule: String): List<Int> {
return if (rule.startsWith("\"")) {
if (message.startsWith(rule[1])) listOf(1) else emptyList()
} else {
matchRule(ruleMap, message, ruleMap[rule]!!)
}
}
fun main() {
val input = readText("Day19")
val (rulesStr, messagesStr) = input.split(LINE_SEPARATOR + LINE_SEPARATOR)
val ruleMap = rulesStr.lines().associate {
val (id, rawRules) = it.split(": ")
val rules = rawRules.split(" | ").map { r -> r.split(" ") }
id to rules
}
val messages = messagesStr.lines()
messages.count { m -> matchRule(ruleMap, m, ruleMap["0"]!!).any { it == m.length } }.println()
val updatedRuleMap = ruleMap +
("8" to listOf(listOf("42"), listOf("42", "8"))) +
("11" to listOf(listOf("42", "31"), listOf("42", "11", "31")))
messages.count { m -> matchRule(updatedRuleMap, m, ruleMap["0"]!!).any { it == m.length } }.println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 1,342 | advent-of-code-2020 | MIT License |
src/Day07.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Long {
val root = parse(input)
var sum = 0L
fun run(folder: Folder) {
if (folder.size <= 100000L)
sum += folder.size
folder.subDirectories.forEach { run(it) }
}
run(root)
return sum
}
fun part2(input: List<String>): Long {
val root = parse(input)
val delta = max(30000000L - (70000000L - root.size), 0L)
var candidate: Folder? = null
fun run(folder: Folder) {
if (folder.size >= delta && (candidate == null || folder.size < candidate!!.size))
candidate = folder
folder.subDirectories.forEach { run(it) }
}
run(root)
return candidate!!.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input)) // 1667443
println(part2(input)) // 8998590
}
private fun parse(input: List<String>): Folder {
val root = Folder(null, "")
var current = root
input.partitionBy(keepDelim = true) { it.startsWith('$') }
.dropWhile { it.isEmpty() }
.map { it.first().substring(2) to it.drop(1).map { r -> r.split(' ', limit = 2) } }
.forEach { (cmd, result) ->
when (cmd) {
"cd /" -> current = root
"cd .." -> current = current.parent!!
"ls" -> result.forEach { (info, name) ->
when (info) {
"dir" -> current.subDirectories += Folder(current, name)
else -> current.files += File(current, info.toLong(), name)
}
}
else -> cmd.substring("cd ".length).run { current = current.subDirectories.first { it.name == this } }
}
}
return root
}
private data class File(val parent: Folder?, val size: Long, val name: String)
private data class Folder(
val parent: Folder?,
val name: String,
val files: MutableList<File> = mutableListOf(),
val subDirectories: MutableList<Folder> = mutableListOf(),
) {
val size: Long by lazy { files.sumOf(File::size) + subDirectories.sumOf(Folder::size) }
}
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 2,401 | advent-of-code-2022 | Apache License 2.0 |
src/Day15.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>, targetY: Int = 2000000): Int {
val parsed = input.map(::parse)
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
parsed.forEach { (sensor, beacon) ->
val dist = sensor.manhattanDist(beacon)
minX = min(minX, sensor.first - dist)
maxX = max(maxX, sensor.first + dist)
minX = min(minX, beacon.first - dist)
maxX = max(maxX, beacon.first + dist)
}
return (minX..maxX).map { it to targetY }.count {
parsed.any { (sensor, beacon) ->
val minDist = sensor.manhattanDist(beacon)
val dist = it.manhattanDist(sensor)
it != sensor && it != beacon && dist <= minDist
}
}
}
fun part2(input: List<String>): Long {
val parsed = input.map(::parse)
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var minY = Int.MAX_VALUE
var maxY = Int.MIN_VALUE
parsed.forEach { (sensor, _) ->
minX = min(minX, sensor.first)
maxX = max(maxX, sensor.first)
minY = min(minY, sensor.second)
maxY = max(maxY, sensor.second)
}
val xRange = max(0, minX)..min(maxX, 4000000)
val yRange = max(0, minY)..min(maxY, 4000000)
return parsed.asSequence()
.map { (sensor, beacon) -> ring(sensor, beacon) }
.flatten()
.filter { it.first in xRange && it.second in yRange }
.first {
parsed.all { (sensor, beacon) ->
val minDist = sensor.manhattanDist(beacon)
val dist = it.manhattanDist(sensor)
it != sensor && it != beacon && dist > minDist
}
}
.let { 4000000L * it.first + it.second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, targetY = 10) == 26)
check(part2(testInput) == 56000011L)
val input = readInput("Day15")
println(part1(input)) // 5461729
println(part2(input)) // 10621647166538
}
private fun ring(sensor: Point2D, beacon: Point2D): Sequence<Point2D> = sequence {
val dist = sensor.manhattanDist(beacon) + 1
for (yOffset in 0..dist) {
val xOffset = dist - yOffset
yield(sensor.first + xOffset to sensor.second + yOffset)
if (xOffset != 0) {
yield(sensor.first - xOffset to sensor.second + yOffset)
}
if (yOffset != 0) {
yield(sensor.first + xOffset to sensor.second - yOffset)
yield(sensor.first - xOffset to sensor.second - yOffset)
}
}
}
private val regex = """^Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)${'$'}""".toRegex()
private fun parse(line: String): Pair<Point2D, Point2D> = regex.matchEntire(line)!!
.groupValues
.drop(1)
.map { it.toInt() }
.let { (sensorX, sensorY, beaconX, beaconY) -> (sensorX to sensorY) to (beaconX to beaconY) }
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 3,172 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun parseToken(token: String): Pair<Int, Int> {
var head = 0
var tail = token.length
for (c in token) {
when (c) {
'[' -> head++
']' -> tail--
}
}
return when (head) {
tail -> Pair(0, -1)
else -> Pair(tail - head, token.substring(head, tail).toInt())
}
}
fun compareTokens(aTokens: List<Pair<Int, Int>>, bTokens: List<Pair<Int, Int>>): Boolean {
var aDepth = 0
var bDepth = 0
for ((aToken, bToken) in aTokens.zip(bTokens)) {
when {
aDepth > bDepth -> return false
aDepth < bDepth -> return true
aToken.second > bToken.second -> return false
aToken.second < bToken.second -> return true
}
aDepth += aToken.first
bDepth += bToken.first
}
return when {
aDepth > bDepth -> false
aDepth < bDepth -> true
else -> aTokens.size < bTokens.size
}
}
fun part1(input: List<List<String>>): Int {
return input.withIndex().filter { (_, tokenStrings) ->
val aTokens = tokenStrings[0].split(",").map { parseToken(it) }
val bTokens = tokenStrings[1].split(",").map { parseToken(it) }
compareTokens(aTokens, bTokens)
}.sumOf { it.index + 1 }
}
fun part2(input: List<String>): Int {
val startToken = listOf(parseToken("[[2]]"))
val endToken = listOf(parseToken("[[6]]"))
val tokens = input
.filter { it.isNotEmpty() }
.map { tl -> tl.split(",").map { t -> parseToken(t) }.toList() }
var start = 1
var end = tokens.size + 2
tokens.forEach {
if (compareTokens(it, startToken)) {
start++
} else if (compareTokens(endToken, it)) {
end--
}
}
return start * end
}
val testInput = readInputDoubleNewline("Day13_test")
check(part1(testInput) == 13)
val testInput2 = readInput("Day13_test")
check(part2(testInput2) == 140)
val input = readInputDoubleNewline("Day13")
println(part1(input))
val input2 = readInput("Day13")
println(part2(input2))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 2,340 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | fun main() {
fun solve(input: List<String>, reverse: Boolean = false): String {
val (stacks, instructions) = parseInput(input)
instructions.forEach {
val from = stacks[it.fromIndex]
val to = stacks[it.toIndex]
(1..it.quantity)
.map { from.removeFirst() }
.run { if (reverse) reversed() else this }
.forEach { c -> to.addFirst(c) }
}
return output(stacks)
}
fun part1(input: List<String>) = solve(input)
fun part2(input: List<String>) = solve(input, true)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input)) // SBPQRSCDF
println(part2(input)) // RGLVRCQSB
}
private fun output(stacks: List<ArrayDeque<Char>>) = stacks.mapNotNull { it.firstOrNull() }.joinToString(separator = "")
private fun parseInput(input: List<String>): Pair<List<ArrayDeque<Char>>, List<Instruction>> {
val (initialStacks, instructions) = input.partitionBy { it.isBlank() }
val n = initialStacks.last().trim().replace(" ", ",").split(',').size
return parseStacks(n, initialStacks) to instructions.map(::parseInstruction)
}
private fun parseStacks(n: Int, initialStacks: List<String>) = (1..n).map { ArrayDeque<Char>() }.apply {
initialStacks.asSequence()
.take(initialStacks.size - 1)
.map { line -> line.chunked(4) { it[1] }.withIndex() }
.flatten()
.filter { it.value != ' ' }
.forEach { this[it.index].addLast(it.value) }
}
private fun parseInstruction(str: String) = str.split(' ')
.let { Instruction(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) }
private data class Instruction(val quantity: Int, val fromIndex: Int, val toIndex: Int)
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 1,927 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | winnerwinter | 573,917,144 | false | {"Kotlin": 20685} | fun main() {
fun part1(): Int {
val testInput = readInput("Day03_test")
val test_ans = computePrioritiesOfMisplacedItems(testInput.toRucksacks())
check(test_ans == 157)
val input = readInput("Day03")
val ans = computePrioritiesOfMisplacedItems(input.toRucksacks())
return ans
}
fun part2(): Int {
val testInput = readInput("Day03_test")
val test_ans = computePrioritiesOfTeamBadges(testInput.toRucksacks())
check(test_ans == 70)
val input = readInput("Day03")
val ans = computePrioritiesOfTeamBadges(input.toRucksacks())
return ans
}
println(part1())
println(part2())
}
///// Part 1
data class Rucksack(val items: List<Char>) {
constructor(items: String) : this(items.toList())
init {
check(items.isNotEmpty())
check(items.toList().size % 2 == 0)
}
val numItems: Int = items.size
val compartment1: List<Char> = items.subList(0, numItems / 2)
val compartment2: List<Char> = items.subList(numItems / 2, numItems)
}
fun List<String>.toRucksacks() = map { Rucksack(it) }
fun Char.toPriority(): Int = if (isLowerCase()) { code - 96 } else { code - 38 }
fun Rucksack.findMisplacedItem(): Char = requireNotNull(compartment1.find { it in compartment2 })
fun computePriorities(extractItems: () -> List<Char>): Int =
extractItems().sumOf { it.toPriority() }
fun computePrioritiesOfMisplacedItems(rucksacks: List<Rucksack>): Int =
computePriorities { rucksacks.map { it.findMisplacedItem() } }
///// Part 2
fun computePrioritiesOfTeamBadges(rucksacks: List<Rucksack>): Int {
val teams = rucksacks.chunked(3).map { it.sortedBy { it.items.size } }
val badges = teams.map { (a, b, c) ->
computePriorities {
listOfNotNull(a.items.find { it in b.items && it in c.items })
}
}
return badges.sum()
}
| 0 | Kotlin | 0 | 0 | a019e5006998224748bcafc1c07011cc1f02aa50 | 1,911 | advent-of-code-22 | Apache License 2.0 |
src/day16/Day16.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day16
import day16.Operation.*
import println
import readInput
import readInputAsText
enum class Operation(val id: String) { SUM("000"), PRODUCT("001"), MIN("010"), MAX("011"), LIT("100"), GT("101"), LT("110"), EQ("111")}
sealed interface Packet { val version: Int; val length: Int }
data class OperationPacket(override val version: Int, override val length: Int, val operation: Operation, val packets: List<Packet>) : Packet
data class LiteralPacket(override val version: Int, override val length: Int, val value: Long) : Packet
fun String.toBinaryString() = this.map { Integer.decode("0x${it}").toString(2).padStart(4, '0') }
.joinToString("")
fun String.readPackets(maxPackets: Int? = null): List<Packet> {
var remaining = this;
val packets = mutableListOf<Packet>()
while ((maxPackets == null || packets.size < maxPackets) && !remaining.matches("^0*$".toRegex())) {
val packet = remaining.readPacket()
packets.add(packet)
remaining = remaining.substring(packet.length)
}
return packets
}
fun String.readPacket() = operation().let { if (it == LIT) this.readLiteralPacket() else this.readOperationPacket() }
fun String.readOperationPacket(): Packet {
return if (this[6] == '0') {
val packetsLength = toDecimal(7, 22)
val packets = substring(22, 22 + packetsLength).readPackets()
OperationPacket(version(), 22 + packetsLength, operation(), packets)
} else {
val packets = substring(18).readPackets(toDecimal(7, 18))
OperationPacket(version(), 18 + packets.sumOf { it.length }, operation(), packets)
}
}
fun String.readLiteralPacket(): LiteralPacket {
val windowed = subSequence(6, length).windowed(5, 5)
val groups = windowed.indexOfFirst { it.startsWith('0') } + 1
val value = windowed.take(groups).joinToString("") { it.substring(1) }.toLong(2)
return LiteralPacket(version(), 6 + 5 * groups, value)
}
fun String.toDecimal(startInd: Int, endInd: Int):Int = Integer.valueOf(substring(startInd, endInd), 2)
fun String.version() = substring(0, 3).toInt(2)
fun String.operation() = values().first { it.id == substring(3, 6) }
fun sumOfVersions(packet: Packet): Int = when (packet) {
is LiteralPacket -> packet.version
is OperationPacket -> packet.version + packet.packets.sumOf { sumOfVersions(it) }
}
fun getValue(packet: Packet): Long = when (packet) {
is LiteralPacket -> packet.value
is OperationPacket -> when (packet.operation) {
SUM -> packet.packets.sumOf { getValue(it) }
PRODUCT -> packet.packets.map { getValue(it) }.reduce(Long::times)
MIN -> packet.packets.minOf { getValue(it) }
MAX -> packet.packets.maxOf { getValue(it) }
LIT -> getValue(packet)
GT -> if (getValue(packet.packets[0]) > getValue(packet.packets[1])) 1 else 0
LT -> if (getValue(packet.packets[0]) < getValue(packet.packets[1])) 1 else 0
EQ -> if (getValue(packet.packets[0]) == getValue(packet.packets[1])) 1 else 0
}
}
fun part1(input: String): Int {
return input.toBinaryString().readPackets().sumOf { sumOfVersions(it) };
}
fun part2(input: String): Long {
return input.toBinaryString().readPackets().sumOf { getValue(it) }
}
fun main() {
check(readInput("day16/input_test_part1").map { part1(it) } == listOf(16, 12, 23, 31))
check(readInput("day16/input_test_part2").map { part2(it) } == listOf(3L, 54L, 7L, 9L, 1L, 0L, 0L, 1L))
val input = readInputAsText("day16/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 3,554 | advent-of-code-2021 | Apache License 2.0 |
src/Day23.kt | underwindfall | 573,471,357 | false | {"Kotlin": 42718} | fun main() {
fun List<String>.parse() = mapIndexed { y, row ->
row.mapIndexedNotNull { x, cell -> if (cell == '#') y to x else null }
}.flatten().toSet()
fun Pair<Int, Int>.adjNorth() = listOf(
first - 1 to second,
first - 1 to second - 1,
first - 1 to second + 1,
)
fun Pair<Int, Int>.adjSouth() = listOf(
first + 1 to second,
first + 1 to second - 1,
first + 1 to second + 1,
)
fun Pair<Int, Int>.adjWest() = listOf(
first to second - 1,
first - 1 to second - 1,
first + 1 to second - 1,
)
fun Pair<Int, Int>.adjEast() = listOf(
first to second + 1,
first - 1 to second + 1,
first + 1 to second + 1,
)
fun Set<Pair<Int, Int>>.considerMove(position: Pair<Int, Int>, iteration: Int): Pair<Int, Int>? {
val moves = listOf(position.adjNorth(), position.adjSouth(), position.adjWest(), position.adjEast())
if (moves.flatten().none { cell -> contains(cell) }) return null
val shift = iteration % moves.size
val shiftedMoves = moves.subList(shift, moves.size) + moves.subList(0, shift)
return shiftedMoves.firstOrNull { it.none { cell -> contains(cell) } }?.first()
}
fun part1(input: List<String>) = input.parse().let { startElves ->
var elves = startElves
repeat(10) { iteration ->
val consideredMoves = elves.map { elves.considerMove(it, iteration) ?: it }
elves = elves.mapIndexed { index, elf ->
val consideredMove = consideredMoves[index]
if (consideredMoves.count { it == consideredMove } == 1) consideredMove else elf
}.toSet()
}
(elves.maxOf { it.first } - elves.minOf { it.first } + 1) * (elves.maxOf { it.second } - elves.minOf { it.second } + 1) - elves.size
}
fun part2(input: List<String>) = input.parse().let { startElves ->
var elves = startElves
var iteration = 0
while (true) {
val consideredMoves = elves.map { elves.considerMove(it, iteration) ?: it }
if (consideredMoves.toSet() == elves) break
elves = elves.mapIndexed { index, elf ->
val consideredMove = consideredMoves[index]
if (consideredMoves.count { it == consideredMove } == 1) consideredMove else elf
}.toSet()
iteration++
}
iteration + 1
}
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0e7caf00319ce99c6772add017c6dd3c933b96f0 | 2,561 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | trosendo | 572,903,458 | false | {"Kotlin": 26100} | import kotlin.math.abs
private data class ForestTree(
val height: Int,
val yPos: Int,
val xPos: Int,
val id: Int
)
private data class TreeRow(
val items: List<ForestTree>
)
fun main() {
var count = 0
val forest = readInputAsList("Day08").mapIndexed { y, row ->
TreeRow(row.mapIndexed { x, char ->
ForestTree(char.toString().toInt(), x, y, count++)
})
}
println("Result of part1: " + part1(forest).filter { it.value }.size)
println("Result of part2: " + part2(forest).values.max())
}
private fun part1(forest: List<TreeRow>): Map<ForestTree, Boolean> {
val visibleTrees = forest.flatMap { row ->
row.items.map { tree ->
val treesInRow = row.items
val treesInColumn =
forest.flatMap { treeRow -> treeRow.items.filter { it.yPos == tree.yPos } }//.filter { it.items..yPos != tree.yPos }.flatMap { it.items }.filter { it.xPos == tree.xPos }
val highestTreeAbove = treesInRow.filter { it.yPos < tree.yPos }.maxByOrNull { it.height }?.height ?: -1
val highestTreesBelow = treesInRow.filter { it.yPos > tree.yPos }.maxByOrNull { it.height }?.height ?: -1
val highestTreesToTheLeft =
treesInColumn.filter { it.xPos < tree.xPos }.maxByOrNull { it.height }?.height ?: -1
val highestTreesToTheRight =
treesInColumn.filter { it.xPos > tree.xPos }.maxByOrNull { it.height }?.height ?: -1
val visibleFromAbove = highestTreeAbove < tree.height
val visibleFromBelow = highestTreesBelow < tree.height
val visibleFromThRight = highestTreesToTheRight < tree.height
val visibleFromTheLeft = highestTreesToTheLeft < tree.height
tree to (visibleFromAbove || visibleFromBelow || visibleFromThRight || visibleFromTheLeft)
}
}.toMap()
return visibleTrees
}
private fun part2(forest: List<TreeRow>): Map<ForestTree, Int> {
val visibleTrees = forest.flatMap { row ->
row.items.map { tree ->
val treesInRow = row.items
val treesInColumn =
forest.flatMap { treeRow -> treeRow.items.filter { it.yPos == tree.yPos } }//.filter { it.items..yPos != tree.yPos }.flatMap { it.items }.filter { it.xPos == tree.xPos }
val treesToTheLeft =
treesInRow.filter { it.yPos < tree.yPos }
val treesToTheRight =
treesInRow.filter { it.yPos > tree.yPos }
val treesAbove =
treesInColumn.filter { it.xPos < tree.xPos }
val treesBelow =
treesInColumn.filter { it.xPos > tree.xPos }
val diffToHighestTreeAbove = treesAbove.reversed().firstOrNull {it.height >= tree.height}?.let { abs(it.xPos - tree.xPos) } ?: (tree.xPos)
val diffToHighestTreeBelow =
treesBelow.firstOrNull {it.height >= tree.height}?.let { abs(it.xPos - tree.xPos) } ?: (row.items.size - (tree.xPos + 1))
val diffToHighestTreeToTheLeft = treesToTheLeft.reversed().firstOrNull {it.height >= tree.height}?.let { abs(it.yPos - tree.yPos) } ?: (tree.yPos)
val diffToHighestTreeToTheRight =
treesToTheRight.firstOrNull {it.height >= tree.height}?.let { abs(it.yPos - tree.yPos) } ?: (treesInRow.size - (tree.yPos + 1))
val result =
diffToHighestTreeAbove * diffToHighestTreeBelow * diffToHighestTreeToTheLeft * diffToHighestTreeToTheRight
tree to result
}
}.toMap()
return visibleTrees
} | 0 | Kotlin | 0 | 0 | ea66a6f6179dc131a73f884c10acf3eef8e66a43 | 3,587 | AoC-2022 | Apache License 2.0 |
src/day02/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day02
import println
import readInput
import kotlin.streams.asSequence
enum class CubeColor {
RED, GREEN, BLUE;
companion object {
fun find(colorString: String): CubeColor? {
return values().find { it.name.equals(colorString, ignoreCase = true) }
}
}
}
fun main() {
class CubeSet(val cubes: Map<CubeColor, Int>) {
fun isPossible(bagContent: CubeSet): Boolean {
return !cubes.entries.stream().anyMatch {
it.value > bagContent.cubes[it.key]!!
}
}
}
class Game (val id: Int, val draws: List<CubeSet>) {
fun calculatePowerOfCubeSet(): Int {
val cubeSet = mutableMapOf(CubeColor.RED to 0, CubeColor.GREEN to 0, CubeColor.BLUE to 0)
draws.forEach { draw ->
draw.cubes.forEach {
if (it.value > cubeSet[it.key]!!) {
cubeSet[it.key] = it.value
}
}
}
return cubeSet.values.fold(1) { acc, element -> acc * element }
}
}
fun parseGame(input: String) : Game {
val gamePattern = Regex("Game (\\d+): (.*)")
val match = gamePattern.findAll(input).first()
val gameId = match.groupValues[1].toInt()
val colorInfo = match.groupValues[2]
val colorEntries = colorInfo.split(";")
val draws = mutableListOf<CubeSet>();
for (entry in colorEntries) {
val colorPattern = Regex("(\\d+) (\\w+)")
val colorMatch = colorPattern.findAll(entry)
val cubesInfo = mutableMapOf<CubeColor, Int>()
for (colorMatchResult in colorMatch) {
val quantity = colorMatchResult.groupValues[1].toInt()
val color = colorMatchResult.groupValues[2]
cubesInfo[CubeColor.find(color)!!] = quantity
}
draws.add(CubeSet(cubesInfo))
}
return Game(gameId, draws);
}
fun validateGame(game: Game, bagContent: CubeSet): Boolean {
return !game.draws.any { !it.isPossible(bagContent)}
}
fun checkGames(input: List<String>, bagContent: CubeSet): Int {
val games = input.stream().map{parseGame(it)}.toList()
return games.stream().filter{validateGame(it, bagContent)}.map { it.id }.asSequence().sum()
}
fun calculateSumOfPowersOfCubeSet(input: List<String>): Int {
val games = input.stream().map{parseGame(it)}.toList()
return games.stream().map {it.calculatePowerOfCubeSet()}.asSequence().sum()
}
val testInput1 = readInput("day02/test1")
check(checkGames(testInput1, CubeSet(mapOf(CubeColor.RED to 12, CubeColor.GREEN to 13, CubeColor.BLUE to 14))) == 8)
val input1 = readInput("day02/input")
checkGames(input1, CubeSet(mapOf(CubeColor.RED to 12, CubeColor.GREEN to 13, CubeColor.BLUE to 14))).println()
check(calculateSumOfPowersOfCubeSet(testInput1) == 2286)
calculateSumOfPowersOfCubeSet(input1).println()
}
| 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 3,027 | advent-of-code-2023 | Apache License 2.0 |
src/Day15.kt | jorgecastrejon | 573,097,701 | false | {"Kotlin": 33669} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val list = parseInput(input)
val intervals = mutableListOf<IntRange>()
for ((sX, sY, bX, bY) in list) {
val currentDistance = abs(bX - sX) + abs(bY - sY)
val distanceToRow = abs(2000000 - sY)
val diff = currentDistance - distanceToRow
if (diff >= 0) {
intervals.add((sX - diff)..(sX + diff))
}
}
return intervals.reduce { acc, next -> minOf(acc.first, next.first)..maxOf(acc.last, next.last) }
.let { it.last - it.first }
}
fun part2(input: List<String>): Long {
val size = 4000000
val list = parseInput(input)
return list.firstNotNullOf { (sX, sY, bX, bY) ->
outerBounds(sX, sY, d = abs(bX - sX) + abs(bY - sY) + 1)
.asSequence()
.filter { (x, y) -> x in 0..size && y in 0..size }
.firstOrNull { (x, y) ->
list.all { (s1, s2, b1, b2) ->
val d1 = abs(b1 - s1) + abs(b2 - s2)
val d2 = abs(x - s1) + abs(y - s2)
d2 > d1
}
}
}.let { it.first * 4000000L + it.second }
}
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
fun outerBounds(x: Int, y: Int, d: Int): List<Pair<Int, Int>> {
val vertices = listOf(x + d to y, x to y + d, x - d to y, x to y - d)
val iterations = listOf(-1 to 1, -1 to -1, 1 to -1, 1 to 1)
return vertices.zip(iterations)
.map { (vertex, iteration) ->
(0 until d).map { vertex.first + iteration.first * it to vertex.second + iteration.second * it }
}.flatten()
}
private fun parseInput(input: List<String>): List<List<Int>> =
input.map { line ->
line.replace(":", ",")
.filter { it.isDigit() || it == ',' || it == '-' }
.split(",").map(String::toInt)
} | 0 | Kotlin | 0 | 0 | d83b6cea997bd18956141fa10e9188a82c138035 | 2,041 | aoc-2022 | Apache License 2.0 |
src/Day15.kt | kmakma | 574,238,598 | false | null | import kotlin.math.abs
fun main() {
data class Interval(var start: Int, var end: Int) {
fun limit(minStart: Int, maxEnd: Int) {
start = maxOf(minStart, start)
end = minOf(maxEnd, end)
}
fun size(): Int {
return 1 + end - start
}
}
fun List<Interval>.maxReduce(): List<Interval> {
if (isEmpty()) return emptyList()
val iterator = this.sortedWith(compareBy({ it.start }, { it.end })).listIterator()
var last = iterator.next()
val reduced = mutableListOf(last)
while (iterator.hasNext()) {
val next = iterator.next()
if (next.start <= last.end) {
last.end = maxOf(next.end, last.end)
} else {
reduced.add(next)
last = next
}
}
return reduced
}
fun parseSensorsBeacons(input: List<String>): Map<Vector2D, Vector2D> {
return input.associate { line ->
val split = line.split("=", ",", ":")
Vector2D(split[1].toInt(), split[3].toInt()) to Vector2D(split[5].toInt(), split[7].toInt())
}
}
fun rangeAtY(sensor: Vector2D, distance: Int, y: Int): Interval? {
val yDist = abs(sensor.y - y)
if (yDist > distance) return null
val restDist = distance - yDist
return Interval(sensor.x - restDist, sensor.x + restDist)
}
fun part1(input: List<String>): Int {
val sensorToBeacons = parseSensorsBeacons(input)
val beaconsCount = sensorToBeacons.values.filter { it.y == 2_000_000 }.toSet().size
val sensorToDistances = sensorToBeacons.mapValues { (s, b) -> s.manhattenDistance(b) }
return sensorToDistances
.mapNotNull { (s, d) -> rangeAtY(s, d, 2_000_000) }
.maxReduce()
.sumOf { it.size() } - beaconsCount
}
fun part2(input: List<String>): Long {
val sensorToDistances = parseSensorsBeacons(input).mapValues { (s, b) -> s.manhattenDistance(b) }
for (y in 0..4_000_000) {
val intervals = sensorToDistances
.mapNotNull { (s, d) -> rangeAtY(s, d, y) }
.maxReduce()
.onEach { it.limit(0, 4_000_000) }
if (intervals.size > 1) {
return 4_000_000L * (intervals.first().end + 1) + y
}
}
return -1L
}
val input = readInput("Day15")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 950ffbce2149df9a7df3aac9289c9a5b38e29135 | 2,519 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | jorander | 571,715,475 | false | {"Kotlin": 28471} | import Outcome.*
import Outcome.Companion.outcome
import Shape.Companion.myShape
import Shape.Companion.opponentShape
enum class Shape(val opponentCode: String, val myCode: String, val score: Int, val winsOver: Int) {
ROCK("A", "X", 1, 2),
PAPER("B", "Y", 2, 0),
SCISSORS("C", "Z", 3, 1);
companion object {
fun opponentShape(opponentCode: String) = values().find { it.opponentCode == opponentCode }!!
fun myShape(myCode: String) = values().find { it.myCode == myCode }!!
fun winsOver(shape: Shape) = values().find { it.winsOver == shape.ordinal }!!
fun loosesTo(shape: Shape) = values().find { it.ordinal == shape.winsOver }!!
}
}
enum class Outcome(val code: String) {
WIN("Z"),
DRAW("Y"),
LOOSE("X");
companion object {
fun outcome(code: String) = values().find { it.code == code }!!
}
}
fun main() {
val day = "Day02"
fun calculateScore(opponentShape: Shape, myShape: Shape) =
myShape.score + when {
myShape.winsOver == opponentShape.ordinal -> 6
myShape == opponentShape -> 3
else -> 0
}
fun part1(input: List<String>): Int {
return input.map { inputRow ->
val (opponentCode, myCode) = inputRow.split(" ")
opponentShape(opponentCode) to myShape(myCode)
}.sumOf { (opponentShape, myShape) -> calculateScore(opponentShape, myShape) }
}
fun part2(input: List<String>): Int {
fun findMyShape(outcome: Outcome, opponentShape: Shape) = when (outcome) {
WIN -> Shape.winsOver(opponentShape)
DRAW -> opponentShape
LOOSE -> Shape.loosesTo(opponentShape)
}
return input.map { inputRow ->
val (opponentCode, outcomeCode) = inputRow.split(" ")
opponentShape(opponentCode) to outcome(outcomeCode)
}
.map { (opponentShape, outcome) -> opponentShape to findMyShape(outcome, opponentShape) }
.sumOf { (opponentShape, myShape) -> calculateScore(opponentShape, myShape) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val input = readInput(day)
check(part1(testInput) == 15)
val result1 = part1(input)
println(result1)
check(result1 == 14264)
check(part2(testInput) == 12)
val result2 = part2(input)
println(result2)
check(result2 == 12382)
}
| 0 | Kotlin | 0 | 0 | 1681218293cce611b2c0467924e4c0207f47e00c | 2,468 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/day22.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Component4
import utils.Component4.X
import utils.Component4.Y
import utils.Component4.Z
import utils.Parser
import utils.Point3i
import utils.Solution
import utils.Vec4i
import utils.flipped
import utils.mapItems
fun main() {
Day22.run()
}
object Day22 : Solution<List<Day22.Command>>() {
override val name = "day22"
override val parser = Parser.lines
.mapItems { line ->
val (on, cuboidStr) = line.split(" ")
Command(on == "on", Cuboid.fromString(cuboidStr.trim()))
}
data class Cuboid(val start: Vec4i, val end: Vec4i) {
val valid = end.x > start.x && end.y > start.y && end.z > start.z
fun volume(): Long {
return (end.x.toLong() - start.x) * (end.y - start.y) * (end.z - start.z)
}
fun cut(component: Component4, value: Int): Pair<Cuboid?, Cuboid?> {
return Cuboid(start, end.copy(component, minOf(value, end[component]))).takeIf { it.valid } to
Cuboid(start.copy(component, maxOf(value, start[component])), end).takeIf { it.valid }
}
operator fun minus(right: Cuboid): List<Cuboid> {
if ((this intersect right) == null) return listOf(this)
val finalCut = ArrayList<Cuboid>(6)
var cut = this
for (c in listOf(X, Y, Z)) {
for (start in listOf(true, false)) {
val (l, r) = if (start) cut.cut(c, right.start[c]) else cut.cut(c, right.end[c]).flipped
if (l != null) { finalCut.add(l) }
if (r == null) { return finalCut }
cut = r
}
}
return finalCut
}
infix fun intersect(right: Cuboid): Cuboid? {
return Cuboid(
Point3i(maxOf(start.x, right.start.x), maxOf(start.y, right.start.y), maxOf(start.z, right.start.z)),
Point3i(minOf(end.x, right.end.x), minOf(end.y, right.end.y), minOf(end.z, right.end.z)),
).takeIf { it.valid }
}
companion object {
fun fromString(str: String): Cuboid {
val components = str.split(",").map { component ->
val (name, value) = component.split("=")
val (from, to) = value.split("..")
name to (from to to)
}.toMap()
return Cuboid(
Point3i(components["x"]!!.first.toInt(), components["y"]!!.first.toInt(), components["z"]!!.first.toInt()),
Point3i(components["x"]!!.second.toInt() + 1, components["y"]!!.second.toInt() + 1, components["z"]!!.second.toInt() + 1),
)
}
}
}
data class Command(val on: Boolean, val cuboid: Cuboid)
fun solve(input: List<Command>): Long {
var cuboids = listOf<Cuboid>()
input.forEachIndexed { _, cmd ->
val (on, cuboid) = cmd
val new = mutableListOf<Cuboid>()
cuboids.forEach {
new.addAll(it - cuboid)
}
if (on) {
new.add(cuboid)
}
cuboids = new
}
return cuboids.sumOf { it.volume() }
}
override fun part1(input: List<Command>): Long {
val pt1Input = input.map { (cmd, cuboid) -> Command(cmd, Cuboid(
cuboid.start.coerceAtLeast(Point3i(-50, -50, -50)),
cuboid.end.coerceAtMost(Point3i(50, 50, 50))
))
}.filter { (_, cuboid) -> cuboid.valid }
return solve(pt1Input)
}
override fun part2(input: List<Command>): Long {
return solve(input)
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,262 | aoc_kotlin | MIT License |
src/day19/Day19.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day19
import utils.*
import kotlin.math.ceil
val ROBOT_REGEX =
"""Each (\w+) robot costs (\d+) (\w+)(?: and (\d+) (\w+))?.""".toRegex()
val MATERIALS = listOf("ore", "clay", "obsidian", "geode")
data class State(
val robots: Map<String, Int>,
val materials: Map<String, Int>,
val time: Int
) : Comparable<State> {
fun canDoBetter(maxGeodes: Int) =
(
materials["geode"]!!
+ time * (time + 2 * robots["geode"]!! - 1) / 2
) > maxGeodes
fun getSubStates(
robotsCosts: Map<String, Map<String, Int>>,
maxCosts: Map<String, Int>
) = sequence {
val buildingStates = robotsCosts.mapNotNull { (material, costs) ->
if (
costs.any { (name, cost) ->
materials[name]!! < cost && robots[name]!! == 0
}
|| maxCosts[material]?.let { robots[material]!! == it } == true
)
return@mapNotNull null
val duration = 1 + costs.maxOf { (name, cost) ->
maxOf(
0,
ceil(
1.0 * (cost - materials[name]!!) / robots[name]!!
).toInt()
)
}
if (duration > time)
return@mapNotNull null
return@mapNotNull State(
robots + mapOf(material to robots[material]!! + 1),
MATERIALS.associateWith { name ->
(
materials[name]!!
+ robots[name]!! * duration
- (costs[name] ?: 0)
)
},
time - duration
)
}
if (buildingStates.isNotEmpty())
yieldAll(buildingStates)
else
yield(State(
robots,
MATERIALS.associateWith { name ->
materials[name]!! + robots[name]!! * time
},
0
))
}
override fun compareTo(other: State): Int {
if (time != other.time)
return other.time - time
materials.values.zip(other.materials.values).reversed().map { (a, b) ->
if (a != b)
return b - a
}
robots.values.zip(other.robots.values).reversed().map { (a, b) ->
if (a != b)
return b - a
}
return 0
}
}
fun parseBlueprints(
input: List<String>
): Map<Int, Map<String, Map<String, Int>>> =
input.associate { line ->
val (title, contents) = line.split(": ")
val id = title.substring(10).toInt()
val matches = ROBOT_REGEX.findAll(contents).map {
it.groupValues.drop(1).filter { match -> match.isNotEmpty() }
}
val materials = matches.associate { parts ->
val costs = parts
.drop(1)
.chunked(2)
.associate { Pair(it[1], it[0].toInt()) }
Pair(parts[0], costs)
}
id to materials
}
fun solve(robotsCosts: Map<String, Map<String, Int>>, time: Int): Int {
val robots = MATERIALS.associateWith { if (it == "ore") 1 else 0 }
val materials = MATERIALS.associateWith { 0 }
val maxCosts = MATERIALS
.take(3)
.associateWith { material ->
robotsCosts.values.maxOf { costs -> costs[material] ?: 0 }
}
var maxGeodes = 0
generateSequence(listOf(State(robots, materials, time))) { stack ->
stack
.flatMap { it.getSubStates(robotsCosts, maxCosts) }
.onEach { state ->
if (state.time == 0)
maxGeodes = maxOf(maxGeodes, state.materials["geode"]!!)
}
.filter { state ->
state.time > 0 && state.canDoBetter(maxGeodes)
}
.sortedDescending()
}.find { it.isEmpty() }
return maxGeodes
}
fun part1(input: List<String>): Int {
val blueprints = parseBlueprints(input)
return blueprints.entries.sumOf { (number, blueprint) ->
number * solve(blueprint, 24)
}
}
fun part2(input: List<String>): Int {
val blueprints = parseBlueprints(input)
return blueprints.values.take(3).fold(1) { acc, blueprint ->
acc * solve(blueprint, 32)
}
}
fun main() {
val testInput = readInput("Day19_test")
expect(part1(testInput), 33)
expect(part2(testInput), 3472)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 4,603 | AOC-2022-Kotlin | Apache License 2.0 |
src/aoc_2023/Day02.kt | jakob-lj | 573,335,157 | false | {"Kotlin": 38689} | package aoc_2023
import java.lang.RuntimeException
data class Round(val blue: Int?, val green: Int?, val red: Int?)
data class Game(val consumesTotalDrawings: Round, val gameId: Int)
private val testInput = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""".trimIndent()
private val realInput = """
""".trimIndent()
private fun formatInput(input: String): List<String> = input.split("\n")
private fun List<Round>.getMax(gameId: Int): Game {
val maxBlue = this.maxOf { it.blue ?: 0 }
val maxRed = this.maxOf { it.red ?: 0 }
val maxGreen = this.maxOf { it.green ?: 0 }
return Game(Round(blue = maxBlue, red = maxRed, green = maxGreen), gameId)
}
private fun formatRoundString(game: String): Pair<List<Round>, Int> {
val indexOfColon = game.indexOf(":")
val gameId = game.subSequence(5, indexOfColon).toString().toInt() // Every game starts with Game xx:
val rounds = game.subSequence((indexOfColon + 2)..game.lastIndex).split("; ")
val roundRounds = rounds.map { round ->
val counts = mutableMapOf<String, Int?>("green" to null, "red" to null, "blue" to null)
for (balDraw in round.split(", ")) {
val (ballCountString: String, color: String) = balDraw.split(" ")
val ballCount: Int = ballCountString.toInt()
if (color !in counts) {
throw RuntimeException("Cound not find color: $color")
}
counts[color] = ballCount
}
Round(blue = counts["blue"], green = counts["green"], red = counts["red"])
}
return Pair(roundRounds, gameId)
}
private fun part1(input: List<String>): Int {
val allowedGames = input.map { formatRoundString(it) }.map { it.first.getMax(it.second) }.filter { game ->
(game.consumesTotalDrawings.blue ?: 0) <= 14 &&
(game.consumesTotalDrawings.green ?: 0) <= 13 &&
(game.consumesTotalDrawings.red ?: 0) <= 12
}
return allowedGames.sumOf { it.gameId }
}
private fun part2(input: List<String>): Int {
return input.map { formatRoundString(it) }.map { it.first.getMax(it.second) }
.sumOf {
val minimums = it.consumesTotalDrawings
(minimums.blue ?: 1) * (minimums.green ?: 1) * (minimums.red ?: 1)
}
}
fun main() {
val result = part2(formatInput(testInput))
println(result)
} | 0 | Kotlin | 0 | 0 | 3a7212dff9ef0644d9dce178e7cc9c3b4992c1ab | 2,658 | advent_of_code | Apache License 2.0 |
src/day08/Day08.kt | xxfast | 572,724,963 | false | {"Kotlin": 32696} | package day08
import readLines
typealias Grid = List<List<Int>>
val List<String>.grid: Grid get() = this.map { line -> line.toList().map { it.digitToInt() } }
val Grid.height: Int get() = size
val Grid.width: Int get() = first().size
fun <T> Grid.map(block: (row: Int, column: Int, i: Int) -> T) =
(0 until height).map { row -> (0 until width).map { column -> block(row, column, this[row][column]) } }
fun <T> Grid.map(block: (i: Int, top: List<Int>, right: List<Int>, bottom: List<Int>, left: List<Int>) -> T) =
map { row, column, i -> block(i, top(row, column), right(row, column), bottom(row, column), left(row, column)) }
fun Grid.top(row: Int, column: Int): List<Int> = (row - 1 downTo 0).map { r -> this[r][column] }
fun Grid.right(row: Int, column: Int): List<Int> = (column + 1 until width).map { c -> this[row][c] }
fun Grid.bottom(row: Int, column: Int): List<Int> = (row + 1 until height).map { r -> this[r][column] }
fun Grid.left(row: Int, column: Int): List<Int> = (column - 1 downTo 0).map { c -> this[row][c] }
// TODO: Why is this not on stdlib 🤯
fun <T> List<T>.takeUntil(predicate: (T) -> Boolean): List<T> {
val take: MutableList<T> = mutableListOf()
for (i in this) {
take += i
if (predicate(i)) break
}
return take
}
fun main() {
fun part1(grid: Grid): Int = grid
.map { i, top, right, bottom, left ->
top.all { it < i } || right.all { it < i } || bottom.all { it < i } || left.all { it < i }
}
.flatten()
.count { it }
fun List<Int>.score(i: Int): Int = takeUntil { it >= i }.count()
fun part2(grid: Grid): Int = grid
.map { i, top, right, bottom, left -> top.score(i) * right.score(i) * bottom.score(i) * left.score(i) }
.flatten()
.max()
val testInput: List<String> = readLines("day08/test.txt")
val input: List<String> = readLines("day08/input.txt")
check(part1(testInput.grid) == 21)
check(part1(input.grid) == 1825)
println(part1(input.grid))
check(part2(testInput.grid) == 8)
check(part2(input.grid) == 235200)
println(part2(input.grid))
}
| 0 | Kotlin | 0 | 1 | a8c40224ec25b7f3739da144cbbb25c505eab2e4 | 2,061 | advent-of-code-22 | Apache License 2.0 |
y2022/src/main/kotlin/adventofcode/y2022/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
object Day11 : AdventSolution(2022, 11, "Monkey in the Middle") {
override fun solvePartOne(input: String): Long = solve(input, 20, 3)
override fun solvePartTwo(input: String): Long = solve(input, 10_000, 1)
private fun solve(input: String, rounds: Int, reduction: Int): Long {
val monkies = parse(input).sortedBy { it.id }
val counts = monkies.map { 0L }.toMutableList()
val mod = monkies.map { it.test.mod }.reduce(Long::times)
repeat(rounds) {
monkies.forEach { m ->
m.items.forEach { item ->
// division under modulo isn't actually allowed here (no inverse) but whatever,
// part 1 stays small enough that the modulo doesn't kick in
val newLevel = (m.operation.apply(item) / reduction) % mod
val newMonkey = m.test.test(newLevel)
monkies[newMonkey].items.add(newLevel)
counts[m.id]++
}
m.items.clear()
}
}
return counts.sorted().takeLast(2).reduce(Long::times)
}
private fun parse(input: String): List<Monkey> {
return input.split("\n\n")
.map { it.toMonkey() }
}
private fun String.toMonkey(): Monkey {
val lines = split("\n").map { it.trim() }
val id = lines[0].substringAfter(' ').dropLast(1).toInt()
val items = lines[1].substringAfter(": ").split(", ").map { it.toLong() }
val operator = lines[2].toOperation()
val mod = lines[3].substringAfter("by ").toLong()
val t = lines[4].substringAfterLast(" ").toInt()
val f = lines[5].substringAfterLast(" ").toInt()
return Monkey(id, items.toMutableList(), operator, Test(mod, t, f))
}
}
private data class Monkey(
val id: Int,
val items: MutableList<Long>,
val operation: Operation,
val test: Test
)
private data class Test(val mod: Long, val t: Int, val f: Int) {
fun test(input: Long) = if (input % mod == 0L) t else f
}
private data class Operation(val operator: Char, val operand: Long?) {
fun apply(input: Long) = when (operator) {
'+' -> (input + (operand ?: input))
'*' -> (input * (operand ?: input))
else -> throw IllegalStateException(operator.toString())
}
}
private fun String.toOperation(): Operation {
val (operatorStr, operandStr) = substringAfter("new = old ").split(" ")
return Operation(operatorStr[0], operandStr.toLongOrNull())
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,600 | advent-of-code | MIT License |
src/main/kotlin/aoc2023/Day03.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day03 {
fun part1(input: List<String>): Int {
val symbols = getSymbolCoords(input)
val numRegex = "(\\d+)".toRegex()
var sum = 0
for (y in input.indices) {
numRegex.findAll(input[y]).forEach { match ->
if (getAdjacentCoords(y to match.range).any { symbols.containsKey(it) }) {
sum += match.value.toInt()
}
}
}
return sum
}
fun part2(input: List<String>): Long {
val gearNumbers = getSymbolCoords(input)
.filterValues { it == '*' }
.keys
.associateBy({ it }, { mutableSetOf<Int>() })
val numRegex = "(\\d+)".toRegex()
for (y in input.indices) {
numRegex.findAll(input[y]).forEach { match ->
getAdjacentCoords(y to match.range)
.filter { coord -> gearNumbers.containsKey(coord) }
.forEach { coord -> gearNumbers[coord]!!.add(match.value.toInt()) }
}
}
return gearNumbers.values
.filter { it.size == 2 }
.sumOf { nums -> nums.fold(1L) { mult, num -> num * mult } }
}
private fun getSymbolCoords(scheme: List<String>): Map<Pair<Int, Int>, Char> {
val symbols = mutableMapOf<Pair<Int, Int>, Char>()
for (y in scheme.indices) {
val chars = scheme[y].toCharArray()
for (x in chars.indices) {
val ch = chars[x]
if (ch.isDigit() || ch == '.') continue
symbols[y to x] = ch
}
}
return symbols
}
private fun getAdjacentCoords(coord: Pair<Int, IntRange>): Set<Pair<Int, Int>> {
val adjacent = mutableSetOf<Pair<Int, Int>>()
val (y, x) = coord
for (dy in y - 1..y + 1) {
for (dx in x.first - 1..x.last + 1) {
adjacent.add(dy to dx)
}
}
return adjacent
}
}
fun main() {
val day03 = Day03()
val input = readInputAsStringList("day03.txt")
println("03, part 1: ${day03.part1(input)}")
println("03, part 2: ${day03.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 2,193 | advent-of-code-2023 | MIT License |
src/Day02.kt | Fenfax | 573,898,130 | false | {"Kotlin": 30582} | import org.apache.commons.lang3.StringUtils
fun main() {
fun game(playerOne: String, playerTwo: String): Pair<GameResult,Token> {
val pOne = Token.getByToken(playerOne)
val pTwo = Token.getByToken(playerTwo)
if (pOne == pTwo) return Pair(GameResult.DRAW, pTwo)
if (pOne.willLose(pTwo)) return Pair(GameResult.PLAYER_TWO, pTwo)
return Pair(GameResult.PLAYER_ONE, pTwo)
}
fun calcToken(playerOne: String, decidingToken: String): Pair<GameResult,Token> {
val pOne = Token.getByToken(playerOne)
return when (GameResult.getByDecidingToken(decidingToken)){
GameResult.DRAW -> Pair(GameResult.DRAW, pOne)
GameResult.PLAYER_ONE -> Pair(GameResult.PLAYER_ONE, Token.values().first { it.willLose(pOne) })
GameResult.PLAYER_TWO -> Pair(GameResult.PLAYER_TWO, Token.values().first { pOne.willLose(it)})
}
}
fun part1(input: List<String>): Int {
return input.map { it.split(StringUtils.SPACE) }
.map { game(it[0], it[1]) }
.sumOf { with(it){ first.score + second.score} }
}
fun part2(input: List<String>): Int {
return input.map { it.split(StringUtils.SPACE) }
.map { calcToken(it[0], it[1]) }
.sumOf { with(it){ first.score + second.score} }
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class GameResult(val score: Int, val decidingToken: String) {
PLAYER_ONE(0,"X"),
PLAYER_TWO(6, "Z"),
DRAW(3,"Y");
companion object {
fun getByDecidingToken(input: String): GameResult {
return values().first { it.decidingToken == input }
}
}
}
enum class Token(val stringTokens: List<String>, val score: Int) {
ROCK(listOf("A", "X"), 1),
PAPER(listOf("B", "Y"), 2),
SCISSORS(listOf("C", "Z"),3);
fun willLose(vsToken: Token): Boolean{
return loses[this]?.equals(vsToken) ?: true
}
companion object {
fun getByToken(input: String): Token {
return values().first { it.stringTokens.contains(input) }
}
private val loses: Map<Token, Token> = mapOf(
Pair(ROCK, PAPER),
Pair(PAPER, SCISSORS),
Pair(SCISSORS, ROCK)
)
}
}
| 0 | Kotlin | 0 | 0 | 28af8fc212c802c35264021ff25005c704c45699 | 2,314 | AdventOfCode2022 | Apache License 2.0 |
AoC2021day14-ExtendedPolymerization/src/main/kotlin/Main.kt | mcrispim | 533,770,397 | false | {"Kotlin": 29888} | import java.io.File
val transforms = mutableMapOf<Pair<String, Int>, Map<Char, Long>>()
var tableOfPairs = mapOf<String, String>()
fun main() {
val input = File("data.txt").readLines()
tableOfPairs = prepareTableOfPairs(input.slice(2..input.lastIndex))
initialTransforms(tableOfPairs)
val polymer = input[0]
val steps = 40
val elements = addMaps(mapOf(polymer[0] to 1), calculateElements(polymer, steps))
val sortedElements = elements.values.sorted()
val result = sortedElements.last() - sortedElements.first()
println("After $steps steps, the quantity of the most common element minus the quantity of the least common element is $result")
}
fun calculateElements(polymer: String, steps: Int): Map<Char, Long> {
//println("polymer: $polymer, steps: $steps")
var map = mapOf<Char, Long>()
if (transforms[Pair(polymer, steps)] != null) {
map = transforms[Pair(polymer, steps)] as MutableMap<Char, Long>
} else {
if (steps == 0) {
map = polymer.drop(1).toMap().mapValues { (k, v) -> v.toLong() }
} else {
for (i in 0 until polymer.lastIndex) {
val part = polymer.slice(i..i + 1)
val partElements = calculateElements(pairToTrio(part), steps - 1)
map = addMaps(map, partElements)
}
}
transforms[Pair(polymer, steps)] = map
}
return map
}
fun pairToTrio(part: String) = "" + part[0] + tableOfPairs[part] + part[1]
fun String.toMap() = this.groupingBy { it }.eachCount().mapValues { (k, v) -> v.toLong() }
fun initialTransforms(tableOfPairs: Map<String, String>) {
for ((k,v) in tableOfPairs) {
val all = k + v
val map = all.toMap()
transforms[Pair(k, 1)] = map
}
}
fun prepareTableOfPairs(values: List<String>): Map<String, String> {
val result = mutableMapOf<String, String>()
for (v in values) {
val (pair, output) = v.split(" -> ")
result[pair] = output
}
return result.toMap()
}
fun addMaps(m1:Map<Char, Long>, m2: Map<Char, Long>): Map<Char, Long> {
var result = m1.toMutableMap()
for ((k, v) in m2) {
result[k] = result.getOrDefault(k, 0) + v
}
return result.toMap()
}
| 0 | Kotlin | 0 | 0 | ac4aa71c9b5955fa4077ae40fc7e3fc3d5242523 | 2,254 | AoC2021 | MIT License |
src/day11/Day11.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day11
import java.io.File
fun main() {
println(solve(readInput(), 20, 3))
println(solve(readInput(), 10000, 1))
}
private fun readInput(): List<Monkey> {
val regex = """Monkey \d*:
Starting items: (.*)
Operation: new = (.*)
Test: divisible by (\d*)
If true: throw to monkey (\d*)
If false: throw to monkey (\d*)""".toRegex()
return File("src/day11/input.txt").readText().split("\n\n").map {
val values = regex.matchEntire(it)!!.groupValues
Monkey(
values[1].split(", ").map(String::toLong).toMutableList(),
values[2].split(" "),
values[3].toLong(),
values[4].toInt(),
values[5].toInt()
)
}.toList()
}
fun solve(monkeys: List<Monkey>, rounds: Int, relief: Int): Long {
val common = monkeys.fold(1L) { acc, m -> acc * m.divisibleBy }
for (round in 1 .. rounds) {
for (i in monkeys.indices) {
monkeys[i].process(relief, common).forEach { pair ->
monkeys[pair.first].items.add(pair.second)
}
}
}
return monkeys.map { it.inspects }.sorted().reversed().let { (first, second) -> first * second }
}
class Monkey(var items: MutableList<Long>, private val test: List<String>, val divisibleBy: Long, private val ifTrue: Int, private val ifFalse: Int) {
var inspects = 0L
fun process(relief: Int, common: Long): List<Pair<Int, Long>> {
val result = items.map { item ->
val b = if (test[2] == "old") item else test[2].toLong()
val testResult: Long = if (test[1] == "*") item * b else item + b
val afterRelief = (testResult / relief) % common
Pair(if (afterRelief % divisibleBy == 0L) ifTrue else ifFalse, afterRelief)
}.toList()
inspects += items.size
items.clear()
return result
}
}
| 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 1,881 | advent-of-code-2022 | MIT License |
src/main/kotlin/Day08.kt | rgawrys | 572,698,359 | false | {"Kotlin": 20855} | import utils.readInput
fun main() {
fun part1(input: List<String>): Int = treesCountVisibleOutsideTheGrid(input)
fun part2(input: List<String>): Int = highestScenicScore(input)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
part1(testInput).let {
check(it == 21) { "Part 1: Incorrect result. Is `$it`, but should be `21`" }
}
part2(testInput).let {
check(it == 8) { "Part 2: Incorrect result. Is `$it`, but should be `8`" }
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
private fun treesCountVisibleOutsideTheGrid(input: List<String>) =
input
.mapToForest()
.toTreeLineCombinationsForEachEdge()
.flatten()
.filterAllVisibleTreeFromEachEdge()
.size
private fun highestScenicScore(input: List<String>) =
input
.mapToForest()
.toTreeLineCombinationsForEachEdge()
.flatten()
.measureViewingDistances()
.calculateScenicScores()
.maxOf { it.second }
private fun List<List<Tree>>.filterAllVisibleTreeFromEachEdge(): Set<Tree> = this
.flatMap { it.filterVisibleTreesInLine() }
.toSet()
private fun List<Tree>.filterVisibleTreesInLine(): List<Tree> = this
.fold((-1 to emptyList<Tree>())) { acc, value ->
val maxHeight = if (value.height > acc.first) value.height else acc.first
val visibleTreesInLine = if (value.height > acc.first) acc.second + value else acc.second
maxHeight to visibleTreesInLine
}
.second
private fun List<List<Tree>>.measureViewingDistances(): List<Pair<Tree, Int>> = this.flatMap {
it.fold((emptyList())) { acc, value ->
val viewingDistance = acc
.takeLastWhile { it.first.height < value.height }
.size
.let { if (it == acc.size) it else it.inc() }
acc + (value to viewingDistance)
}
}
private fun List<Pair<Tree, Int>>.calculateScenicScores(): Set<Pair<Tree, Int>> = this.groupBy { it.first }
.map { it.key to it.value.map { it.second }.reduce(Int::times) }
.toSet()
private fun List<Tree>.toTreeLineCombinationsForEachEdge(): List<List<List<Tree>>> = with(this) {
listOf(
fromLeftEdgeLines(),
fromRightEdgeLines(),
fromTopEdgeLines(),
fromBottomEdgeLines()
)
}
private fun List<Tree>.fromLeftEdgeLines(): List<List<Tree>> = this
.groupBy(Tree::row)
.values
.map { it.sortedBy(Tree::column) }
private fun List<Tree>.fromRightEdgeLines(): List<List<Tree>> = this
.groupBy(Tree::row)
.values
.map { it.sortedByDescending(Tree::column) }
private fun List<Tree>.fromTopEdgeLines(): List<List<Tree>> = this
.groupBy(Tree::column)
.values
.map { it.sortedBy(Tree::row) }
private fun List<Tree>.fromBottomEdgeLines(): List<List<Tree>> = this
.groupBy(Tree::column)
.values
.map { it.sortedByDescending(Tree::row) }
private fun List<String>.mapToForest(): List<Tree> = this
.flatMapIndexed { row, treeRow ->
treeRow.mapIndexed { column, height ->
Tree(column, row, height.toString().toInt())
}
}
data class Tree(val column: Int, val row: Int, val height: Int)
| 0 | Kotlin | 0 | 0 | 5102fab140d7194bc73701a6090702f2d46da5b4 | 3,273 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | import kotlin.math.abs
private data class Vector(val x: Int, val y: Int) {
operator fun minus(other: Vector) = Vector(x - other.x, y - other.y)
operator fun plus(other: Vector) = Vector(x + other.x, y + other.y)
}
private data class Rope(
val head: Vector,
val tail: Vector,
) {
fun moveHead(direction: Vector): Rope {
val nextHead = head + direction
val diff = nextHead - tail
val tailMove = when {
abs(diff.x) <= 1 && abs(diff.y) <= 1 -> Vector(0, 0)
else -> Vector(diff.x.coerceIn(-1, 1), diff.y.coerceIn(-1, 1))
}
return Rope(nextHead, tail + tailMove)
}
fun toStr(width: Int = 5, height: Int = 5): String =
Array(height) { y ->
Array(width) { x ->
when (Vector(x, y)) {
head -> 'H'
tail -> 'T'
else -> '*'
}
}.joinToString("")
}.reversed().joinToString("\n")
}
private data class SuperRope(val ropes: List<Rope>) {
init {
check(ropes.zipWithNext().all { (a, b) -> a.tail == b.head }) { "Ropes must be connected" }
}
fun moveHead(direction: Vector): SuperRope {
val nextRopes = buildList<Rope> {
add(ropes.first().moveHead(direction))
ropes.drop(1).forEach {
add(it.moveHead(last().tail - it.head))
}
}
return SuperRope(nextRopes)
}
}
private fun parseMoves(input: List<String>): List<Vector> = buildList {
input.forEach { line ->
val (directionCode, stepsCount) = line.split(" ")
val direction = when (directionCode) {
"U" -> Vector(0, 1)
"D" -> Vector(0, -1)
"R" -> Vector(1, 0)
"L" -> Vector(-1, 0)
else -> throw IllegalArgumentException("Unknown direction: $directionCode")
}
repeat(stepsCount.toInt()) {
add(direction)
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val startPosition = Vector(0, 0)
val moves = parseMoves(input)
return moves.asSequence()
.runningFold(Rope(startPosition, startPosition)) { rope, move ->
rope.moveHead(move)
}
// .onEach { println(it.toStr()) }
.map { it.tail }
.distinct()
.count()
}
fun part2(input: List<String>): Int {
val startPosition = Vector(0, 0)
val moves = parseMoves(input)
val initialSuperRope = SuperRope(List(9) { Rope(startPosition, startPosition) })
return moves.asSequence()
.runningFold(initialSuperRope) { rope, move ->
rope.moveHead(move)
}
.map { it.ropes.last().tail }
.distinct()
.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13) {
part1(testInput)
}
val input = readInput("Day09")
println(part1(input))
val testInput2 = readInput("Day09_test_2")
part2(testInput2).let { check(it == 36) { it } }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 3,232 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | rafael-ribeiro1 | 572,657,838 | false | {"Kotlin": 15675} | fun main() {
fun part1(input: List<String>): Long {
return input.buildFilesystemTree()
.directorySizes()
.filter { it <= 100000 }
.sum()
}
fun part2(input: List<String>): Long {
val tree = input.buildFilesystemTree()
val sizes = tree.directorySizes()
return sizes.filter { it >= 30000000L - (70000000L - sizes.max()) }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun List<String>.buildFilesystemTree(): TreeNode<FilesystemItem> {
val root = FilesystemTreeNode(FilesystemItem.Directory("/"))
var actual = root
this.forEach { input ->
val split = input.split(" ")
when (split[0]) {
"$" -> {
if (split[1] == "cd") {
actual = when (split[2]) {
"/" -> root
".." -> (actual.parent ?: root) as FilesystemTreeNode
else -> actual.getOrAdd(FilesystemItem.Directory(split[2]))
}
}
}
"dir" -> { actual.getOrAdd(FilesystemItem.Directory(split[1])) }
else -> { actual.getOrAdd(FilesystemItem.File(split[1], split[0].toLong())) }
}
}
return root
}
fun TreeNode<FilesystemItem>.directorySizes(): List<Long> {
return mutableListOf<Long>().also { this.sumDirectorySizes(it) }
}
fun TreeNode<FilesystemItem>.sumDirectorySizes(sizes: MutableList<Long>): Long {
var sum = 0L
this.children.forEach {
sum += if (it.value is FilesystemItem.File) {
it.value.size
} else {
it.sumDirectorySizes(sizes)
}
}
return sum.also { sizes.add(it) }
}
sealed class FilesystemItem(val name: String) {
class Directory(name: String) : FilesystemItem(name)
class File(name: String, val size: Long) : FilesystemItem(name)
}
class FilesystemTreeNode(value: FilesystemItem) : TreeNode<FilesystemItem>(value) {
fun getOrAdd(item: FilesystemItem): FilesystemTreeNode {
return (children.firstOrNull { item.name == it.value.name }
?: FilesystemTreeNode(item).also { add(it) }) as FilesystemTreeNode
}
}
open class TreeNode<T>(val value: T) {
val children: MutableList<TreeNode<T>> = mutableListOf()
private var _parent: TreeNode<T>? = null
val parent: TreeNode<T>?
get() = _parent
fun add(node: TreeNode<T>) {
children.add(node)
node._parent = this
}
}
| 0 | Kotlin | 0 | 0 | 5cae94a637567e8a1e911316e2adcc1b2a1ee4af | 2,737 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | enum class HandType {
K5,
K4,
FH,
K3,
P2,
P1,
HC
}
val cardOrder1 = "A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2".split(", ").map { it[0] }
val cardOrder2 = "A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, J".split(", ").map { it[0] }
fun getHandType1(h: String): HandType {
val cc = h.groupingBy { it }.eachCount().values.toList().sortedDescending()
return when {
cc[0] == 5 -> HandType.K5
cc[0] == 4 -> HandType.K4
cc == listOf(3, 2) -> HandType.FH
cc[0] == 3 -> HandType.K3
cc == listOf(2, 2, 1) -> HandType.P2
cc == listOf(2, 1, 1, 1) -> HandType.P1
cc == listOf(1, 1, 1, 1, 1) -> HandType.HC
else -> error("impossible")
}
}
fun getHandType2(h: String): HandType {
return cardOrder2.minOf { jc -> getHandType1(h.replace('J', jc)) }
}
fun main() {
val input = readInput("Day07")
fun cmpCards(cardOrder: List<Char>) = Comparator<String> { s1, s2 ->
for (i in s1.indices) {
val r = cardOrder.indexOf(s1[i]) - cardOrder.indexOf(s2[i])
if (r != 0) return@Comparator r
}
return@Comparator 0
}
fun solve(cmp: Comparator<String>) {
val handsSorted = input.map { it.substringBefore(' ') }.sortedWith(cmp.reversed())
var res = 0L
for (line in input) {
val hand = line.substringBefore(' ')
val rank = handsSorted.indexOf(hand) + 1
val value = line.substringAfter(' ').toLong()
res += rank * value
}
println(res)
}
solve(compareBy<String> { getHandType1(it) }.thenComparing(cmpCards(cardOrder1)))
solve(compareBy<String> { getHandType2(it) }.thenComparing(cmpCards(cardOrder2)))
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,732 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/day19.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(19)
println(day19A(input))
println(day19B(input))
}
fun day19A(input: Input): Int {
val workflows = Workflow.init(input)
return input.chunks[1].lines().sumOf { line ->
val ints = line.toInts()
val part = Part(ints[0], ints[1], ints[2], ints[3])
var next = "in"
do {
val workflow = workflows.first {it.name == next }
next = workflow.process(part)
} while (next != "A" && next != "R")
if(next == "A") {
ints.sum()
} else {
0
}
}
}
fun day19B(input: Input): Long {
val workflows = Workflow.init(input)
var parts = listOf<Pair<PartRange, String?>>(
PartRange(1 .. 4000, 1 .. 4000, 1 .. 4000, 1 .. 4000) to "in"
)
while (parts.any { it.second != "A" }) {
parts = parts.filter { it.second != "R" }.flatMap { part ->
if(part.second == "A") {
listOf(part)
} else {
workflows.first { it.name == part.second }.process(part.first)
}
}
}
return parts.sumOf {
it.first.x.count().toLong() *
it.first.m.count().toLong() *
it.first.a.count().toLong() *
it.first.s.count().toLong()
}
}
private class Workflow(val name: String, val rules: List<Rule>) {
fun process(part: Part): String {
return rules.firstNotNullOf { it.process(part) }
}
fun process(part: PartRange): List<Pair<PartRange, String?>> {
var parts = listOf<Pair<PartRange, String?>>(part to null)
rules.forEach { rule ->
parts = parts.flatMap {
if(it.second == null) {
rule.process(it.first)
} else {
listOf(it)
}
}
}
return parts
}
companion object {
fun init(input: Input): List<Workflow> {
return input.chunks[0].lines().map { line ->
val (name, rest) = line.split('{')
val rules = rest.dropLast(1).split(',').map { ruleString ->
Regex("""(\w)(<|>)(\d+):(\w+)""").find(ruleString)?.let {
Rule(
it.groupValues[1].first(),
it.groupValues[2].first(),
it.groupValues[3].toInt(),
it.groupValues[4],
)
} ?: Rule(null, null, null, ruleString)
}
Workflow(name, rules)
}
}
}
}
private class Part(val x: Int, val m: Int, val a: Int, val s: Int) {
fun get(char: Char): Int {
return when(char) {
'x' -> x
'm' -> m
'a' -> a
's' -> s
else -> throw Exception()
}
}
}
private class Rule(val property: Char?, val compare: Char?, val limit: Int?, val to: String) {
fun process(part: Part): String? {
if (property == null || compare == null || limit == null) {
return to
}
return when {
compare == '>' && part.get(property) > limit -> to
compare == '<' && part.get(property) < limit -> to
else -> null
}
}
fun process(part: PartRange): List<Pair<PartRange, String?>> {
if (property == null || compare == null || limit == null) {
return listOf(part to to)
}
return when (property) {
'x' -> {
return part.x.split(limit, compare, to).map {
PartRange(it.first, part.m, part.a, part.s) to it.second
}
}
'm' -> {
return part.m.split(limit, compare, to).map {
PartRange(part.x, it.first, part.a, part.s) to it.second
}
}
'a' -> {
return part.a.split(limit, compare, to).map {
PartRange(part.x, part.m, it.first, part.s) to it.second
}
}
's' -> {
return part.s.split(limit, compare, to).map {
PartRange(part.x, part.m, part.a, it.first) to it.second
}
}
else -> emptyList()
}
}
}
private class PartRange(val x: IntRange, val m: IntRange, val a: IntRange, val s: IntRange)
private fun IntRange.split(limit: Int, compare: Char, to: String): List<Pair<IntRange, String?>> {
if (contains(limit)) {
if (compare == '<') {
return listOf(
first..<limit to to,
limit..last to null,
)
}
return listOf(
first..limit to null,
limit + 1..last to to,
)
}
if (compare == '<') {
return listOf(
this to if (last < limit) to else null
)
}
return listOf(
this to if (first > limit) to else null
)
}
| 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 5,068 | AdventOfCode2023 | MIT License |
src/Day08.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | import java.util.Stack
import kotlin.math.max
typealias ScenicState = Pair<Stack<Pair<Int, Int>>, Int>
private enum class Side { UP, DOWN, LEFT, RIGHT }
private data class Tree(
val height: Int,
var up: Tree? = null,
var down: Tree? = null,
var left: Tree? = null,
var right: Tree? = null,
) {
val maxUp: Int by lazy { maxSeenTree(Side.UP) }
val maxDown: Int by lazy { maxSeenTree(Side.DOWN) }
val maxLeft: Int by lazy { maxSeenTree(Side.LEFT) }
val maxRight: Int by lazy { maxSeenTree(Side.RIGHT) }
val scenicUp: ScenicState by lazy { scenicSide(Side.UP) }
val scenicDown: ScenicState by lazy { scenicSide(Side.DOWN) }
val scenicLeft: ScenicState by lazy { scenicSide(Side.LEFT) }
val scenicRight: ScenicState by lazy { scenicSide(Side.RIGHT) }
val visible: Boolean by lazy { listOf(maxUp, maxDown, maxLeft, maxRight).any { it < height } }
val scenicScore: Int by lazy {
listOf(scenicUp, scenicDown, scenicLeft, scenicRight).map { it.second }.reduce { acc, it -> acc * it }
}
private fun nextTree(side: Side): Tree? {
return when (side) {
Side.UP -> up
Side.DOWN -> down
Side.LEFT -> left
Side.RIGHT -> right
}
}
private fun maxSeenTree(side: Side): Int {
val next = nextTree(side)
return if (next == null) -1 else max(next.maxSeenTree(side), next.height)
}
private fun calculateScenicAcc(prev: ScenicState): ScenicState {
val (s, _) = prev
var popped = 0
while (!s.empty()) {
val top = s.peek()
if (top.first < height) {
s.pop()
popped += top.second
} else {
break
}
}
val seen = popped + (if (s.isEmpty()) 0 else 1)
s.push(height to popped + 1)
return s to seen
}
private fun scenicSide(side: Side): ScenicState {
val next = nextTree(side)
return when (next) {
null -> {
val stack = Stack<Pair<Int, Int>>()
stack.push(height to 1)
return stack to 0
}
else -> calculateScenicAcc(next.scenicSide(side))
}
}
}
fun main() {
val input = readInput("Day08")
fun part1(input: List<String>): Int {
val trees = parseGrid2(input)
return trees.count { it.visible }
}
fun part2(input: List<String>): Int {
val trees = parseGrid2(input)
return trees.maxOf { it.scenicScore }
}
val testInput = readInput("Day08_test")
println(part1(testInput))
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
println("Part 1")
println(part1(input))
println("Part 2")
println(part2(input))
}
private fun parseGrid2(map: List<String>): List<Tree> {
val tmp = map.map { it.map { char -> char - '0' }.map { Tree(it) } }
tmp.forEach { row -> row.zipWithNext().forEach { (prev, cur) -> cur.left = prev; prev.right = cur } }
tmp.transpose().forEach { row -> row.zipWithNext().forEach { (prev, cur) -> cur.up = prev; prev.down = cur } }
return tmp.flatten()
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 3,226 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day04.kt | uipko | 572,710,263 | false | {"Kotlin": 25828} |
fun main() {
val pairsContains = contains("Day04.txt")
println("The total sum of pairs of elf to reconsider is: $pairsContains")
val pairsOverlap = overlap_wip("Day04.txt")
println("The total sum of pairs of elf to reconsider is: $pairsOverlap")
}
fun contains(fileName: String): Int {
val test = readInput(fileName).count { pairs ->
val elfRange = pairs.split(",").map {
range -> range.split("-").map { it.toInt() } }
val elf1 = elfRange.first()
val elf2 = elfRange.last()
(elf1.first() >= elf2.first() && elf1.last() <= elf2.last())
|| (elf2.first() >= elf1.first() && elf2.last() <= elf1.last())
}
return test
}
fun overlap_wip(fileName: String): Int {
return readInput(fileName).map { pairs ->
pairs.split(",").map { range ->
range.split("-").let { (range.first()..range.last()).toSet() }
}
}.count { it.first().intersect(it.last()).isNotEmpty() }
}
fun overlap(fileName: String): Int {
val test = readInput(fileName).count { pairs ->
val elfRange = pairs.split(",").map {
range -> range.split("-").map { it.toInt() } }
val elf1 = elfRange.first()
val elf2 = elfRange.last()
((elf1.first() in elf2.first() .. elf2.last())
|| (elf1.last() in elf2.first() .. elf2.last())
) || ((elf2.first() in elf1.first() .. elf1.last())
|| (elf2.last() in elf1.first() .. elf1.last()))
}
return test
}
| 0 | Kotlin | 0 | 0 | b2604043f387914b7f043e43dbcde574b7173462 | 1,525 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day14/Polymerization.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day14
import utils.merge
import utils.read
data class Rule(val first: Char, val second: Char, val insert: Char)
fun main() {
solve().let { println(it) }
}
fun solve() = listOf(day14.solve(10), day14.solve(40))
fun solve(rounds: Int): Long {
val input = read("./src/main/resources/day14Input.txt")
var template = input.first().toCharArray().toList()
val rules = input.drop(2).map {
val array = it.toCharArray()
Rule(array[0], array[1], array[6])
}
val countsInTemplate = template.groupBy { it }
.mapValues { it.value.size.toLong() }
val partlyPolymerCounts = template.windowed(2, 1)
.map {
countPolymers(rounds, Pair(it[0], it[1]), rules)
}.plus(countsInTemplate)
val result = merge(partlyPolymerCounts) { a, b -> a+b}
val sorted = result.entries.sortedBy { it.value }
val smallest = sorted.first().value
val largest = sorted.last().value
return largest-smallest
}
typealias CacheKey = Pair<Int, Pair<Char,Char>>
var cache: MutableMap<CacheKey, Map<Char,Long>> = mutableMapOf()
private fun cacheKey(
roundsRemaining: Int,
template: Pair<Char, Char>
) = Pair(roundsRemaining, template)
private fun countPolymers(
roundsRemaining: Int,
template: Pair<Char, Char>,
rules: List<Rule>
): Map<Char, Long> {
if (roundsRemaining == 0) {
return mapOf()
}
val cacheKey = cacheKey(roundsRemaining,template)
if(cache.containsKey(cacheKey)) {
return cache[cacheKey]!!
}
val expanded = applyRule(template, rules)
if (expanded.size > 1) {
val inserted = expanded[0].second
val counts = mutableMapOf<Char, Long>()
counts[inserted] = 1
val leftCounts = countPolymers(roundsRemaining - 1, expanded[0], rules)
val rightCounts = countPolymers(roundsRemaining - 1, expanded[1], rules)
val result = merge(listOf(counts,leftCounts,rightCounts)) { a, b -> a+b}
cache[cacheKey] =result
return result
} else
return mapOf()
}
fun applyRule(polymer: Pair<Char, Char>, rules: List<Rule>): List<Pair<Char, Char>> {
val applyingRule = rules.find {
it.first == polymer.first && it.second == polymer.second
}
return if (applyingRule != null) {
listOf(
Pair(polymer.first, applyingRule.insert),
Pair(applyingRule.insert, polymer.second)
)
}
else {
listOf(polymer)
}
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 2,474 | adventOfCode2021 | Apache License 2.0 |
2k23/aoc2k23/src/main/kotlin/03.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 d03
import input.read
fun main() {
val (numbers, symbols) = parseMap(read("03.txt"))
println("Part 1: ${part1(numbers, symbols)}")
println("Part 2: ${part2(numbers, symbols)}")
}
fun part1(numbers: Numbers, symbols: Symbols): Int {
return numbers.filter { entry ->
(0..<entry.value.toString().length).any { bx ->
intArrayOf(-1, 0, 1).any { dx ->
intArrayOf(-1, 0, 1).any { dy ->
symbols.keys.contains(Pair(entry.key.first + bx + dx, entry.key.second + dy))
}
}
}
}.values.sum()
}
val GEAR_SYMBOL = '*'
val GEAR_RATIOS = 2
fun part2(numbers: Numbers, symbols: Symbols): Int {
val numberz: Numbers = numbers.flatMap { (key, value) ->
(0..<value.toString().length).map {
Pair(key.first + it, key.second) to value
}
}.toMap() as Numbers
return symbols.filter { it.value == GEAR_SYMBOL }.keys.sumOf {
val set: MutableSet<Int> = mutableSetOf()
intArrayOf(-1, 0, 1).forEach { dx ->
intArrayOf(-1, 0, 1).forEach { dy ->
val neighbor = Pair(it.first + dx, it.second + dy)
if (numberz.contains(neighbor)) {
set.add(numberz[neighbor]!!)
}
}
}
if (set.size == GEAR_RATIOS) set.reduce(Int::times) else 0
}
}
typealias Numbers = HashMap<Pair<Int, Int>, Int>
typealias Symbols = HashMap<Pair<Int, Int>, Char>
fun parseMap(lines: List<String>): Pair<Numbers, Symbols> {
val numbers: Numbers = hashMapOf()
val symbols: Symbols = hashMapOf()
val regex = """\d+""".toRegex()
lines.forEachIndexed { y, s ->
var x = 0
var currentLine = s
while (currentLine.isNotEmpty()) {
val currentChar = currentLine.first()
if (currentChar.isDigit()) {
val match = regex.find(currentLine)!!
val num = match.value.toInt()
numbers[Pair(x, y)] = num
x += match.value.length
currentLine = currentLine.substring(match.value.length)
} else {
if (currentChar != '.') {
symbols[Pair(x, y)] = currentChar
}
x += 1
currentLine = currentLine.substring(1)
}
}
}
return Pair(numbers, symbols)
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 2,417 | aoc | The Unlicense |
src/Day05.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun part1(pair: Pair<MutableList<MutableList<Char>>, List<Move>>): String {
var (stacks, instructions) = pair
instructions.forEach { (count, from, to) ->
val items = stacks[from].takeLast(count)
stacks[to].addAll(items.reversed())
stacks[from] = stacks[from].dropLast(count).toMutableList()
}
return stacks.map { it.lastOrNull() ?: ' ' }.joinToString("")
}
fun part2(pair: Pair<MutableList<MutableList<Char>>, List<Move>>): String {
var (stacks, instructions) = pair
instructions.forEach { (count, from, to) ->
val items = stacks[from].takeLast(count)
stacks[to].addAll(items)
stacks[from] = stacks[from].dropLast(count).toMutableList()
}
return stacks.map { it.lastOrNull() ?: ' ' }.joinToString("")
}
fun parse(stringList: List<String>): Pair<MutableList<MutableList<Char>>, List<Move>> {
val height = stringList.takeWhile { it.isNotBlank() }.size
val (order, instructions) = stringList.take(height) to stringList.drop(height + 1)
var crates = order.dropLast(1).map { crate ->
crate.windowed(3, 4).map { it[1] }
}
val width = crates.maxBy { it.size }.size
crates = crates.map {
if (it.size != width)
it.also {
(0..it.size - width + 1).forEach { _ ->
(it as MutableList<Char>).add(' ')
}
}
else it
}
return crates.transpose().map { it.filter { ch -> ch.isLetter() }.reversed().toMutableList() }
.toMutableList() to instructions.map { line -> Move.of(line) }
}
val testInput = readInput("Day05_test")
check(part1(parse(testInput)) == "CMZ")
check(part2(parse(testInput)) == "MCD")
val input = readInput("Day05_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
/* Copied */
data class Move(val quantity: Int, val source: Int, val target: Int) {
companion object {
fun of(line: String): Move {
return line.split(" ")
.filterIndexed { idx, _ -> idx % 2 == 1 }
.map { it.toInt() }
.let { Move(it[0], it[1] - 1, it[2] - 1) }
}
}
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 2,340 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day21.kt | mstar95 | 317,305,289 | false | null | package days
inline class Allergen(val value: String)
inline class Ingredient(val value: String)
class Day21 : Day(21) {
override fun partOne(): Any {
val entries = prepareInput(inputList)
val allergens = basicAllergens(entries)
val safe = entries.safeIngredients(allergens)
// println(safe)
return safe.map { s -> entries.entries.count { it.ingredients.contains(s) } }.sum()
}
override fun partTwo(): Any {
val entries = prepareInput(inputList)
val allergens: Map<Allergen, Ingredient> = basicAllergens(entries)
return allergens.toList().sortedBy { it.first.value }.joinToString(",") { it.second.value }
}
private fun basicAllergens(entries: Entries): Map<Allergen, Ingredient> {
val allergensToIngredients: Map<Allergen, Set<Ingredient>> = entries.allergensToIngredients
return basicAllergens(allergensToIngredients)
}
private fun basicAllergens(input: Map<Allergen, Set<Ingredient>>, result: Map<Allergen, Ingredient> = emptyMap()): Map<Allergen, Ingredient> {
if (input.isEmpty()) {
return result
}
val singleEntry: Map.Entry<Allergen, Set<Ingredient>> = input.entries.first { it.value.size == 1 }
if (singleEntry == null) {
error(" Found is null Message $input, $result")
}
val singleAllergen: Allergen = singleEntry.key
val singleIngredient: Ingredient = singleEntry.value.first()
val next = result + (singleAllergen to singleIngredient)
val nextInput: Map<Allergen, Set<Ingredient>> = (input - singleAllergen)
.entries.map { it.key to (it.value - singleIngredient) }.toMap()
return basicAllergens(nextInput, next)
}
private fun prepareInput(input: List<String>): Entries {
return Entries(input.map { row ->
val split: List<String> = row.split(" (contains ")
Entry(split[0].split(" ").map { Ingredient(it) }.toSet(),
split[1].dropLast(1).split(", ").map { Allergen(it) }.toSet())
})
}
}
data class Entry(val ingredients: Set<Ingredient>, val allergens: Set<Allergen>)
data class Entries(val entries: List<Entry>) {
val allergens = entries.flatMap { it.allergens }.toSet()
val ingredients = entries.flatMap { it.ingredients }.toSet()
val allergensToIngredients: Map<Allergen, Set<Ingredient>>
get() = allergens.map {
it to ingredientsWhichCanContain(it)
}.toMap()
private fun ingredientsWhichCanContain(allergen: Allergen): Set<Ingredient> {
return entries.filter { it.allergens.contains(allergen) }
.map { it.ingredients }
.reduce { a, b -> a.intersect(b) }
}
fun safeIngredients(allergens: Map<Allergen, Ingredient>): Set<Ingredient> {
return ingredients - allergens.values
}
}
| 0 | Kotlin | 0 | 0 | ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81 | 2,899 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/day12/Day12.kt | bartoszm | 572,719,007 | false | {"Kotlin": 39186} | package day12
import readInput
import java.util.*
fun main() {
println(solve1(parse(readInput("day12/test"))))
println(solve1(parse(readInput("day12/input"))))
println(solve2(parse(readInput("day12/test"))))
println(solve2(parse(readInput("day12/input"))))
}
typealias Point = Pair<Int, Int>
fun Array<CharArray>.weight(p: Point): Char = when (this[p.first][p.second]) {
'S' -> 'a'
'E' -> 'z'
else -> this[p.first][p.second]
}
fun toGraphE(input: Array<CharArray>): Map<Point, List<Pair<Point, Int>>> {
val edges = hashMapOf<Point, List<Pair<Point, Int>>>()
for (i in input.indices) {
for (j in input[0].indices) {
val thiz = i to j
edges[thiz] = neighbours(input, thiz)
}
}
return edges
}
fun toPosition(x: Char, input: Array<CharArray>): List<Point> {
return sequence {
for (i in input.indices) {
for (j in input[0].indices) {
if (input[i][j] == x) {
yield(i to j)
}
}
}
}.toList()
}
fun solve1(input: Array<CharArray>): Int {
val g = toGraphE(input)
val start = toPosition('S', input).first()
val end = toPosition('E', input).first()
return findShortestPath(start, end, g)
}
fun solve2(input: Array<CharArray>): Int {
val g = toGraphE(input)
val start = toPosition('S', input) + toPosition('a', input)
val end = toPosition('E', input).first()
return start.map {
findShortestPath(it, end, g)
}.filter { it > 0 }.min()
}
fun findShortestPath(
src: Point,
dest: Point,
connections: Map<Point, List<Pair<Point, Int>>>
): Int {
val visited = hashSetOf<Point>()
val queue: Queue<Point> = LinkedList()
visited.add(src)
queue.add(src)
val parents = hashMapOf<Point, Point>()
while (queue.isNotEmpty()) {
val node = queue.poll()
visited.add(node)
if (node == dest) {
return path(dest, parents).size
}
connections[node]!!
.filter { !visited.contains(it.first) }
.filter { !queue.contains(it.first) }
.forEach {
parents[it.first] = node
queue.add(it.first)
}
}
return -1
}
fun path(dest: Point, parents: HashMap<Point, Point>): List<Point> {
var current = dest
return sequence {
while (parents[current] != null) {
yield(parents[current]!!)
current = parents[current]!!
}
}.toList()
}
private fun neighbours(
input: Array<CharArray>,
thiz: Pair<Int, Int>
): List<Pair<Point, Int>> {
return sequenceOf(
thiz.first - 1 to thiz.second, thiz.first + 1 to thiz.second,
thiz.first to thiz.second - 1, thiz.first to thiz.second + 1
)
.filter { it.first in input.indices && it.second in input[0].indices }
.map {
val w = input.weight(it) - input.weight(thiz)
it to if (w > 0) w else 0
}
.filter { it.second in (0..1) }
.map { (p, v) -> p to v + 1 }.toList()
}
fun parse(input: List<String>) = input.map { it.toCharArray() }.toTypedArray()
| 0 | Kotlin | 0 | 0 | f1ac6838de23beb71a5636976d6c157a5be344ac | 3,198 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | mikemac42 | 573,071,179 | false | {"Kotlin": 45264} | import java.io.File
fun main() {
val testInput = """30373
25512
65332
33549
35390"""
val realInput = File("src/Day08.txt").readText()
val part1TestOutput = treesVisible(testInput)
println("Part 1 Test Output: $part1TestOutput")
check(part1TestOutput == 21)
val part1RealOutput = treesVisible(realInput)
println("Part 1 Real Output: $part1RealOutput")
val part2TestOutput = maxScenicScore(testInput)
println("Part 2 Test Output: $part2TestOutput")
check(part2TestOutput == 8)
println("Part 2 Real Output: ${maxScenicScore(realInput)}")
}
/**
* Each tree is a single digit (0-9) whose value is its height.
* A tree is visible if all of the other trees between it and an edge of the grid are shorter than it.
* Only look up, down, left, or right from any given tree.
* All of the trees around the edge of the grid are visible.
* How many trees are visible from outside the grid?
*/
fun treesVisible(input: String): Int {
val heightgrid = input.toGrid()
val n = heightgrid.size
val visibilityGrid = heightgrid.mapIndexed { j, row ->
row.mapIndexed { i, height ->
if (i == 0 || i == n - 1 || j == 0 || j == n - 1
|| row.subList(0, i).all { it < height } // left
|| row.subList(i + 1, n).all { it < height } // right
|| heightgrid.subList(0, j).all { it[i] < height } // up
|| heightgrid.subList(j + 1, n).all { it[i] < height } // down
) {
1
} else {
0
}
}
}
return visibilityGrid.sumOf { it.sum() }
}
/**
* What is the highest scenic score possible for any tree?
*/
fun maxScenicScore(input: String): Int {
val heightGrid = input.toGrid()
val n = heightGrid.size
val scoreGrid = heightGrid.mapIndexed { j, row ->
row.mapIndexed { i, height ->
listOf(
row.subList(0, i).reversed(), // left
row.subList(i + 1, n), // right
heightGrid.subList(0, j).map { it[i] }.reversed(), // up
heightGrid.subList(j + 1, n).map { it[i] } // down
).map { treeRow ->
if (treeRow.all { it < height }) {
treeRow.size
} else {
treeRow.indexOfFirst { it >= height } + 1
}
}.reduce { acc, e ->
acc * e
}
}
}
return scoreGrid.maxOf { it.max() }
}
fun String.toGrid(): List<List<Int>> =
lines().map { line ->
line.map { char ->
char.digitToInt()
}
} | 0 | Kotlin | 1 | 0 | 909b245e4a0a440e1e45b4ecdc719c15f77719ab | 2,391 | advent-of-code-2022 | Apache License 2.0 |
src/twentythree/Day04.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentythree
import readInputTwentyThree
import kotlin.math.pow
/**
* Integer power using [Double.pow]
*/
infix fun Int.pow(exponent: Int): Int = toDouble().pow(exponent).toInt()
data class Card(val id: Int, val winningNumbers: Set<Int>, val ownNumbers: Set<Int>) {
fun numberOfMatches() = winningNumbers.intersect(ownNumbers)
}
fun String.parseCard(): Card {
val id = this.substring(4, this.indexOf(':')).trim().toInt().also { println("Parsed index: $it") }
val winningNumbers = this.substring(this.indexOf(':') + 1, this.indexOf('|'))
.split(' ')
.map(String::trim)
.filter { it.isNotBlank() }
.map(String::toInt)
.toSet()
val ownNumbers = this.substring(this.indexOf('|') + 1)
.split(' ')
.map(String::trim)
.filter { it.isNotBlank() }
.map(String::toInt)
.toSet()
return Card(id, winningNumbers, ownNumbers)
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.parseCard() }
.map { it.numberOfMatches() }
.sumOf {
if (it.isEmpty()) {
0
} else {
1 * 2.pow(it.size - 1)
}
}
}
fun part2(input: List<String>): Int {
val cards = input.map { it.parseCard() }
val copiesAmount = cards.indices.associateWith { 1 }.toMutableMap()
copiesAmount.keys.forEach { index ->
cards[index].numberOfMatches().size
.also { println("Card ${index + 1} has $it matches") }
.let { matches ->
val currentCopies = copiesAmount[index] ?: 0.also { println("Have $it of card ${index + 1}") }
for (i in 0 until matches) {
val targetIndex = index + i + 1
copiesAmount[targetIndex] = copiesAmount[targetIndex]?.plus(currentCopies) ?: 0
println("Adding $currentCopies copies to card $targetIndex")
}
if (matches == 0 && currentCopies == 1) {
return@forEach
}
}
}
return copiesAmount.values.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyThree("Day04_test")
check(part1(testInput).also(::println) == 13)
check(part2(testInput).also(::println) == 30)
val input = readInputTwentyThree("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 2,583 | kotlin-aoc-1 | Apache License 2.0 |
src/Day08.kt | ChAoSUnItY | 572,814,842 | false | {"Kotlin": 19036} | typealias GridWalk = Pair<IntProgression, IntProgression>
typealias GridCrossWalk = IntProgression
fun main() {
fun getRanges(size: Int): List<IntProgression> =
listOf((0 until size), (size - 1 downTo 0))
fun getRanges(size: Int, start: Int): List<IntProgression> =
listOf((start - 1 downTo 0), (start + 1 until size))
fun gridWalk(size: Int): List<GridWalk> =
getRanges(size).flatMap { y -> getRanges(size).map { x -> y to x } }
fun gridCrossWalk(size: Int, startX: Int, startY: Int): List<GridCrossWalk> =
listOf(startX, startY).flatMap { getRanges(size, it) }
fun processData(data: List<String>): List<List<Int>> =
data.map {
it.toCharArray()
.filter(Char::isDigit)
.map(Char::digitToInt)
}
// Optimized, per element is iterated 4 times from different directions,
// which means the time complexity is O((N ^ 2) * 4), where N is size of data (N ^ 2)
fun part1(data: List<List<Int>>): Int {
val size = data.size
val visible = Array(size) { BooleanArray(size) }
for ((i, gridWalk) in gridWalk(size).withIndex()) {
val (xWalk, yWalk) = gridWalk
for (y in yWalk) {
var currentMaxHeight = -1
for (x in xWalk) {
val currentHeight =
if (i % 2 == 0) data[x][y]
else data[y][x]
if (currentHeight > currentMaxHeight) {
currentMaxHeight = currentHeight
if (x == 0 || y == 0 || x == size - 1 || y == size - 1)
continue
if (i % 2 == 0) visible[x][y] = true
else visible[y][x] = true
}
}
}
}
return visible.flatMap(BooleanArray::toList)
.count { it } + size * 4 - 4
}
fun part1Unoptimized(data: List<List<Int>>): Int =
data.flatMapIndexed { y, row ->
row.mapIndexed { x, height ->
gridCrossWalk(data.size, x, y).mapIndexed { i, gridWalk ->
gridWalk.map {
if (i < 2) data[y][it] else data[it][x]
}.all { it < height }
}.any { it }
}.filter { it }
}.count()
fun part2(data: List<List<Int>>): Int =
data.flatMapIndexed { y, row ->
row.mapIndexed { x, treeHouseHeight ->
gridCrossWalk(data.size, x, y).mapIndexed { i, gridWalk ->
gridWalk.map {
if (i < 2) data[y][it] else data[it][x]
}.takeWhileInclusive { // Collections.kt
it < treeHouseHeight
}.count()
}.reduce(Int::times)
}
}.max()
val data = readInput("Day08")
val processedData = processData(data)
println(part1(processedData))
// println(part1Unoptimized(processedData))
println(part2(processedData))
}
| 0 | Kotlin | 0 | 3 | 4fae89104aba1428820821dbf050822750a736bb | 3,103 | advent-of-code-2022-kt | Apache License 2.0 |
src/main/kotlin/Day13.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun part1(input: List<Packet>): Int = input.chunked(2)
.mapIndexed { index, packets -> if (packets.first() < packets.last()) index + 1 else 0 }
.sum()
fun part2(input: List<Packet>): Int {
val packet1 = ListPacket(listOf(ListPacket(listOf(ListPacket(listOf(IntPacket(2)))))))
val packet2 = ListPacket(listOf(ListPacket(listOf(ListPacket(listOf(IntPacket(6)))))))
val packets = (input + packet1 + packet2).sorted()
return (packets.indexOf(packet1) + 1) * (packets.indexOf(packet2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test").toPackets()
check(part1(testInput) == 13)
println(part2(testInput))
val input = readInput("Day13").toPackets()
println(part1(input))
println(part2(input))
}
fun List<String>.toPackets(): List<Packet> = this.filter { it.isNotBlank() }
.map { line ->
fun read(iterator: Iterator<String>): Packet {
val packets = mutableListOf<Packet>()
while (iterator.hasNext()) {
when (val c = iterator.next()) {
"]" -> return ListPacket(packets)
"[" -> packets.add(read(iterator))
else -> packets.add(IntPacket(c.toInt()))
}
}
return ListPacket(packets)
}
read(
line.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex())
.filter { it.isNotBlank() }
.filter { it != "," }
.iterator())
}
sealed class Packet : Comparable<Packet>
class IntPacket(val value: Int) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is IntPacket -> value.compareTo(other.value)
is ListPacket -> ListPacket(listOf(this)).compareTo(other)
}
}
class ListPacket(val packets: List<Packet> = listOf()) : Packet() {
override fun compareTo(other: Packet): Int = when (other) {
is IntPacket -> compareTo(ListPacket(listOf(other)))
is ListPacket -> packets.zip(other.packets)
.map { it.first.compareTo(it.second) }
.firstOrNull { it != 0 } ?: packets.size.compareTo(other.packets.size)
}
}
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 2,269 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day05.kt | andydenk | 573,909,669 | false | {"Kotlin": 24096} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<String>): String {
val (stacks: Map<Int, Stack>, instructions: List<Instruction>) = parseInput(input)
instructions.forEach { applyPart1Instruction(it, stacks) }
return printResult(stacks)
}
private fun part2(input: List<String>): String {
val (stacks: Map<Int, Stack>, instructions: List<Instruction>) = parseInput(input)
instructions.forEach { applyPart2Instruction(it, stacks) }
return printResult(stacks)
}
private fun applyPart1Instruction(instruction: Instruction, stacks: Map<Int, Stack>) {
val originStack = stacks.getValue(instruction.origin)
val destinationStack = stacks.getValue(instruction.destination)
repeat(instruction.amount) { destinationStack.addFirst(originStack.removeFirst()) }
}
private fun applyPart2Instruction(instruction: Instruction, stacks: Map<Int, Stack>) {
val originStack = stacks.getValue(instruction.origin)
val destinationStack = stacks.getValue(instruction.destination)
(1..instruction.amount)
.map { originStack.removeFirst() }
.reversed()
.forEach { destinationStack.addFirst(it) }
}
private fun parseInput(input: List<String>): Pair<Map<Int, Stack>, List<Instruction>> {
val stacks = parseStacks(input.subList(0, input.indexOf("") - 1))
val instructions = input.subList(input.indexOf("") + 1, input.size).map { Instruction.of(it) }
return stacks to instructions
}
private fun parseStacks(stacksInput: List<String>): Map<Int, Stack> {
val numberOfStacks = stacksInput.last().split(" ").size
val stacksMap = (1..numberOfStacks).associateBy({ it }, { Stack() })
stacksInput.map { line ->
line.chunked(4)
.forEachIndexed { index, item ->
item[1].takeIf { item.isNotBlank() }?.let { stacksMap.getValue(index + 1).addLast(it) }
}
}
return stacksMap
}
private fun printResult(stacks: Map<Int, Stack>) =
stacks.entries.sortedBy { it.key }.map { it.value.first() }.joinToString("") { it.toString() }
private typealias Crate = Char
private typealias Stack = ArrayDeque<Crate>
private data class Instruction(val origin: Int, val destination: Int, val amount: Int) {
companion object {
fun of(line: String): Instruction {
return line
.split("move ", " from ", " to ")
.let { Instruction(origin = it[2].toInt(), destination = it[3].toInt(), amount = it[1].toInt()) }
}
}
}
| 0 | Kotlin | 0 | 0 | 1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1 | 2,791 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | import kotlin.math.abs
import kotlin.math.absoluteValue
fun main() {
fun isValid(point: Point, sensors: List<Sensor>): Boolean =
(point.x in 0..MAX_COORDINATES && point.y in 0..MAX_COORDINATES) && sensors.none { (sensor, beacon) ->
point.distanceTo(sensor) <= sensor.distanceTo(
beacon
)
}
fun part1(input: List<Sensor>): Int {
val beacons = input.map { it.beacon }.toSet()
return input.filter { abs(it.at.y - MAX_Y) < it.distanceToBeacon }
.fold(mutableSetOf<Int>()) { acc, sensor ->
val d = sensor.distanceToBeacon - sensor.at.distanceTo(Point(sensor.at.x, MAX_Y))
(-d..d).asSequence().map { sensor.at.x + it }.filter { Point(it, MAX_Y) !in beacons }
.forEach(acc::add)
acc
}.size
}
fun part2(input: List<Sensor>): Long {
for (sensor in input.sortedBy { it.distanceToBeacon }) {
for (x in sensor.distanceToBeacon + 1 downTo 1) for (p in sensor.at.toPoints(
x, y = sensor.distanceToBeacon + 1 - x
)) {
if (isValid(p, input)) {
return p.x.toLong() * MAX_COORDINATES + p.y
}
}
}
return -1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test").toSensors()
check(part1(testInput) == 0)
println(part2(testInput))
val input = readInput("Day15").toSensors()
println(part1(input))
println(part2(input))
}
fun List<String>.toSensors(): List<Sensor> = this.map { it.split(":") }
.map { (sensor, beacon) ->
val (sensorX, sensorY) = sensor.split(",")
val (beaconX, beaconY) = beacon.split(",")
Sensor(
Point(sensorX.substringAfter("x=").toInt(), sensorY.substringAfter("y=").toInt()),
Point(beaconX.substringAfter("x=").toInt(), beaconY.substringAfter("y=").toInt())
)
}
data class Sensor(
val at: Point,
val beacon: Point,
val distanceToBeacon: Int = (at.x - beacon.x).absoluteValue + (at.y - beacon.y).absoluteValue
)
const val MAX_Y = 2000000
const val MAX_COORDINATES = 4000000
fun Point.distanceTo(other: Point): Int =
(x - other.x).absoluteValue + (y - other.y).absoluteValue
fun Point.toPoints(x: Int, y: Int) =
sequenceOf(Point(x, y), Point(x, -y), Point(-x, y), Point(-x, -y))
.map { Point(this.x + it.x, this.y + it.y) } | 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 2,519 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | peterfortuin | 573,120,586 | false | {"Kotlin": 22151} | fun main() {
fun part1(input: List<String>): Int {
return input
.map { line ->
line.parseLine()
}.map { rangePair ->
when {
rangePair.first.intersect(rangePair.second) == rangePair.second.toSet() -> 1
rangePair.second.intersect(rangePair.first) == rangePair.first.toSet() -> 1
else -> 0
}
}.sum()
}
fun part2(input: List<String>): Int {
return input
.map { line ->
line.parseLine()
}.map { rangePair ->
when {
rangePair.first.intersect(rangePair.second).isNotEmpty() -> 1
rangePair.second.intersect(rangePair.first).isNotEmpty() -> 1
else -> 0
}
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Part 1 = ${part1(input)}")
println("Part 2 = ${part2(input)}")
}
private fun String.parseLine(): Pair<IntRange, IntRange> {
val parts = this.split(",")
val firstRange = parts[0].toRange()
val secondRange = parts[1].toRange()
return Pair(firstRange, secondRange)
}
private fun String.toRange(): IntRange {
val parts = this.split("-")
return IntRange(parts[0].toInt(), parts[1].toInt())
}
| 0 | Kotlin | 0 | 0 | c92a8260e0b124e4da55ac6622d4fe80138c5e64 | 1,528 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun solution(input: List<String>, part2: Boolean): Int {
val map = HashSet<Pair<Int, Int>>()
input.forEach { line ->
line.split(" -> ").windowed(2).forEach { (a, b) ->
val (x0, y0) = a.split(",").map { it.toInt() }
val (x1, y1) = b.split(",").map { it.toInt() }
for (x in min(x0, x1)..max(x0, x1)) {
for (y in min(y0, y1)..max(y0, y1)) {
map.add(Pair(x, y))
}
}
}
}
val minX = map.minBy { it.first }.first
val maxX = map.maxBy { it.first }.first
val maxY = map.maxBy { it.second }.second
var i = 0
outer@while (true) {
var sand = Pair(500, 0)
inner@while (true) {
when {
!part2 && (!(minX..maxX).contains(sand.first) || sand.second > maxY) -> break@outer
part2 && sand.second == maxY + 1 -> break@inner
!map.contains(Pair(sand.first, sand.second + 1)) -> {
sand = Pair(sand.first, sand.second + 1)
}
!map.contains(Pair(sand.first - 1, sand.second + 1)) -> {
sand = Pair(sand.first - 1, sand.second + 1)
}
!map.contains(Pair(sand.first + 1, sand.second + 1)) -> {
sand = Pair(sand.first + 1, sand.second + 1)
}
part2 && sand == Pair(500, 0) -> {
i++
break@outer
}
else -> break@inner
}
}
map.add(sand)
i++
}
return i
}
fun part1(input: List<String>) = solution(input, false)
fun part2(input: List<String>) = solution(input, true)
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 2,178 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | Misano9699 | 572,108,457 | false | null | const val LOSS = 0
const val DRAW = 3
const val WIN = 6
fun main() {
val elvesMap: Map<String, RockPaperScissors> = mapOf("A" to RockPaperScissors.ROCK, "B" to RockPaperScissors.PAPER, "C" to RockPaperScissors.SCISSORS)
val meMap: Map<String, RockPaperScissors> = mapOf("X" to RockPaperScissors.ROCK, "Y" to RockPaperScissors.PAPER, "Z" to RockPaperScissors.SCISSORS)
val winMap: Map<RockPaperScissors, RockPaperScissors> = mapOf(
RockPaperScissors.ROCK to RockPaperScissors.PAPER,
RockPaperScissors.PAPER to RockPaperScissors.SCISSORS,
RockPaperScissors.SCISSORS to RockPaperScissors.ROCK
)
val lossMap: Map<RockPaperScissors, RockPaperScissors> = mapOf(
RockPaperScissors.ROCK to RockPaperScissors.SCISSORS,
RockPaperScissors.PAPER to RockPaperScissors.ROCK,
RockPaperScissors.SCISSORS to RockPaperScissors.PAPER
)
fun calculateScore(elf: RockPaperScissors, outcome: String): Int = when (outcome) {
"X" -> elf.score(lossMap[elf]!!)
"Y" -> elf.score(elf)
"Z" -> elf.score(winMap[elf]!!)
else -> throw IllegalArgumentException("Ongeldige waarde")
}
fun part1(input: List<String>): Int {
return input.sumOf {
val split = it.split(" ")
elvesMap[split[0]]!!.score(meMap[split[1]]!!)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val split = it.split(" ")
calculateScore(elvesMap[split[0]]!!, split[1])
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val input = readInput("Day02")
check(part1(testInput).also { println("Answer test input part1: $it") } == 15)
println("Answer part1: " + part1(input))
check(part2(testInput).also { println("Answer test input part2: $it") } == 12)
println("Answer part2: " + part2(input))
}
enum class RockPaperScissors(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun score(other: RockPaperScissors): Int = when {
this.ordinal == other.ordinal -> DRAW + other.score
this == ROCK && other == SCISSORS -> LOSS + other.score
this == SCISSORS && other == ROCK -> WIN + other.score
this.ordinal < other.ordinal -> WIN + other.score
else -> LOSS + other.score
}
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 2,384 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | enum class Gesture(val points: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
fun Gesture.beats() = when (this) {
Gesture.ROCK -> Gesture.SCISSORS
Gesture.PAPER -> Gesture.ROCK
Gesture.SCISSORS -> Gesture.PAPER
}
fun Gesture.beatenBy() = Gesture.values().find { it beats this }!!
infix fun Gesture.beats(other: Gesture) = this.beats() == other
infix fun Gesture.beatenBy(other: Gesture) = this.beatenBy() == other
enum class Outcome(val points: Int) {
WIN(6),
DRAW(3),
LOSS(0)
}
fun main() {
fun List<String>.parseInput() = map {
val (a, b) = it.split(' ')
a.first() to b.first()
}
fun Char.toGesture(): Gesture {
require(this in 'A'..'C' || this in 'X'..'Z')
return when (this) {
'A', 'X' -> Gesture.ROCK
'B', 'Y' -> Gesture.PAPER
'C', 'Z' -> Gesture.SCISSORS
else -> error("Unknown input $this")
}
}
fun Char.toOutcome(): Outcome {
require(this in 'X'..'Z')
return when (this) {
'X' -> Outcome.LOSS
'Y' -> Outcome.DRAW
'Z' -> Outcome.WIN
else -> error("Unknown input $this")
}
}
fun calculateOutcome(first: Gesture, second: Gesture): Outcome {
return if (first == second) Outcome.DRAW
else if (first beats second) Outcome.WIN
else Outcome.LOSS
}
fun calculateScore(oponentGesture: Gesture, myGesture: Gesture) =
myGesture.points + calculateOutcome(myGesture, oponentGesture).points
fun part1(input: List<Pair<Char, Char>>): Int {
return input.sumOf { (oponenteCode, myCode) ->
calculateScore(oponenteCode.toGesture(), myCode.toGesture())
}
}
fun part2(input: List<Pair<Char, Char>>): Int {
return input.sumOf { (oponenteCode, gameResultCode) ->
val oponentGesture = oponenteCode.toGesture()
val myGesture = when (gameResultCode.toOutcome()) {
Outcome.DRAW -> oponentGesture
Outcome.LOSS -> oponentGesture.beats()
Outcome.WIN -> oponentGesture.beatenBy()
}
calculateScore(oponentGesture, myGesture)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test").parseInput()
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 2,531 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | data class Monkey(val items: MutableList<Long>,
val operation: (Long) -> Long,
val testValue: Int,
val ifTrue: Int,
val ifFalse: Int,) {
var inspected: Long = 0
// Pair<ToMonkey, newWorryLevel>
private fun test(manageWorryLevel: (Long) -> Long, value: Long): Pair<Int, Long> {
val newWorryLevel = manageWorryLevel(value)
return if (newWorryLevel % testValue == 0L)
Pair(ifTrue, newWorryLevel) else Pair(ifFalse, newWorryLevel)
}
fun testItems(manageWorryLevel: (Long) -> Long): MutableList<Pair<Int, Long>> {
var results = mutableListOf<Pair<Int , Long>>()
items.forEach{item ->
val worryLevelInspection = this.operation(item)
val toMonkeyNewWorryLevel = this.test(manageWorryLevel, worryLevelInspection)
results.add(toMonkeyNewWorryLevel)
inspected++
}
items.clear()
return results
}
}
fun main() {
fun operation(operationValue: String): (Long) -> Long {
return when {
operationValue == "* old" -> { first: Long -> first * first }
operationValue.startsWith("* ") -> {
first: Long -> first * operationValue.split("* ")[1].toLong()
}
operationValue.startsWith("+ ") -> {
first: Long -> first + operationValue.split("+ ")[1].toLong()
}
else -> {throw IllegalArgumentException("parsing operations")}
}
}
fun solve(input: List<String>, rounds: Int): Long {
var monkeys = mutableListOf<Monkey>()
input.windowed(7, step = 7, partialWindows = true).forEach { line ->
val monkey = Monkey(
line[1].substringAfter(": ").split(", ")
.map { it.toLong() }.toMutableList(),
operation(line[2].split(" Operation: new = old ")[1]),
line[3].split("Test: divisible by ")[1].toInt(),
line[4].split("If true: throw to monkey ")[1].toInt(),
line[5].split("If false: throw to monkey ")[1].toInt()
)
monkeys.add(monkey)
}
var manageWorryLevel: (Long) -> Long = if (rounds == 20) {
{ worryLevel: Long -> worryLevel / 3 }
} else {
val commonDivisor = monkeys.map { it.testValue }.reduce { acc, i -> acc * i }
({ worryLevel: Long -> worryLevel % commonDivisor })
}
repeat(rounds) {
monkeys.forEach { monkey ->
monkey.testItems(manageWorryLevel).forEach { result ->
monkeys[result.first]?.items?.add(result.second)
}
}
}
return monkeys.map { it.inspected }.sortedDescending().subList(0, 2)
.reduce { acc, i -> acc * i }
}
var test = solve(readInput("Day11_test"), 20)
println("Test1: $test")
check(test == 10605L)
test = solve(readInput("Day11_test"), 10000)
println("Test2: $test")
val first = solve(readInput("Day11_input"), 20)
println("Part1: $first")
val second = solve(readInput("Day11_input"), 10000)
println("Part2: $second")
}
| 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 3,235 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
private val MOVES: Map<Char, Pair<Int, Int>> =
mapOf(Pair('U', Pair(0, 1)), Pair('D', Pair(0, -1)), Pair('L', Pair(-1, 0)), Pair('R', Pair(1, 0)))
fun main() {
fun kingDist(a: Pair<Int, Int>, b: Pair<Int, Int>): Int {
return max(abs(a.first - b.first), abs(a.second - b.second))
}
fun moveOneStep(from: Pair<Int, Int>, to: Pair<Int, Int>): Pair<Int, Int> {
return Pair(from.first + (to.first - from.first).sign, from.second + (to.second - from.second).sign)
}
fun applyMove(a: Pair<Int, Int>, dir: Char, len: Int) =
Pair(a.first + MOVES[dir]!!.first * len, a.second + MOVES[dir]!!.second * len)
fun walkAsRope(input: List<String>, ropeLen: Int): Int {
val visitedPoints: MutableSet<Pair<Int, Int>> = mutableSetOf(Pair(0, 0))
val currentParts = Array(ropeLen) { Pair(0, 0) }
input.map { it.split(" ") }.map { (charS, lenS) -> Pair(charS[0], lenS.toInt()) }.forEach { (char, len) ->
currentParts[0] = applyMove(currentParts[0], char, len)
while (kingDist(currentParts[0], currentParts[1]) > 1) {
for (i in 1 until currentParts.size) {
if (kingDist(currentParts[i - 1], currentParts[i]) > 1)
currentParts[i] = moveOneStep(currentParts[i], currentParts[i - 1])
if (i == currentParts.lastIndex) visitedPoints.add(currentParts[i])
}
}
}
return visitedPoints.size
}
fun part1(input: List<String>): Int {
return walkAsRope(input, 2)
}
fun part2(input: List<String>): Int {
return walkAsRope(input, 10)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 88)
check(part2(testInput) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 2,009 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/_2018/Day11.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2018
import aocRun
fun main() {
aocRun(puzzleInput) { input ->
val grid = calcPowerLevels(input.toInt())
//grid.forEach { println(it.joinToString()) }
val totals = calcTotals(grid, 3)
return@aocRun totals.maxByOrNull { it.value }.let { "(${it!!.key.first + 1},${it.key.second + 1}) = ${it.value}" }
}
aocRun(puzzleInput) { input ->
val grid = calcPowerLevels(input.toInt())
println("Calculated power levels")
val totals = (0..300).toList().stream().parallel().map { it to calcTotals(grid, it) }
val largestTotalsPerSize = totals.map { sizeTotals ->
val largestForSize = sizeTotals.second.maxByOrNull { it.value }!!
return@map Triple(largestForSize.key, largestForSize.value, sizeTotals.first)
}
val largestTotal = largestTotalsPerSize.max { o1, o2 -> o1.second.compareTo(o2.second) }.get()
return@aocRun "(${largestTotal.first.first + 1},${largestTotal.first.second + 1},${largestTotal.third}) = ${largestTotal.second}"
}
}
private fun calcPowerLevels(serialNum: Int): Array<Array<Int>> =
Array(300) { x -> Array(300) { y -> calcPowerLevel(x + 1, y + 1, serialNum) } }
private fun calcPowerLevel(x: Int, y: Int, serialNum: Int): Int {
val rackId = x + 10
var powerLevel = rackId
powerLevel *= y
powerLevel += serialNum
powerLevel *= rackId
val powerString = powerLevel.toString()
val strLength = powerString.length
powerLevel = if (strLength >= 3) powerString[strLength - 3].toString().toInt() else 0
powerLevel -= 5
return powerLevel
}
private fun calcTotals(grid: Array<Array<Int>>, squareSize: Int): Map<Pair<Int, Int>, Int> {
println("Calculating total for square size $squareSize")
val max = 300 - squareSize
val totalsMap = mutableMapOf<Pair<Int, Int>, Int>()
(0..max).forEach { x ->
(0..max).forEach { y ->
totalsMap[x to y] = calc3x3TotalPower(grid, squareSize, x, y)
}
}
return totalsMap
}
private fun calc3x3TotalPower(grid: Array<Array<Int>>, squareSize: Int, x: Int, y: Int): Int {
var total = 0
(x until x + squareSize).forEach { gridX ->
(y until y + squareSize).forEach { gridY ->
total += grid[gridX][gridY]
}
}
return total
}
private const val puzzleInput = "9445"
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 2,368 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/days/Solution07.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
enum class HandType : Comparable<HandType> {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND
}
class CamelHand(private val cards: CharArray, val bid: Int, var jokerWildcard: Boolean = false) : Comparable<CamelHand> {
private fun getCardValue(c: Char) = mapOf(
'2' to 2,
'3' to 3,
'4' to 4,
'5' to 5,
'6' to 6,
'7' to 7,
'8' to 8,
'9' to 9,
'T' to 10,
'J' to if (jokerWildcard) 1 else 11,
'Q' to 12,
'K' to 13,
'A' to 14
).getOrDefault(c, 0)
private val handType: HandType
get() {
val cardCounts = mutableMapOf<Char, Int>().withDefault { 0 }
cards.forEach { cardCounts.merge(it, 1, Int::plus) }
val jokers = if (jokerWildcard) cardCounts.remove('J') ?: 0 else 0
val sortedCounts = cardCounts.values.sortedDescending()
val first = sortedCounts.firstOrNull() ?: 0
val second = sortedCounts.drop(1).firstOrNull() ?: 0
return when {
first + jokers == 5 -> HandType.FIVE_OF_A_KIND
first + jokers == 4 -> HandType.FOUR_OF_A_KIND
first + jokers == 3 && second == 2 -> HandType.FULL_HOUSE
first + jokers == 3 -> HandType.THREE_OF_A_KIND
first == 2 && second == 2 -> HandType.TWO_PAIR
first + jokers == 2 -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
}
private val comparisonValues
get() = sequenceOf(handType.ordinal) + cards.asSequence().map(::getCardValue)
override fun compareTo(other: CamelHand) = comparisonValues.zip(other.comparisonValues)
.map { it.first - it.second }
.filter { it != 0 }
.firstOrNull() ?: 0
companion object {
fun fromString(string: String): CamelHand {
val (cards, bid) = string.split(' ')
return CamelHand(cards.toCharArray(), bid.toInt())
}
}
}
object Solution07 : Solution<List<CamelHand>>(AOC_YEAR, 7) {
override fun getInput(handler: InputHandler) = handler.getInput("\n").map(CamelHand::fromString)
override fun solve(input: List<CamelHand>): PairOf<Int> {
fun List<CamelHand>.totalWinnings() = this.withIndex().sumOf { (it.index + 1) * it.value.bid }
val hands = input.toMutableList()
hands.sort()
val ans1 = hands.totalWinnings()
hands.forEach { it.jokerWildcard = true }
hands.sort()
val ans2 = hands.totalWinnings()
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 2,765 | Advent-of-Code-2023 | MIT License |
src/Day13.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | private val DIVIDER_PACKETS = listOf("[[2]]", "[[6]]")
private sealed interface Signal : Comparable<Signal?> {
override operator fun compareTo(signal: Signal?): Int
}
private data class SingleSignal(val element: Int) : Signal {
fun toMultiSignal() = MultiSignal(listOf(this))
override fun compareTo(signal: Signal?) = when (signal) {
null -> 1
is SingleSignal -> element.compareTo(signal.element)
is MultiSignal -> toMultiSignal().compareTo(signal)
}
}
private data class MultiSignal(val items: List<Signal>) : Signal {
override fun compareTo(signal: Signal?): Int = when (signal) {
null -> 1
is SingleSignal -> compareTo(signal.toMultiSignal())
is MultiSignal -> items.mapIndexed { i, e -> e.compareTo(signal.items.getOrNull(i)) }.firstOrNull { it != 0 }
?: items.size.compareTo(signal.items.size)
}
}
private fun parseSignal(input: String): Signal {
val res = mutableListOf<Signal>()
var values = input.substring(1, input.length - 1)
while (values.contains(',')) {
val number = values.substringBefore(',').toIntOrNull()
res += if (number != null) {
SingleSignal(number)
} else {
val list = values.firstInnerList()
parseSignal(list).also { values = values.substringAfter(list) }
}
values = values.substringAfter(',')
}
if (values.contains('[')) {
res += parseSignal(values)
} else if (values.isNotEmpty()) {
res += SingleSignal(values.toInt())
}
return MultiSignal(res)
}
private fun String.firstInnerList(): String {
var balance = 0
for (i in indices) {
when (get(i)) {
'[' -> balance++
']' -> balance--
}
if (balance == 0) return substring(0, i + 1) // assuming given string starts with '['.
}
return this
}
fun main() {
fun part1(input: List<List<String>>) =
input.map { (first, second) -> parseSignal(first) to parseSignal(second) }.withIndex()
.filter { (_, value) -> value.first < value.second }.sumOf { (i) -> i + 1 }
fun part2(input: List<List<String>>): Int {
val signals = input.flatten().toMutableList()
signals.addAll(DIVIDER_PACKETS)
val sortedSignals = signals.map(::parseSignal).sorted()
return DIVIDER_PACKETS.map { sortedSignals.indexOf(parseSignal(it)) + 1 }.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readBlocks("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readBlocks("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 2,732 | advent-of-code-kotlin | Apache License 2.0 |
src/Day11.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
fun part1(monkeys: List<Monkey>, rounds: Int): Long {
(1..rounds).forEach { _ ->
monkeys.forEach { monkey -> monkey.evaluate(monkeys) { it.floorDiv(3) } }
}
return monkeys
.sortedByDescending { it.inspections }
.take(2)
.fold(1L) { acc, curr -> acc * curr.inspections }
}
fun part2(monkeys: List<Monkey>, rounds: Int): Long {
val testProduct: Long = monkeys.map { it.test }.reduce { acc, curr -> acc * curr}
(1..rounds).forEach { _ ->
monkeys.forEach { monkey -> monkey.evaluate(monkeys) { it % testProduct } }
}
return monkeys
.sortedByDescending { it.inspections }
.take(2)
.fold(1L) { acc, curr -> acc * curr.inspections }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
val testMonkeysSilver = determineMonkeys(testInput)
val testMonkeysGold = determineMonkeys(testInput)
check(part1(testMonkeysSilver, 20) == 10605L)
check(part2(testMonkeysGold, 10000) == 2713310158L)
val input = readInput("Day11")
val monkeysSilver = determineMonkeys(input)
val monkeysGold = determineMonkeys(input)
println(part1(monkeysSilver, 20))
println(part2(monkeysGold, 10000))
}
private fun determineMonkeys(input: List<String>): List<Monkey> =
input
.splitBy { it.isEmpty() }
.map {
val items = it[1].substringAfter("Starting items: ", "").trim().split(", ").map { it.toLong() }
val operand = it[2].substringAfterLast(" ")
val operator = it[2].substringAfter("old ").first().toString()
val operation: (Long) -> Long = { v ->
if (operator == "*") {
if (operand == "old") {
v * v
} else {
v * operand.toLong()
}
} else if (operator == "+") {
if (operand == "old") {
v + v
} else {
v + operand.toLong()
}
} else {
throw IllegalArgumentException("Unknown operand $operator")
}
}
val test = it[3].substringAfterLast(" ").toLong()
val monkeyTrue = it[4].substringAfterLast(" ").toInt()
val monkeyFalse = it[5].substringAfterLast(" ").toInt()
Monkey(items.toMutableList(), operation, test, monkeyTrue, monkeyFalse)
}
private class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val monkeyTrue: Int,
val monkeyFalse: Int,
var inspections: Long = 0L
) {
fun evaluate(monkeys: List<Monkey>, extraOperation: (Long) -> Long = { it }) {
items.forEach { item ->
val worryLevel = extraOperation(operation(item))
if (worryLevel % test == 0L) {
monkeys[monkeyTrue].items.add(worryLevel)
} else {
monkeys[monkeyFalse].items.add(worryLevel)
}
}
inspections += items.size
items.clear()
}
}
| 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 3,264 | adventofcode-2022 | Apache License 2.0 |
src/day08/Day08.kt | pnavais | 727,416,570 | false | {"Kotlin": 17859} | package day08
import readInput
class Node(val name: String, var left: Node? = null, var right: Node? = null)
private fun readNetwork(input: List<String>): Map<String, Node> {
val nodeMap = mutableMapOf<String, Node>()
input.drop(2).forEach { s ->
val (currentName, siblings) = s.split("[\\s+]=[\\s+]".toRegex())
val (leftNode, rightNode) = siblings.replace("(","").replace(")","").split(", ").map { nodeMap.merge(it, Node(name = it)) { n, _ -> n } }
val currentNode = nodeMap.merge(currentName, Node(name = currentName)) { n, _ -> n }
//if (!currentNode?.isTerminal()!!) {
currentNode?.left = leftNode
currentNode?.right = rightNode
//}
}
return nodeMap
}
fun traverse(movements: String, startNode: Node, stopCondition: (n: Node) -> Boolean): Long {
var steps = 0L
var movementIterator = movements.iterator()
var currentNode : Node? = startNode
val visitedNodes = mutableSetOf<String>()
visitedNodes.add(startNode.name)
while (stopCondition(currentNode!!)) {
if (!movementIterator.hasNext()) {
movementIterator = movements.iterator()
}
val movement = movementIterator.next()
currentNode = if (movement == 'L') { currentNode.left } else { currentNode.right }
steps++
}
return steps
}
// Recursive method to return gcd of a and b
fun gcd(a: Long, b: Long): Long {
if (a == 0L) return b
return gcd(b % a, a)
}
// method to return LCM of two numbers
fun lcm(a: Long, b: Long): Long {
return (a / gcd(a, b)) * b
}
fun part1(input: List<String>): Long {
val movements = input.first()
val nodeMap = readNetwork(input)
return traverse(movements, nodeMap["AAA"]!!) { n -> n.name != "ZZZ" }
}
fun part2(input: List<String>): Long {
val movements = input.first()
val nodeMap = readNetwork(input)
var steps = 1L
// Find all starting nodes
val startNodes = nodeMap.filterKeys { s -> s.endsWith('A') }.map { e -> e.value }
for (node in startNodes) {
steps = lcm(steps, traverse(movements, node) { n -> !n.name.endsWith("Z") })
}
return steps
}
fun main() {
val testInput = readInput("input/day08")
//println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | f5b1f7ac50d5c0c896d00af83e94a423e984a6b1 | 2,300 | advent-of-code-2k3 | Apache License 2.0 |
src/year2021/Day9.kt | drademacher | 725,945,859 | false | {"Kotlin": 76037} | package year2021
import Point
import readLines
fun main() {
val input = parseInput(readLines("2021", "day9"))
val testInput = parseInput(readLines("2021", "day9_test"))
check(part1(testInput) == 15)
println("Part 1:" + part1(input))
check(part2(testInput) == 1134)
println("Part 2:" + part2(input))
}
private fun parseInput(lines: List<String>): Day9Input {
return lines
.map { line -> line.split("").filter { it != "" }.map { it.toInt() } }
}
private fun part1(input: Day9Input): Int {
return determineLowPoints(input).sumOf { input[it.y][it.x] + 1 }
}
private fun determineLowPoints(input: Day9Input): Set<Point> {
val lowPoints = mutableSetOf<Point>()
for (y in input.indices) {
for (x in input[y].indices) {
if (getOrthogonalNeighbors(input, Point(x, y)).all { input[it.y][it.x] > input[y][x] }) {
lowPoints.add(Point(x, y))
}
}
}
return lowPoints
}
private fun getOrthogonalNeighbors(
input: Day9Input,
point: Point,
): Set<Point> {
val result = mutableSetOf<Point>()
if (point.x > 0) result.add(Point(point.x - 1, point.y))
if (point.x < input[point.y].size - 1) result.add(Point(point.x + 1, point.y))
if (point.y > 0) result.add(Point(point.x, point.y - 1))
if (point.y < input.size - 1) result.add(Point(point.x, point.y + 1))
return result
}
private fun part2(input: Day9Input): Int {
return determineLowPoints(input)
.map { lowPoint -> findBasin(input, lowPoint) }
.map { it.size }
.sorted()
.reversed()
.take(3)
.reduce { a, b -> a * b }
}
private fun findBasin(
input: Day9Input,
start: Point,
): Set<Point> {
val frontier = mutableListOf(start)
val visited = mutableSetOf<Point>()
while (frontier.size > 0) {
val next = frontier.removeFirst()
if (visited.contains(next) || input[next.y][next.x] == 9) {
continue
}
visited.add(next)
val neighbors = getOrthogonalNeighbors(input, next)
frontier.addAll(neighbors)
}
return visited
}
private typealias Day9Input = List<List<Int>>
| 0 | Kotlin | 0 | 0 | 4c4cbf677d97cfe96264b922af6ae332b9044ba8 | 2,190 | advent_of_code | MIT License |
src/Day04.kt | jwalter | 573,111,342 | false | {"Kotlin": 19975} | fun main() {
fun Pair<Int, Int>.rangeContains(other: Pair<Int, Int>): Boolean {
return first <= other.first && second >= other.second
}
fun fullyContains(a: Pair<Int, Int>, b: Pair<Int, Int>): Boolean {
return a.rangeContains(b) || b.rangeContains(a)
}
fun overlaps(a: Pair<Int, Int>, b: Pair<Int, Int>): Boolean {
val aRange = a.first..a.second
val bRange = b.first..b.second
return aRange.contains(b.first) ||
aRange.contains(b.second) ||
bRange.contains(a.first) ||
bRange.contains(a.second)
}
fun countRangesMatching(input: List<String>, predicate: (Pair<Int, Int>, Pair<Int, Int>) -> Boolean): Int {
return input
.map { it.split(",") }
.map {
it
.map { assignment ->
assignment
.split("-")
.map(String::toInt)
.let { p -> p.first() to p.last() }
}.let { elfPairAssignment ->
predicate(elfPairAssignment.first(), elfPairAssignment.last())
}
}.count { it }
}
fun part1(input: List<String>): Int {
return countRangesMatching(input, ::fullyContains)
}
fun part2(input: List<String>): Int {
return countRangesMatching(input, ::overlaps)
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 576aeabd297a7d7ee77eca9bb405ec5d2641b441 | 1,649 | adventofcode2022 | Apache License 2.0 |
src/Day12.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | import java.util.*
class Graph<T> {
private val adjacencyMap: HashMap<T, HashSet<T>> = HashMap()
fun addEdge(node1: T, node2: T) {
adjacencyMap.computeIfAbsent(node1) { HashSet() }.add(node2)
}
fun shortestPath(start: T, endCondition: (T) -> Boolean): Int {
val visited = HashSet<T>()
val queue = PriorityQueue<Pair<T, Int>>(compareBy { it.second })// queue base on distance
queue.add(Pair(start, 0))
while (queue.isNotEmpty()) {
val (node, distance) = queue.poll()
if (node !in visited) {
visited.add(node)
adjacencyMap[node]?.forEach {
if (endCondition(it)) {
return distance + 1
}
queue.add(Pair(it, distance + 1))
}
}
}
throw IllegalStateException("No path found")
}
}
class Day12Solver(private val gridMap: List<String>) {
data class MyPoint(val row: Int, val col: Int, val elevation: Int, val isSource: Boolean, val isTarget: Boolean) {
fun neighbors(grid: List<List<MyPoint>>): List<MyPoint> {
return listOfNotNull(
grid.getOrNull(row - 1)?.getOrNull(col),
grid.getOrNull(row + 1)?.getOrNull(col),
grid.getOrNull(row)?.getOrNull(col - 1),
grid.getOrNull(row)?.getOrNull(col + 1)
)
}
fun canMoveTo(other: MyPoint): Boolean {
return other.elevation - this.elevation <= 1
}
}
private val grid = processInput()
private lateinit var startPoint: MyPoint
private lateinit var endPoint: MyPoint
private fun processInput(): List<List<MyPoint>> {
return gridMap.mapIndexed { r, line ->
line.mapIndexed { c, elevation ->
when (elevation) {
'S' -> {
MyPoint(row = r, col = c, elevation = 'a' - 'a', isSource = true, isTarget = false)
.also {
startPoint = it
}
}
'E' -> {
MyPoint(row = r, col = c, elevation = 'z' - 'a', isSource = false, isTarget = true)
.also {
endPoint = it
}
}
else -> {
MyPoint(row = r, col = c, elevation = elevation - 'a', isSource = false, isTarget = false)
}
}
}
}
}
private fun generateGraph(isPart1: Boolean): Graph<MyPoint> {
val graph = Graph<MyPoint>()
grid.forEach { p ->
p.forEach { point ->
val neighbors = point.neighbors(grid)
neighbors.forEach { neighbor ->
if (point.canMoveTo(neighbor)) {
if (isPart1)
graph.addEdge(point, neighbor)
else {
graph.addEdge(neighbor, point)
}
}
}
}
}
return graph
}
fun solve(part1: Boolean): Int {
if (part1) {
return generateGraph(true).shortestPath(startPoint) { it.isTarget }
}
return generateGraph(false).shortestPath(endPoint) { it.elevation == 0 }
}
}
fun main() {
// val data = readInput("Day12_test")
val data = readInput("Day12")
val solver = Day12Solver(data)
// check(solver.solve(true) == 31)
// check(solver.solve(false) == 29)
println(solver.solve(true))
println(solver.solve(false))
} | 0 | Kotlin | 0 | 0 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 3,769 | advent_code_2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day07.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import kotlin.math.abs
import kotlin.math.min
/**
* Transforms this [IntArray] so that at each index in the result array gives the amount of occurrences of that index
* value in the original array
*
* For example: [0, 0, 2] -> [2, 0, 1]
* -> original array contained two zeros -> result[0] = 2
*
* @return the consolidated array
*/
private fun IntArray.consolidate(): IntArray {
val consolidated = IntArray(maxOf { it } + 1)
groupBy { it }.mapValues { it.value.count() }.forEach { consolidated[it.key] = it.value }
return consolidated
}
private fun IntArray.getMedianIndex(): Int {
val elements = sum()
var elementsSoFar = 0
return withIndex().takeWhile {
elementsSoFar += it.value
elementsSoFar <= elements / 2
}.last().index
}
/**
* @param positions the horizontal positions (index) and the amount of submarines at that position (value)
* @param destinationIndex the target position where to move all submarines
* @param consumptionRate a function to calculate the fuel necessary for one submarine to move a given distance
* @return the total fuel necessary to move all submarines to [destinationIndex]
*/
private inline fun getTotalFuelConsumption(
positions: IntArray,
destinationIndex: Int,
consumptionRate: (Int) -> Int
) = positions.withIndex().sumOf { it.value * consumptionRate(abs(destinationIndex - it.index)) }
private fun part1(input: List<String>): Int {
val array = input.first().split(",").map { it.toInt() }.toIntArray().consolidate()
val median = array.getMedianIndex() // small optimization: target index should be around the median
var minConsumption = Int.MAX_VALUE
for (i in -1..1) {
minConsumption = min(minConsumption, getTotalFuelConsumption(array, median + i) { distance -> distance })
}
return minConsumption
}
private fun part2(input: List<String>): Int {
val array = input.first().split(",").map { it.toInt() }.toIntArray().consolidate()
var minConsumption = Int.MAX_VALUE
for (i in array.indices) {
val consumption = getTotalFuelConsumption(array, i) { distance -> 0.rangeTo(distance).sum() }
if (consumption < minConsumption) {
minConsumption = consumption
} else {
break
}
}
return minConsumption
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 37)
check(part2(testInput) == 168)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,638 | adventOfCode | Apache License 2.0 |
src/2022/Day08.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
fun main() {
fun part1(input: List<String>): Int {
val forest = input.map { it.asIterable().map { char -> char.toString().toInt() } }
return forest.flatMapIndexed { row, trees ->
trees.filterIndexed { column, treeHeight ->
val checkTop = forest.subList(0, row).map { it[column] }.all { it < treeHeight }
val checkBottom = forest.subList(row + 1, forest.size).map { it[column] }.all { it < treeHeight }
val checkLeft = trees.subList(0, column).all { it < treeHeight }
val checkRight = trees.subList(column + 1, trees.size).all { it < treeHeight }
checkTop || checkBottom || checkLeft || checkRight
}
}.size
}
fun part2(input: List<String>): Int {
val forest = input.map { it.asIterable().map { char -> char.toString().toInt() } }
return forest.flatMapIndexed { row, trees ->
trees.mapIndexed { column, treeHeight ->
val top = forest.subList(0, row).reversed().map { it[column] }.visibleTrees(treeHeight)
val bottom = forest.subList(row + 1, forest.size).map { it[column] }.visibleTrees(treeHeight)
val left = trees.subList(0, column).reversed().visibleTrees(treeHeight)
val right = trees.subList(column + 1, trees.size).visibleTrees(treeHeight)
top * bottom * left * right
}
}.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
fun List<Int>.visibleTrees(treeHeight: Int): Int {
return (takeWhile { it < treeHeight }.size + 1).coerceAtMost(size)
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 1,895 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Day18.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day18.solvePart1())
println(Day18.solvePart2())
}
object Day18 {
private val numbers = readInput("day18").map { parse(it) }
fun solvePart1() = numbers.reduce(::add).magnitude()
fun solvePart2() = (0 until numbers.lastIndex)
.flatMap { i ->
(i + 1..numbers.lastIndex).flatMap { j ->
listOf(i to j, j to i)
}
}
.map { (i, j) -> add(numbers[i], numbers[j]) }
.maxOf { it.magnitude() }
private fun add(a: SNumber, b: SNumber): SNumber {
return SNumber((a.values + b.values).map { it.copy(depth = it.depth + 1) }.toMutableList()).reduce()
}
private fun SNumber.reduce(): SNumber {
while (explode() || split()) {
// the show must go on
}
return this
}
private fun SNumber.explode(): Boolean {
val i = values.windowed(2).indexOfFirst { (l, r) -> l.depth == r.depth && l.depth >= 5 }.takeIf { it >= 0 } ?: return false
val l = values.removeAt(i)
val r = values.removeAt(i)
values.getOrNull(i - 1)?.apply { value += l.value }
values.getOrNull(i)?.apply { value += r.value }
values.add(i, SValue(0, l.depth - 1))
return true
}
private fun SNumber.split(): Boolean {
val i = values.indexOfFirst { it.value >= 10 }.takeIf { it >= 0 } ?: return false
val num = values.removeAt(i)
values.add(i, SValue(num.value - num.value / 2, num.depth + 1))
values.add(i, SValue(num.value / 2, num.depth + 1))
return true
}
private fun SNumber.magnitude(): Int {
val v = values.toMutableList()
for (depth in 4 downTo 1) {
var i = v.indexOfFirst { it.depth == depth }
while (i >= 0) {
val l = v.removeAt(i).value
val r = v.removeAt(i).value
v.add(i, SValue(l * 3 + r * 2, depth - 1))
i = v.indexOfFirst { it.depth == depth }
}
}
return v.single().value
}
private fun parse(line: String): SNumber {
var depth = 0
return line.fold<MutableList<SValue>>(mutableListOf()) { list, c ->
when (c) {
'[' -> depth++
']' -> depth--
in '0'..'9' -> list += SValue(c.digitToInt(), depth)
}
list
}.let { SNumber(it) }
}
private data class SValue(var value: Int, val depth: Int)
private data class SNumber(val values: MutableList<SValue>)
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 2,556 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/twentythree/Day04.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentythree
import kotlin.math.pow
const val day = "04"
fun main() {
// test if implementation meets criteria from the description:
println("Day$day Test Answers:")
val testInput = readInputLines("Day${day}_test")
val part1 = part1(testInput)
part1.println()
check(part1 == 13)
val part2 = part2(testInput)
part2.println()
check(part2 == 30)
println("---")
println("Solutions:")
val input = readInputLines("Day${day}_input")
part1(input).println()
part2(input).println()
testAlternativeSolutions()
}
val points = listOf(0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 4096*2, 4096*4, 4096*8, 4096*16)
private fun part1(input: List<String>): Int {
return input.sumOf { inputLine ->
val (_, gameLine) = inputLine.split(":")
val (targetsString, ourScoresString) = gameLine.split("|")
val targets = targetsString.trim().split(" ").filter { it != "" }
val ourScores = ourScoresString.trim().split(" ").filter { it != "" }
val countingScores = ourScores.filter { targets.contains(it) }
points[countingScores.size]
}
}
private fun part2(input: List<String>): Int {
val cards = MutableList(input.size) { 1 }
input.forEachIndexed { index, inputLine ->
val (_, gameLine) = inputLine.split(":")
val (targetsString, ourScoresString) = gameLine.split("|")
val targets = targetsString.trim().split(" ").filter { it != "" }
val ourScores = ourScoresString.trim().split(" ").filter { it != "" }
val countingScores = ourScores.filter { targets.contains(it) }
val winning = countingScores.size
// add winning copies
for (i in index+1..(index+winning)) {
cards[i] += cards[index]
}
}
return cards.sum()
}
// ------------------------------------------------------------------------------------------------
private fun testAlternativeSolutions() {
val testInput = readInputLines("Day${day}_test")
check(alternativePart1(testInput) == 13)
// check(part2AlternativeSolution(testInput) == 281)
println("Alternative Solutions:")
val input = readInputLines("Day${day}_input")
println(alternativePart1(input))
// println(part2(input))
}
private fun alternativePart1(input: List<String>): Int {
return input.sumOf { inputLine ->
val (_, gameLine) = inputLine.split(":")
val (targetsString, ourScoresString) = gameLine.split("|")
val targets = targetsString.trim().replace(" ", " ").split(" ")
val ourScores = ourScoresString.trim().replace(" ", " ").split(" ")
val countingScores = ourScores.count { targets.contains(it) }
if (countingScores == 0) {
0
} else {
2.pow(countingScores-1)
}
}
}
fun Int.pow(n: Int): Int {
return this.toDouble().pow(n.toDouble()).toInt()
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 2,919 | advent-of-code-solutions | Apache License 2.0 |
src/Day07.kt | icoffiel | 572,651,851 | false | {"Kotlin": 29350} | fun main() {
class Node(
val name: String,
var size: Int,
val parent: Node? = null,
val children: MutableList<Node> = mutableListOf()
)
fun directoryList(node: Node): List<Node> {
return listOf(node) + node.children.map { directoryList(it) }.flatten()
}
fun calculateDirectorySize(node: Node): Int {
if (node.children.isEmpty()) {
return node.size
}
return node.size + node.children.sumOf { calculateDirectorySize(it) }
}
fun part1(input: List<String>): Int {
val rootNode = Node(name = "/", size = 0)
var currentNode = rootNode
input
.filter { !it.startsWith("$ ls") }
.forEach {
when {
it.startsWith("$ cd") -> {
val splits = it.split(" ")
currentNode = when(val target = splits.last()) {
"/" -> rootNode
".." -> currentNode.parent ?: rootNode
else -> currentNode.children.first { child -> child.name == target }
}
}
it.startsWith("dir") -> {
val (_, name) = it.split(" ")
currentNode.children.add(Node(name = name, size = 0, parent = currentNode))
}
else -> {
val (size, _) = it.split(" ")
currentNode.size += size.toInt()
}
}
}
return directoryList(rootNode)
.filter { it.name != "/" }
.map { calculateDirectorySize(it) }
.filter { it < 100000 }
.sum()
}
fun part2(input: List<String>): Int {
val rootNode = Node(name = "/", size = 0)
var currentNode = rootNode
input
.filter { !it.startsWith("$ ls") }
.forEach {
when {
it.startsWith("$ cd") -> {
val splits = it.split(" ")
currentNode = when(val target = splits.last()) {
"/" -> rootNode
".." -> currentNode.parent ?: rootNode
else -> currentNode.children.first { child -> child.name == target }
}
}
it.startsWith("dir") -> {
val (_, name) = it.split(" ")
currentNode.children.add(Node(name = name, size = 0, parent = currentNode))
}
else -> {
val (size, _) = it.split(" ")
currentNode.size += size.toInt()
}
}
}
val unusedSpace = 70000000 - calculateDirectorySize(rootNode)
return directoryList(rootNode)
.filter { it.name != "/" }
.map { calculateDirectorySize(it) }
.filter { unusedSpace + it > 30000000 }
.min()
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println("Part One: ${part1(input)}")
check(part1(input) == 1243729)
println("Part Two: ${part2(input)}")
check(part2(input) == 4443914)
}
| 0 | Kotlin | 0 | 0 | 515f5681c385f22efab5c711dc983e24157fc84f | 3,458 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | fun main() {
fun part1(input: List<String>) = input
.partitionBy { it.isEmpty() }
.mapIndexed { index, (first, second) -> if (check(first, second)) index + 1 else 0 }
.sum()
fun part2(input: List<String>) = input
.filterTo(mutableListOf("[[2]]", "[[6]]")) { it.isNotEmpty() }
.sortedWith { x, y -> check(parse(x), parse(y), true).let { b -> if (b == null) 0 else if (b) -1 else 1 } }
.let { (it.indexOf("[[2]]") + 1) * (it.indexOf("[[6]]") + 1) }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input)) // 5625
println(part2(input)) // 23111
}
private fun check(first: String, second: String): Boolean = false != check(parse(first), parse(second), true)
private fun check(first: ListNode, second: ListNode, root: Boolean = false): Boolean? {
while (second.value.isNotEmpty()) {
val left = first.value.removeFirstOrNull() ?: return true
val right = second.value.removeFirst()
if (left is NumericNode && right is NumericNode) {
if (left.value < right.value) return true
if (right.value < left.value) return false
} else {
val b = check(left.asListNode(), right.asListNode())
if (b != null) return b
}
}
return if (first.value.isNotEmpty() || root) false else null
}
private fun parse(line: String): ListNode {
val root = ListNode()
var current: ListNode? = null
val sb = StringBuilder(line)
while (sb.isNotEmpty()) {
val c = sb.first()
var consumed = 1
when (c) {
'[' -> current = if (current == null) {
root
} else {
val next = ListNode(current)
current.value += next
next
}
']' -> current = current?.parent
',' -> Unit
else -> {
val num = sb.takeWhile { it.isDigit() }.toString()
consumed = num.length
val node = NumericNode(num.toInt())
current!!.value += node
}
}
sb.deleteRange(0, consumed)
}
return root
}
private fun Node<*>.asListNode(): ListNode = if (this is ListNode) this else ListNode().also { it.value += this }
private class ListNode(val parent: ListNode? = null) : Node<MutableList<Node<*>>>(mutableListOf())
private class NumericNode(value: Int) : Node<Int>(value)
private sealed class Node<T>(val value: T)
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 2,663 | advent-of-code-2022 | Apache License 2.0 |