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/aoc2022/day08/AoC08.kt
Saxintosh
576,065,000
false
{"Kotlin": 30013}
package aoc2022.day08 import readLines data class P(val x: Int, val y: Int) class Grid(private val lines: List<String>) { val xRange = lines[0].indices val yRange = lines.indices operator fun get(x: Int, y: Int) = lines[y][x] operator fun get(p: P) = lines[p.y][p.x] private fun Iterable<Int>.countUntil(predicate: (Int) -> Boolean): Int { var count = 0 for (element in this) { ++count if (predicate(element)) break } return count } fun findScore(p: P): Int { val treeHeight = get(p) val top = p.y - 1 downTo 0 val bottom = p.y + 1..yRange.last val left = p.x - 1 downTo 0 val right = p.x + 1..xRange.last val d1 = top.countUntil { get(p.x, it) >= treeHeight } val d2 = bottom.countUntil { get(p.x, it) >= treeHeight } val d3 = left.countUntil { get(it, p.y) >= treeHeight } val d4 = right.countUntil { get(it, p.y) >= treeHeight } return d1 * d2 * d3 * d4 } private fun checkRanges(r: IntRange, cut: Int, block: (Int) -> Boolean): Boolean { val r1 = 0 until cut val r2 = cut + 1 until r.last + 1 return (!r1.isEmpty() && r1.all(block)) || (!r2.isEmpty() && r2.all(block)) } fun isVisible(p: P): Boolean { if (p.x == 0 || p.y == 0 || p.x == xRange.last || p.y == yRange.last) return true val treeHeight = get(p) return checkRanges(xRange, p.x) { get(it, p.y) < treeHeight } || checkRanges(yRange, p.y) { get(p.x, it) < treeHeight } } } fun main() { fun part1(lines: List<String>): Int { val g = Grid(lines) var visibleTrees = 0 for (x in g.xRange) for (y in g.yRange) { val p = P(x, y) if (g.isVisible(p)) visibleTrees++ } return visibleTrees } fun part2(lines: List<String>): Int { val g = Grid(lines) var max = -1 for (x in g.xRange) { for (y in g.yRange) { val p = P(x, y) val d = g.findScore(p) max = max.coerceAtLeast(d) } } return max } readLines(21, 8, ::part1, ::part2) }
0
Kotlin
0
0
877d58367018372502f03dcc97a26a6f831fc8d8
1,927
aoc2022
Apache License 2.0
day11/src/main/kotlin/com/lillicoder/adventofcode2023/day11/Day11.kt
lillicoder
731,776,788
false
{"Kotlin": 98872}
package com.lillicoder.adventofcode2023.day11 import com.lillicoder.adventofcode2023.grids.Grid import com.lillicoder.adventofcode2023.grids.GridParser import com.lillicoder.adventofcode2023.grids.Node fun main() { val day11 = Day11() val grid = GridParser().parseFile("input.txt").first() println("The shortest path for all pairs of galaxies is ${day11.part1(grid)}. [factor=2]") println("The shortest path for all pairs of galaxies is ${day11.part2(grid)}. [factor=1,000,000]") } class Day11 { fun part1(grid: Grid<String>) = expandAndSum(grid, 2) fun part2(grid: Grid<String>) = expandAndSum(grid, 1_000_000) /** * Expands the given [Grid] by the given expansion factor, finds all galaxy pairs, and then sums * the distances. * @param grid Grid to expand. * @param factor Expansion factor. * @return Sum of galaxy pair distances after expansion. */ private fun expandAndSum( grid: Grid<String>, factor: Long, ): Long { val expanded = expand(grid, factor) val pairs = galaxyPairs(expanded) val shortestPaths = pairs.map { expanded.distance(it.first, it.second) } return shortestPaths.sum() } /** * Expands the given [Grid] based on the given cosmic expansion factor. * @param grid Grid to expand. * @param factor Expansion factor. * @return Expanded grid. */ private fun expand( grid: Grid<String>, factor: Long, ): Grid<String> { // Actually inserting values into the grid for huge factors will bust the heap, just update X, Y positions // as though those things really existed val emptyRows = mutableListOf<Long>() grid.forEachRowIndexed { index, row -> if (row.all { it.value == "." }) emptyRows.add(index.toLong()) } val emptyColumns = mutableListOf<Long>() grid.forEachColumnIndexed { index, column -> if (column.all { it.value == "." }) emptyColumns.add(index.toLong()) } return grid.map { node -> Node( node.x + emptyColumns.count { it < node.x } * (factor - 1), node.y + emptyRows.count { it < node.y } * (factor - 1), node.value, ) } } /** * Gets the unique pairs of galaxies in the given grid. * @param grid Grid to search. * @return Unique pairs of galaxies. */ private fun galaxyPairs(grid: Grid<String>): List<Pair<Node<String>, Node<String>>> { val galaxies = grid.filter { it == "#" } val ids = galaxies.associateWith { galaxies.indexOf(it) } return galaxies.flatMap { galaxy -> (galaxies - galaxy).map { if (ids[galaxy]!! > ids[it]!!) Pair(it, galaxy) else Pair(galaxy, it) } }.distinct() } }
0
Kotlin
0
0
390f804a3da7e9d2e5747ef29299a6ad42c8d877
2,875
advent-of-code-2023
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2022/day11/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2022.day11 import com.kingsleyadio.adventofcode.util.readInput fun main() { solution(loadMonkeys(), 20, true) solution(loadMonkeys(), 10_000, false) } fun solution(monkeys: List<Monkey>, rounds: Int, divisibleBy3: Boolean) { val monkeyOps = IntArray(monkeys.size) val limit = monkeys.fold(1) { acc, m -> acc * m.testDivisor } // needed for part 2 repeat(rounds) { for (index in monkeys.indices) { monkeys[index].inspect(divisibleBy3, limit) { receiver, item -> monkeys[receiver].receive(item) monkeyOps[index]++ } } } val monkeyBusiness = monkeyOps.sortedDescending().take(2).fold(1L) { acc, m -> acc * m } println(monkeyBusiness) } fun loadMonkeys(): List<Monkey> { val monkeys = mutableListOf<Monkey>() readInput(2022, 11).useLines { lineSequence -> val lines = lineSequence.iterator() while (lines.hasNext()) { lines.next() val startingItems = lines.next().substringAfterLast(": ").split(", ").map { it.toLong() } val op = lines.next().substringAfterLast("= ") val testDivisor = lines.next().substringAfterLast(" ").toInt() val trueMonkey = lines.next().substringAfterLast(" ").toInt() val falseMonkey = lines.next().substringAfterLast(" ").toInt() if (lines.hasNext()) lines.next() val newMonkey = Monkey(startingItems, op, testDivisor, trueMonkey, falseMonkey) monkeys.add(newMonkey) } } return monkeys } class Monkey( startingItems: List<Long>, opString: String, val testDivisor: Int, private val trueMonkey: Int, private val falseMonkey: Int, ) { private val itemsInHand = startingItems.toMutableList() private val inspector = { item: Long -> val op = opString.split(" ") val left = if (op[0] == "old") item else op[0].toLong() val right = if (op[2] == "old") item else op[2].toLong() when (op[1]) { "+" -> left + right "*" -> left * right else -> 0 } } fun receive(item: Long) = itemsInHand.add(item) fun inspect(divisibleBy3: Boolean, mod: Int, onThrow: (monkey: Int, item: Long) -> Unit) { itemsInHand.forEach { item -> val inspection = inspector(item) val worryLevel = if (divisibleBy3) inspection / 3 else inspection % mod if (worryLevel % testDivisor == 0L) onThrow(trueMonkey, worryLevel) else onThrow(falseMonkey, worryLevel) } itemsInHand.clear() } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
2,658
adventofcode
Apache License 2.0
kotlin/src/x2022/day8/day8.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package day8 import readInput enum class Direction { Up, Down, Right, Left } data class Tree(val height: Int, val views: Map<Direction, List<Int>>) { fun visible(): Boolean { return views.any { (_, v) -> v.isEmpty() || v.all { it < height } } } fun locationValue(): Int { return views.map { (k, v) -> val i = v.indexOfFirst { it >= height } val check = if (i == -1) v else v.subList(0, i + 1) check.count() }.reduce { acc, v -> acc * v } } } fun main() { fun parseInput(input: List<String>): List<Tree> { val matrix = input.map { it.chunked(1).map { it.toInt() } } val trees = mutableListOf<Tree>() for (x in 0 until matrix[0].count()) { for (y in 0 until matrix.count()) { val views = mutableMapOf<Direction, List<Int>>() for (direction in Direction.values()) { val view = mutableListOf<Int>() when (direction) { Direction.Left -> { for (i in y - 1 downTo 0) { view.add(matrix[x][i]) } views[Direction.Left] = view } Direction.Right -> { for (i in y + 1 until matrix.count()) { view.add(matrix[x][i]) } views[Direction.Right] = view } Direction.Down -> { for (i in x + 1 until matrix[0].count()) { view.add(matrix[i][y]) } views[Direction.Down] = view } Direction.Up -> { for (i in x - 1 downTo 0) { view.add(matrix[i][y]) } views[Direction.Up] = view } } } trees.add(Tree(matrix[x][y], views)) } } return trees } fun partOne(input: List<String>) { println( parseInput(input).sumOf { if (it.visible()) 1 else 0 as Int } ) } fun partTwo(input: List<String>) { println( parseInput(input).map { Pair(it.locationValue(), it) }.maxBy { it.first } ) } println("partOne test") partOne(readInput("day8.test")) println() println("partOne") partOne(readInput("day8")) println() println("partTwo test") partTwo(readInput("day8.test")) println() println("partTwo") partTwo(readInput("day8")) }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
2,920
adventOfCode
Apache License 2.0
src/Day11.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
private fun monkeys(): List<Monkey> { return readInput("Day11").filter { it.isNotBlank() }.map(String::trim).chunked(6).mapIndexed { i, s -> val items = s[1].substring("Starting items: ".length).split(", ").map(String::toLong).toMutableList() val ops = s[2].substring("Operation: new = old ".length).split(" ") val op = when (ops[0]) { "+" -> { x: Long -> x + if (ops[1] == "old") x else ops[1].toLong() } "*" -> { x: Long -> x * if (ops[1] == "old") x else ops[1].toLong() } else -> error("unknown operator") } val div = s[3].substring("Test: divisible by ".length).toInt() val t = s[4].substring("If true: throw to monkey ".length).toInt() val f = s[5].substring("If false: throw to monkey ".length).toInt() Monkey(i, items, op, div, t, f) } } private fun part1(monkeys: List<Monkey>): Long { val totalInspections = LongArray(monkeys.size) repeat(20) { for (m in monkeys) { for (i in m.items) { val newWorry = m.operation(i) / 3 monkeys[m.test(newWorry)].items.add(newWorry) } totalInspections[m.index] += m.items.size.toLong() m.items.clear() } } return totalInspections.sortedDescending().take(2).reduce(Long::times) } private fun part2(monkeys: List<Monkey>): Long { val divLCM = monkeys.map(Monkey::testDiv).lcm() val totalInspections = LongArray(monkeys.size) repeat(10000) { for (m in monkeys) { for (i in m.items) { val newWorry = m.operation(i) % divLCM monkeys[m.test(newWorry)].items.add(newWorry) } totalInspections[m.index] += m.items.size.toLong() m.items.clear() } } return totalInspections.sortedDescending().take(2).reduce(Long::times) } fun main() { println(part1(monkeys())) println(part2(monkeys())) } data class Monkey( val index: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val testDiv: Int, val testTrue: Int, val testFalse: Int ) { fun test(x: Long) = if (x % testDiv == 0L) testTrue else testFalse }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
2,223
advent-of-code-2022
Apache License 2.0
src/year_2023/day_07/Day07.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_07 import readInput enum class HandType(val strength: Int) { FiveOfAKind(6), FourOfAKind(5), FullHouse(4), ThreeOfAKind(3), TwoPair(2), OnePair(1), HighCard(0), ; companion object { fun fromString(text: String, jIsJoker: Boolean): HandType { val map = mutableMapOf<Char, Int>() text.forEach { char -> val curr = map[char] ?: 0 map[char] = curr + 1 } if (jIsJoker) { val jokerCount = map['J'] ?: 0 val maxMatches = map.toList().filterNot { it.first == 'J' }.maxByOrNull { it.second } if (maxMatches == null) { map['A'] = jokerCount } else { map[maxMatches.first] = maxMatches.second + jokerCount } map.remove('J') } val maxMatches = map.toList().maxByOrNull { it.second }!! return when(maxMatches.second) { 5 -> FiveOfAKind 4 -> FourOfAKind 3 -> { when (map.size) { 2 -> FullHouse else -> ThreeOfAKind } } 2 -> { when (map.size) { 3 -> TwoPair else -> OnePair } } else -> HighCard } } } } data class Hand( val type: HandType, val cards: String, val bid: Long, val jIsJoker: Boolean ): Comparable<Hand> { override fun compareTo(other: Hand): Int { if (type.strength > other.type.strength) { return 1 } else if (type.strength < other.type.strength) { return -1 } cards.forEachIndexed { index, myCard -> if (cardToInt(myCard) > cardToInt(other.cards[index])) { return 1 } else if (cardToInt(myCard) < cardToInt(other.cards[index])) { return -1 } } return 0 } // Solution 1 private fun cardToInt(char: Char): Int { return when (char) { '2'-> 2 '3' -> 3 '4' -> 4 '5' -> 5 '6' -> 6 '7' -> 7 '8' -> 8 '9' -> 9 'T' -> 10 'J' -> if (jIsJoker) 1 else 11 'Q' -> 12 'K' -> 13 'A' -> 14 else -> throw IllegalArgumentException("invalid card") } } } object Day07 { /** * */ fun solutionOne(text: List<String>): Long { val hands = text.map { parseHand(it, false) }.sorted() var sum = 0L hands.forEachIndexed { index, hand -> sum += (hand.bid * (index + 1)) } return sum } /** * */ fun solutionTwo(text: List<String>): Long { val hands = text.map { parseHand(it, true) }.sorted() var sum = 0L hands.forEachIndexed { index, hand -> sum += (hand.bid * (index + 1)) } return sum } private fun parseHand(text: String, jIsJoker: Boolean): Hand { val split = text.split(" ") return Hand( HandType.fromString(split[0], jIsJoker), split[0], split[1].toLong(), jIsJoker ) } } fun main() { val text = readInput("year_2023/day_07/Day07.txt") val solutionOne = Day07.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day07.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,735
advent_of_code
Apache License 2.0
src/main/kotlin/aoc2023/Day15.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput private data class Lense(val label: String, var focalLength: Int) private data class Box(val lenses: MutableList<Lense> = mutableListOf()) object Day15 { private fun hash(input: String): Int { var currentValue = 0 input.forEach { char -> currentValue += char.code currentValue *= 17 currentValue %= 256 } return currentValue } fun part1(input: List<String>) = input.first().split(",").sumOf { hash(it) } fun part2(input: List<String>): Int { val boxes = Array(256) { Box() } val regex = """(?<label>.*)(?<operation>[-=])(?<focalLength>\d?)""".toRegex() input.first().split(",").forEach { str -> val matchResult = regex.find(str) ?: throw IllegalArgumentException("Did not match: $str") val label = matchResult.groups["label"]!!.value val box = boxes[hash(label)] when (val operation = matchResult.groups["operation"]!!.value) { "-" -> box.lenses.removeIf { it.label == label } "=" -> { val focalLength = matchResult.groups["focalLength"]!!.value.toInt() val existingLense = box.lenses.firstOrNull { it.label == label } if (existingLense != null) { existingLense.focalLength = focalLength } else { box.lenses.add(Lense(label, focalLength)) } } else -> throw IllegalArgumentException("Unknown operation: $operation") } } return boxes.withIndex().sumOf { (boxIndex, box) -> box.lenses.withIndex().sumOf { (lenseIndex, lense) -> (boxIndex + 1) * (lenseIndex + 1) * lense.focalLength } } } } fun main() { val testInput = readInput("Day15_test", 2023) check(Day15.part1(testInput) == 1320) check(Day15.part2(testInput) == 145) val input = readInput("Day15", 2023) println(Day15.part1(input)) println(Day15.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
2,133
adventOfCode
Apache License 2.0
src/Day04.kt
krisbrud
573,455,086
false
{"Kotlin": 8417}
typealias Range = Pair<Int, Int> fun main() { fun parseLine(line: String): List<Range> { // Split on comma val ranges = line.split(",").map { val (first, second) = it.split("-").take(2) Range(first.toInt(), second.toInt()) } return ranges } fun contains(a: Range, b: Range): Boolean { return if (a.first < b.first) { a.second >= b.second } else if (a.first == b.first) { true } else { // b.first < a.first b.second >= a.second } } fun part1(input: List<String>): Int { val ranges = input.map { parseLine(it) } val isRangesOverlapping = ranges.map { val (a, b) = it.take(2) contains(a, b) } return isRangesOverlapping.count { it } } fun nonContainingOverlap(a: Range, b: Range): Boolean { return ((b.first <= a.first) && (a.first <= b.second)) } fun overlapAtAll(a: Range, b: Range): Boolean { return contains(a, b) || nonContainingOverlap(a, b) || nonContainingOverlap(b, a) } fun part2(input: List<String>): Int { val ranges = input.map { parseLine(it) } val isOverlappingAtAll = ranges.map { val (a, b) = it.take(2) overlapAtAll(a, b) } return isOverlappingAtAll.count { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) val input = readInput("Day04") println(part1(input)) check(part2(testInput) == 4) println(part2(input)) }
0
Kotlin
0
0
02caf3a30a292d7b8c9e2b7788df74650e54573c
1,674
advent-of-code-2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day04/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day04 import com.kingsleyadio.adventofcode.util.readInput fun solution(numbers: List<Int>, boards: MutableList<Board>, exitFirst: Boolean): Int { for (number in numbers) { val iterator = boards.iterator() for (board in iterator) { board.asSequence().flatten().filter { it.number == number }.forEach { it.isMarked = true } val (win, unmarkedSum) = checkWin(board) if (win) { iterator.remove() if (exitFirst || boards.isEmpty()) return number * unmarkedSum } } } return 0 } class Cell(val number: Int, var isMarked: Boolean) typealias Board = List<List<Cell>> fun main() { val (numbers, boards) = parseInput() println(solution(numbers, boards, exitFirst = true)) // Continue part 2 with the same boards println(solution(numbers, boards, exitFirst = false)) } fun parseInput(): Pair<List<Int>, MutableList<Board>> = readInput(2021, 4).useLines { lines -> val iterator = lines.iterator() val numbers = iterator.next().split(",").map { it.toInt() } val boards = mutableListOf<Board>() while (iterator.hasNext()) { iterator.next() val board = buildList { repeat(5) { val line = iterator.next().trim().split(" +".toRegex()).map { Cell(it.toInt(), false) } add(line) } } boards.add(board) } numbers to boards } fun checkWin(board: Board): Pair<Boolean, Int> { var win = false for (index in 0..4) { // Check rows and columns if (board[index].all { it.isMarked } || board.all { it[index].isMarked }) { win = true break } } return win to when { win -> board.asSequence().flatten().filterNot { it.isMarked }.sumOf { it.number } else -> 0 } }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,910
adventofcode
Apache License 2.0
src/main/kotlin/day17/Day17.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day17 import java.io.File import kotlin.math.absoluteValue import kotlin.math.min import kotlin.math.sqrt fun parseInput(line: String): Pair<IntRange, IntRange> { val rawXRange = line.split("x=")[1].split(",")[0] val rawYRange = line.split("y=")[1] val (minX, maxX) = rawXRange.split("..").map(String::toInt) val (minY, maxY) = rawYRange.split("..").map(String::toInt) return minX..maxX to minY..maxY } private fun Double.hasDecimals(): Boolean = this % 1.0 != 0.0 /* * Solving t^2 - (2*C + 1)*t + 2*Y = 0; where * - C is the vertical velocity * - Y is any of the valid positions in rangeY * * There's probably a better way, but I'm only OK-ish with Maths * * Returns a map time => all vertical velocities that will make it to the target area */ fun samplingInitialVy(rangeY: IntRange): Map<Int, List<Int>> { val minTheoreticalVelocityY = rangeY.minOf { it } // going straight from S0 to SX in one unit of time /* With the current formula, given an initial Vy, when time = 2*Vy + 1 the vertical space travelled is 0 - If the target is below the Y axis then in the next 'moment' Vy(t) will be greater than the greatest distance from the Y axis which will cause the probe to miss the area - If the target is above the Y axis then we are in the same case but one step before reaching the 0 sum. The limit in that case will be the greatest distance to the Y axis as any greater speed will be short and then miss the target */ val maxTheoreticalVelocity = rangeY.maxOf { it.absoluteValue } // the furthest distance from the Y axis var candidate = minTheoreticalVelocityY // starting with the min velocity possible val solutionsByTime = mutableListOf<Pair<Int, Int>>() do { val b = -((2 * candidate) + 1) val squaredB = 1.0 * b * b val solutions = mutableListOf<Int>() for (y in rangeY) { val ac4 = 4 * 2 * y if (ac4 > squaredB) continue val root = sqrt(squaredB - ac4) val localSolutions = listOf( (-b + root) / 2, (-b - root) / 2 ).filterNot { it < 0 || it.hasDecimals() }.map { it.toInt() } // t can only be a positive integer because: // [a] can't travel back in time // [b] the granularity of the problem is in units of time solutions.addAll(localSolutions) } solutionsByTime.addAll(solutions.associateWith { candidate }.toList()) candidate += 1; } while (candidate <= maxTheoreticalVelocity) return solutionsByTime.groupBy { it.first }.mapValues { (_, v) -> v.map { it.second } } } /* * Values for initial horizontal velocity Vx, aka Vx(0), are determined by the elapsed time, given that: * - Vx(t) = min(0, Vx(t-1) - 1) * - After time t, * Sx(t) = Vx(0) * min(Vx(0), t) - [1, min(Vx(0), t)) # IMPORTANT, the range is end exclusive * * Sx(t) is the distance traveled at the given initial velocity during time t. For the velocity to be * considered valid, Sx(t) must belong to rangeX */ private fun samplingInitialVxForGivenTime(time: Int, rangeX: IntRange): List<Int> { val candidates = (rangeX.first / time)..rangeX.last return candidates.filter { vx -> val sx = vx * min(vx, time) - (1 until min(vx, time)).sum() sx in rangeX } } fun findAllPossibleSolutions(rangeX: IntRange, rangeY: IntRange): List<Pair<Int, Int>> = samplingInitialVy(rangeY).flatMap { (time, vys) -> val solutionSpaceForX = samplingInitialVxForGivenTime(time, rangeX) solutionSpaceForX.flatMap { vx -> vys.map { vy -> vx to vy } } }.distinct() fun findMaxInitialVerticalVelocity(rangeY: IntRange) = samplingInitialVy(rangeY).mapValues { (_, vs) -> vs.maxOf { it } }.maxByOrNull { it.value }!! fun computeMaxHeight(time: Int, initialVerticalVelocity: Int): Int = (initialVerticalVelocity downTo 0).take(time).sum() fun main() { File("./input/day17.txt").useLines { lines -> val areaDefinition = lines.first() val (rangeX, rangeY) = parseInput(areaDefinition) val (time, maxInitialVerticalSpeed) = findMaxInitialVerticalVelocity(rangeY) println(computeMaxHeight(time, maxInitialVerticalSpeed)) println(findAllPossibleSolutions(rangeX, rangeY).size) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
4,160
advent-of-code-2021
MIT License
src/Day05.kt
bin-wang
572,801,360
false
{"Kotlin": 19395}
object Day05 { class State(val stacks: List<List<Char>>) { companion object { fun fromString(input: String): State { val lines = input.lines() // Get the number of stacks val n = lines .last() .split(" ") .last(String::isNotEmpty) .toInt() // parse each stack val stacks = (0 until n).map { i -> lines .dropLast(1) .map { it.padEnd(4 * n + 3).chunked(4)[i][1] } .takeLastWhile(Char::isLetter) } return State(stacks) } } fun move(step: Step, chunked: Boolean): State { val (i, from, to) = step val cratesToMove = stacks[from - 1].take(i).let { if (chunked) it else it.reversed() } val newStacks = stacks.mapIndexed { index, stack -> when (index) { from - 1 -> stack.drop(i) to - 1 -> cratesToMove + stack else -> stack } } return State(newStacks) } fun getTopCratesAsString(): String = stacks .mapNotNull { it.firstOrNull() } .joinToString(separator = "") } data class Step(val i: Int, val from: Int, val to: Int) } fun main() { fun parseSteps(steps: List<String>) = steps.map { val chunks = it.split(" ") val i = chunks[1].toInt() val from = chunks[3].toInt() val to = chunks[5].toInt() Day05.Step(i, from, to) } fun part1(input: String): String { val (initialStateStr, stepsStr) = input.split("\n\n") val steps = parseSteps(stepsStr.trim().lines()) return steps.fold(Day05.State.fromString(initialStateStr)) { state, step -> state.move(step, chunked = false) }.getTopCratesAsString() } fun part2(input: String): String { val (initialStateStr, stepsStr) = input.split("\n\n") val steps = parseSteps(stepsStr.trim().lines()) return steps.fold(Day05.State.fromString(initialStateStr)) { state, step -> state.move(step, chunked = true) }.getTopCratesAsString() } val testInput = readInputAsString("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInputAsString("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
dca2c4915594a4b4ca2791843b53b71fd068fe28
2,602
aoc22-kt
Apache License 2.0
src/Day07.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
private class Node7 private constructor(val name: String, val intrinsicSize: Int? = null, val parent: Node7? = null) : Iterable<Node7> { private val children: MutableList<Node7> = mutableListOf() val totalSize: Int get() = (intrinsicSize ?: 0) + children.sumOf { it.totalSize } operator fun get(childName: String) = children.first { it.name == childName } fun addChild(node: Node7) = children.add(node) val isDirectory get() = intrinsicSize == null override fun iterator(): Iterator<Node7> = iterator { yield(this@Node7); children.forEach { yieldAll(it.iterator()) } } override fun toString(): String = "$name " + if (isDirectory) "(dir)" else "(file, size=$intrinsicSize)" companion object { fun file(name: String, size: Int, parent: Node7) = Node7(name, size, parent) fun directory(name: String, parent: Node7) = Node7(name, parent = parent) fun root() = Node7("/") } } private fun parse(input: List<String>): Node7 { val cd = Regex("\\$ cd (.*)") val dir = Regex("dir (.*)") val file = Regex("(\\d+) (.*)") val root = Node7.root() var current = root fun onDirectoryDiscovered(name: String) = current.addChild(Node7.directory(name, current)) fun onFileDiscovered(name: String, size: Int) = current.addChild(Node7.file(name, size, current)) fun onDirectoryChanged(name: String) { current = when (name) { "/" -> root; ".." -> current.parent!!; else -> current[name] } } fun Regex.onMatch(line: String, block: (List<String>) -> Unit) = find(line)?.let { block(it.groupValues) } input.forEach { line -> dir.onMatch(line) { onDirectoryDiscovered(it[1]) } file.onMatch(line) { onFileDiscovered(it[2], it[1].toInt()) } cd.onMatch(line) { onDirectoryChanged(it[1]) } } return root } fun main() { fun part1(input: List<String>): Int = parse(input) .filter { it.isDirectory && it.totalSize <= 100_000 } .sumOf { it.totalSize } fun part2(input: List<String>): Int = with(parse(input)) { val minimumToDelete = 30_000_000 - (70_000_000 - totalSize) return filter { it.isDirectory }.sortedBy { it.totalSize }.first { it.totalSize >= minimumToDelete }.totalSize } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24_933_642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
2,484
advent-of-code-in-kotlin-2022
Apache License 2.0
src/Day09.kt
Excape
572,551,865
false
{"Kotlin": 36421}
import kotlin.math.abs import kotlin.math.sign fun main() { data class Point(val x: Int, val y: Int) { fun move(move: Pair<Int, Int>) = Point(x + move.first, y + move.second) fun follow(other: Point): Point { if (this == other) { return this } var dx = 0 var dy = 0 if (abs(this.x - other.x) > 1 || abs(this.y - other.y) > 1) { dx = (other.x - this.x).sign dy = (other.y - this.y).sign } return Point(x + dx, y + dy) } } data class Instruction(val direction: Pair<Int, Int>, val times: Int) { } val moves = mapOf('U' to Pair(0, 1), 'D' to Pair(0, -1), 'R' to Pair(1, 0), 'L' to Pair(-1, 0)) fun parseInstructions(input: List<String>) = input.map { it.split(" ") }.map { Instruction(moves[it[0][0]]!!, it[1].toInt()) } fun part1(input: List<String>): Int { val instructions = parseInstructions(input) var head = Point(0, 0) var tail = Point(0, 0) val visited = mutableSetOf(tail) for (instr in instructions) { repeat(instr.times) { head = head.move(instr.direction) tail = tail.follow(head) visited.add(tail) } } return visited.size } fun part2(input: List<String>): Int { val instructions = parseInstructions(input) val knots = generateSequence { Point(0, 0) }.take(10).toMutableList() val visited = mutableSetOf(Point(0, 0)) instructions.forEach { instr -> repeat(instr.times) { knots.indices.forEach() { i -> if (i == 0) { knots[0] = knots[0].move(instr.direction) } else { knots[i] = knots[i].follow(knots[i - 1]) } } visited.add(knots.last()) } } return visited.size } val testInput = readInput("Day09_test") println(part1(testInput)) check(part1(testInput) == 88) check(part2(testInput) == 36) val input = readInput("Day09") val part1Answer = part1(input) val part2Answer = part2(input) println("part 1: $part1Answer") println("part 2: $part2Answer") }
0
Kotlin
0
0
a9d7fa1e463306ad9ea211f9c037c6637c168e2f
2,367
advent-of-code-2022
Apache License 2.0
archive/2022/Day12.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import java.util.* private const val EXPECTED_1 = 31 private const val EXPECTED_2 = 29 private const val MAX = 100000 private val DIRS = listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1) /** * Day12 implementation using Dijkstra's */ private class Day12(isTest: Boolean) : Solver(isTest) { var start = 0 to 0 var end = 0 to 0 var X = 0 var Y = 0 lateinit var best: List<MutableList<Int>> val heights: List<List<Int>> = readAsLines().withIndex().map { (y, row) -> row.withIndex().map { (x, value) -> when (value) { 'S' -> { start = y to x 0 } 'E' -> { end = y to x 26 } else -> value - 'a' } } } init { Y = heights.size X = heights[0].size } fun dijkstra(start: Pair<Int, Int>, reverse: Boolean) { val queue = TreeSet<Pair<Int, Int>>(compareBy( { best[it.first][it.second] }, { it.first }, { it.second } ) ) best[start.first][start.second] = 0 queue.add(start) while (!queue.isEmpty()) { val pos = queue.pollFirst()!! for (dir in DIRS) { val n = (pos.first + dir.first) to (pos.second + dir.second) if (n.first in 0 until Y && n.second in 0 until X) { if ((if (reverse) -1 else 1) * (heights[n.first][n.second] - heights[pos.first][pos.second]) <= 1) { if (best[n.first][n.second] > best[pos.first][pos.second] + 1) { queue.remove(n) best[n.first][n.second] = best[pos.first][pos.second] + 1 queue.add(n) } } } } } } fun part1(): Any { best = (0 until Y).map { (0 until X).map { MAX }.toMutableList() } dijkstra(start, false) return best[end.first][end.second] } fun part2(): Any { best = (0 until Y).map { (0 until X).map { MAX }.toMutableList() } dijkstra(end, true) return (0 until Y).minOf { y -> (0 until X).minOf { x -> if (heights[y][x] == 0) best[y][x] else MAX } } } } fun main() { val testInstance = Day12(true) val instance = Day12(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,860
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day22.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* import kotlin.math.max import kotlin.math.min fun main() { val input = Input.day(22) println(day22A(input)) println(day22B(input)) } fun day22A(input: Input): Int { val bricks = input.lines.map(Brick::init) bricks.fall() return bricks.count { brick -> bricks.none { b -> b.canFall(bricks.filter { it != b && it != brick }) } } } fun day22B(input: Input): Int { val bricks = input.lines.map(Brick::init) bricks.fall() return bricks.sumOf { brick -> val withoutBrick = bricks .filter { it != brick } .map { Brick(it.x, it.y, it.currentZ) } withoutBrick.fall() withoutBrick.count { it.hasFallen() } } } private class Brick(val x: Range, val y: Range, val z: Range) { var currentZ = z fun canFall(others: List<Brick>): Boolean { val lowerZ = Range(currentZ.first - 1, currentZ.last - 1) if(lowerZ.contains(0)) return false return others.none { x.intersect(it.x) && y.intersect(it.y) && lowerZ.intersect(it.currentZ) } } fun fall() { currentZ = Range(currentZ.first - 1, currentZ.last - 1) } fun hasFallen() = z != currentZ companion object { fun init(line: String): Brick { val ints = line.toInts() return Brick( Range(ints[0], ints[3]), Range(ints[1], ints[4]), Range(ints[2], ints[5]), ) } } } private fun List<Brick>.fall() { while (any { b -> b.canFall(filter { it != b }) }) { forEach { b -> if(b.canFall(filter { it != b })) { b.fall() } } } } private data class Range(private val a: Int, private val b: Int) { val first = min(a, b) val last = max(a, b) fun contains(value: Int): Boolean { return first <= value && value <= last } fun intersect(other: Range): Boolean { return contains(other.first) || contains(other.last) || other.contains(first) || other.contains(last) } }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,093
AdventOfCode2023
MIT License
src/day10/Day10.kt
spyroid
433,555,350
false
null
package day10 import readInput import kotlin.math.absoluteValue import kotlin.system.measureTimeMillis fun main() { val pairs = mapOf('}' to '{', '>' to '<', ')' to '(', ']' to '[') val scores = mapOf('}' to 1197L, '>' to 25137L, ')' to 3L, ']' to 57L) val scores2 = mapOf('{' to 3L, '<' to 4L, '(' to 1L, '[' to 2L) fun validate(line: String): Long { val stack = ArrayDeque<Char>() for (c in line) { if (pairs.containsValue(c)) stack.addFirst(c) else { if (pairs[c] == stack.first()) stack.removeFirst() else return -scores[c]!! } } return stack.map { scores2[it]!! }.fold(0) { acc, i -> acc * 5 + i } } fun part1(input: List<String>) = input.map { validate(it) }.filter { it < 0 }.sumOf { it }.absoluteValue fun part2(input: List<String>) = input.map { validate(it) }.filter { it > 0 }.sorted().let { it[it.size / 2] } fun parts12(input: List<String>) = input .map { validate(it) } .groupBy { it < 0 } .let { g -> Pair(g[true]!!.sumOf { it }.absoluteValue, g[false]!!.sorted().let { list -> list[list.size / 2] }) } val testData = readInput("day10/test") val inputData = readInput("day10/input") var res1 = part1(testData) check(res1 == 26397L) { "Expected 26397 but got $res1" } var time = measureTimeMillis { res1 = part1(inputData) } println("Part1: $res1 in $time ms") res1 = part2(testData) check(res1 == 288957L) { "Expected 288957 but got $res1" } time = measureTimeMillis { res1 = part2(inputData) } println("Part2: $res1 in $time ms") var res2: Pair<Long, Long> time = measureTimeMillis { res2 = parts12(inputData) } println("Parts 1&2: Corrupted ${res2.first}, Incompleted ${res2.second} in $time ms") }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
1,812
Advent-of-Code-2021
Apache License 2.0
src/Day14.kt
palex65
572,937,600
false
{"Kotlin": 68582}
private data class Point(val x: Int, val y: Int) private enum class Material(val symbol: Char){ ROCK('#'), SAND('o'), PATH('~') } private fun Scan(lines: List<String>): MutableMap<Point,Material> { val res = mutableMapOf<Point,Material>() lines.forEach { path -> var start: Point? = null path.split(" -> ").map{ it.split(',') }.forEach { (a,b) -> val p = Point(a.toInt(),b.toInt()) val s = start start = p if (s==null) res.put(p,Material.ROCK) else when { p.x==s.x && s.y<p.y -> for(y in s.y .. p.y ) res.put(Point(p.x,y),Material.ROCK) p.x==s.x && s.y>p.y -> for(y in p.y .. s.y ) res.put(Point(p.x,y),Material.ROCK) p.y==s.y && s.x<p.x -> for(x in s.x .. p.x ) res.put(Point(x,p.y),Material.ROCK) p.y==s.y && s.x>p.x -> for(x in p.x .. s.x ) res.put(Point(x,p.y),Material.ROCK) } } } return res } private fun printScan(s: Map<Point,Material>) { val orig = Point( s.keys.minOf{ it.x }, s.keys.minOf{ it.y }) val max = Point( s.keys.maxOf{ it.x }, s.keys.maxOf{ it.y }) println("Orig=$orig Max=$max") for (y in orig.y .. max.y) { for(x in orig.x .. max.x) print( s[Point(x,y)]?.symbol ?: '.' ) println() } } private val Point.drops get() = listOf( Point(x,y+1), Point(x-1,y+1), Point(x+1,y+1) ) private fun dropSand(from: Point, scan: MutableMap<Point,Material>): Point? { var p = from val maxY = scan.keys.maxOf { it.y } while(p.y <= maxY) { val drop = p.drops.firstOrNull { val material = scan[it] material==null || material==Material.PATH } if (drop==null) { scan[p] = Material.SAND return p } else { scan[p]=Material.PATH p = drop } } return null } private val sourceSand = Point(500,0) private fun part1(lines: List<String>): Int { val scan = Scan(lines) do { val stop = dropSand(sourceSand,scan) } while( stop!=null ) return scan.values.count { it == Material.SAND } } private fun part2(lines: List<String>): Int { val scan = Scan(lines) val floorY = scan.keys.maxOf { it.y } + 2 do { val stop = dropSand(sourceSand,scan) if (stop==null) { val pathStopX = scan.filter{ it.value==Material.PATH }.maxBy{ it.key.y }.key.x scan[Point(pathStopX,floorY)] = Material.ROCK } } while( stop!=sourceSand ) return scan.values.count { it == Material.SAND } } fun main() { val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) // 757 println(part2(input)) // 24943 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
2,831
aoc2022
Apache License 2.0
src/Day03.kt
mzlnk
573,124,510
false
{"Kotlin": 14876}
fun main() { fun part1(input: List<String>): Int { val letterToPriority: (Char) -> Int = { letter -> (if (letter in 'a'..'z') (letter.code - 97) else (letter.code - 39)) + 1 } var sum = 0 for ((index: Int, line: String) in input.withIndex()) { val pack1 = HashSet<Char>() for (i in 0 until line.length / 2) { pack1.add(line[i]) } for (i in (line.length / 2) until line.length) { if (pack1.contains(line[i])) { sum += letterToPriority(line[i]) break; } } } return sum } fun part2(input: List<String>): Int { val letterToPriority: (Char) -> Int = { letter -> (if (letter in 'a'..'z') (letter.code - 97) else (letter.code - 39)) + 1 } var sum = 0 for (i in 0..(input.size - 3) step 3) { val itemTypes = HashMap<Char, Int>() for (j in 0..2) { val computedLetters = HashSet<Char>() input[i + j].toCharArray().forEach { itemTypes.compute(it) { k, v -> if (!computedLetters.contains(k)) { computedLetters.add(k) ((v ?: 0) + 1) } else v } } } val commonLetter = itemTypes.filterValues { it == 3 }.toList().find { it.second == 3 }?.first!! println("Pair ${i / 3}: $commonLetter") sum += letterToPriority(commonLetter) } return 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)) }
0
Kotlin
0
0
3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5
1,943
advent-of-code-2022
Apache License 2.0
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day7.kt
rocky-jaiswal
726,062,069
false
{"Kotlin": 41834, "Ruby": 2966, "TypeScript": 2848, "JavaScript": 830, "Shell": 455, "Dockerfile": 387}
package dev.rockyj.advent_kt private val cardRanking = "A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, 2".split(",") .map { it.trim() } .filter { it != "" } .reversed() private val cardRanking2 = "A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, J".split(",") .map { it.trim() } .filter { it != "" } .reversed() private data class Hand(val cards: List<String>, val cloned: List<String>, val bid: Long, val index: Int) private fun comp(h1: Hand, h2: Hand): Int { val h1c = h1.cards.map { cardRanking2.indexOf(it) } val h2c = h2.cards.map { cardRanking2.indexOf(it) } var big = 0 h1c.forEachIndexed lit@{ index, _rank -> if (big == 0) { if ((h1c.get(index) == h2c.get(index))) { return@lit } if (h1c.get(index) > h2c.get(index)) { big = 1 } if (h1c.get(index) < h2c.get(index)) { big = -1 } } } return big } private fun part2(input: List<String>) { val handsM = mutableListOf<Hand>() input.forEachIndexed { idx, it -> val parts = it.trim().split(Regex("\\s+")) val cards = parts.first().split("").filter { it != "" } val bid = parts.last() val groupsWithoutJoker = cards.filter { it != "J" }.groupBy { it } val cloned = if (groupsWithoutJoker.isNotEmpty()) { val biggestGroupWithoutJoker = groupsWithoutJoker.keys.sortedBy { groupsWithoutJoker[it]!!.size }.last() cards.map { if (it == "J" || it == biggestGroupWithoutJoker) "X" else it } } else { cards } handsM.add(Hand(cards, cloned, bid.toLong(), idx)) } val hands = handsM.toList() // 5 of a kind val fiveOfAKind = hands.filter { hand -> val cards = hand.cards val groupsWithoutJoker = cards.filter { it != "J" }.groupBy { it } cards.distinct().size == 1 || groupsWithoutJoker.size == 1 }.sortedWith { h1, h2 -> comp(h1, h2) } // 4 of a kind val fourOfAKind = hands.filter { !fiveOfAKind.map { ex -> ex.index }.contains(it.index) }.filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } val clonedGroup = hand.cloned.groupBy { it } (cards.distinct().size == 2 && groups.keys.map { groups[it]!!.size }.sorted() == listOf( 1, 4 )) || clonedGroup.keys.map { clonedGroup[it]!!.size }.sorted() == listOf(1, 4) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // full house val fullHouse = hands.filter { !fiveOfAKind.plus(fourOfAKind).map { ex -> ex.index }.contains(it.index) }.filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } val clonedGroup = hand.cloned.groupBy { it } (groups.size == 2 && groups.keys.map { groups[it]!!.size }.sorted() == listOf( 2, 3 )) || clonedGroup.keys.map { clonedGroup[it]!!.size }.sorted() == listOf(2, 3) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 3 of a kind val threeOfAKind = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).map { ex -> ex.index }.contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } val clonedGroup = hand.cloned.groupBy { it } (groups.keys.map { groups[it]!!.size }.sorted() == listOf( 1, 1, 3 )) || clonedGroup.keys.map { clonedGroup[it]!!.size }.sorted() == listOf(1, 1, 3) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 2 pair val twoPair = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).map { ex -> ex.index }.contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } val clonedGroup = hand.cloned.groupBy { it } (cards.distinct().size == 3 && groups.keys.filter { k -> groups[k]!!.size == 2 }.size == 2) || clonedGroup.keys.map { clonedGroup[it]!!.size }.sorted() == listOf(1, 2, 2) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 1 pair val onePair = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).plus(twoPair).map { ex -> ex.index } .contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } val clonedGroup = hand.cloned.groupBy { it } (cards.distinct().size == 4 && groups.keys.filter { k -> groups[k]!!.size == 2 }.size == 1) || clonedGroup.keys.map { clonedGroup[it]!!.size }.sorted() == listOf(1, 1, 1, 2) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // high card val highCard = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).plus(twoPair).plus(onePair) .map { ex -> ex.index } .contains(it.index) } .filter { hand -> hand.cards.distinct().size == 5 }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) val score = highCard .plus(onePair) .plus(twoPair) .plus(threeOfAKind) .plus(fullHouse) .plus(fourOfAKind) .plus(fiveOfAKind) .mapIndexed { index, hand -> //println(hand.bid) (index + 1) * hand.bid }.sum() println(score) } private fun part1(input: List<String>) { val handsM = mutableListOf<Hand>() input.forEachIndexed { idx, it -> val parts = it.trim().split(Regex("\\s+")) val cards = parts.first().split("").filter { it != "" } val bid = parts.last() handsM.add(Hand(cards, cards, bid.toLong(), idx)) } val hands = handsM.toList() // 5 of a kind val fiveOfAKind = hands.filter { hand -> hand.cards.distinct().size == 1 }.sortedWith { h1, h2 -> comp(h1, h2) } // 4 of a kind val fourOfAKind = hands.filter { !fiveOfAKind.map { ex -> ex.index }.contains(it.index) }.filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } cards.distinct().size == 2 && groups.keys.map { groups[it]!!.size }.sorted() == listOf(1, 4) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // full house val fullHouse = hands.filter { !fiveOfAKind.plus(fourOfAKind).map { ex -> ex.index }.contains(it.index) }.filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } groups.size == 2 && groups.keys.map { groups[it]!!.size }.sorted() == listOf(2, 3) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 3 of a kind val threeOfAKind = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).map { ex -> ex.index }.contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } groups.keys.map { groups[it]!!.size }.sorted() == listOf(1, 1, 3) }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 2 pair val twoPair = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).map { ex -> ex.index }.contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } cards.distinct().size == 3 && groups.keys.filter { k -> groups[k]!!.size == 2 }.size == 2 }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // 1 pair val onePair = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).plus(twoPair).map { ex -> ex.index } .contains(it.index) } .filter { hand -> val cards = hand.cards val groups = cards.groupBy { it } cards.distinct().size == 4 && groups.keys.filter { k -> groups[k]!!.size == 2 }.size == 1 }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) // high card val highCard = hands.filter { !fiveOfAKind.plus(fourOfAKind).plus(fullHouse).plus(threeOfAKind).plus(twoPair).plus(onePair) .map { ex -> ex.index } .contains(it.index) } .filter { hand -> hand.cards.distinct().size == 5 }.sortedWith(Comparator<Hand> { h1, h2 -> comp(h1, h2) }) val score = highCard .plus(onePair) .plus(twoPair) .plus(threeOfAKind) .plus(fullHouse) .plus(fourOfAKind) .plus(fiveOfAKind) .mapIndexed { index, hand -> //println(hand.bid) (index + 1) * hand.bid }.sum() println(score) } fun main() { val lines = fileToArr("day7_2.txt") // part1(lines) TODO: change card ranking part2(lines) }
0
Kotlin
0
0
a7bc1dfad8fb784868150d7cf32f35f606a8dafe
9,454
advent-2023
MIT License
src/Day03.kt
Kbzinho-66
572,299,619
false
{"Kotlin": 34500}
fun main() { operator fun String.component1() = this.subSequence(0, this.length / 2).toSet() operator fun String.component2() = this.subSequence(this.length / 2, this.length).toSet() fun priority(char: Char): Int { return when (char) { in 'a'..'z' -> char - 'a' + 1 in 'A'..'Z' -> 26 + (char - 'A' + 1) else -> 0 } } fun part1(input: List<String>): Int { // Decompor a string nos seus dois compartimentos return input.map { (comp1, comp2) -> // Encontrar itens comuns aos dois comp1 intersect comp2 }.flatten().sumOf { priority(it) } // E somar a prioridade de todos } fun part2(input: List<String>): Int { // Pegar grupos de 3 mochilas return input.chunked(3) .map { group -> // O zipWithNext vai comparar o primeiro com o segundo e o segundo com o terceiro group.zipWithNext() // Separar nos dois compartimentos .map { (first, second) -> // Daqui vão sair os elementos comuns aos dois first.toSet() intersect second.toSet() } }.flatMap { shared -> // Como foi usado um grupo de 3, vai ter n-1 conjuntos de elementos comuns shared[0] intersect shared[1] }.sumOf { priority(it) } } // Testar os casos básicos val testInput = readInput("../inputs/Day03_test") sanityCheck(part1(testInput), 157) sanityCheck(part2(testInput), 70) val input = readInput("../inputs/Day03") println("Parte 1 = ${part1(input)}") println("Parte 2 = ${part2(input)}") }
0
Kotlin
0
0
e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b
1,737
advent_of_code_2022_kotlin
Apache License 2.0
day19/part2.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Part Two --- // Even with your help, the sorting process still isn't fast enough. // // One of the Elves comes up with a new plan: rather than sort parts // individually through all of these workflows, maybe you can figure out in // advance which combinations of ratings will be accepted or rejected. // // Each of the four ratings (x, m, a, s) can have an integer value ranging from // a minimum of 1 to a maximum of 4000. Of all possible distinct combinations // of ratings, your job is to figure out which ones will be accepted. // // In the above example, there are 167409079868000 distinct combinations of // ratings that will be accepted. // // Consider only your list of workflows; the list of part ratings that the // Elves wanted you to sort is no longer relevant. How many distinct // combinations of ratings will be accepted by the Elves' workflows? import java.io.* import kotlin.math.max import kotlin.math.min fun IntRange.size() = (this.endInclusive - this.start + 1).toLong() // Returns two ranges: the first is the result of applying the op + operand to // the range, and the second is the remaining part of the range. fun IntRange.splitOn(op: Char, operand: Int): Pair<IntRange, IntRange> { return when (op) { '<' -> min(this.start, operand - 1)..min(this.endInclusive, operand - 1) to max(this.start, operand)..max(this.endInclusive, operand) '>' -> max(this.start, operand + 1)..max(this.endInclusive, operand + 1) to min(this.start, operand)..min(this.endInclusive, operand) else -> throw Exception("Unknown op $op") } } interface Rule { val to: String } data class ConditionalRule(val op: Char, val operand1: Char, val operand2: Int, override val to: String) : Rule data class UnconditionalRule(override val to: String) : Rule val RULE_LINE_RGX = Regex("(?<name>\\w+)\\{(?<rules>.*)\\}") val CONDITIONAL_RULE_RGX = Regex("(?<operand1>[xmas])(?<op>[<>])(?<operand2>\\d+):(?<to>\\w+)") val lines = File("input.txt").readLines() val blankLineIdx = lines.indexOfFirst { it.isBlank() } val rules = lines.take(blankLineIdx).associate { val ruleLine = RULE_LINE_RGX.matchEntire(it)!! ruleLine.groups["name"]!!.value to ruleLine.groups["rules"]!!.value.split(',').map { val conditional = CONDITIONAL_RULE_RGX.matchEntire(it) if (conditional != null) { ConditionalRule( conditional.groups["op"]!!.value[0], conditional.groups["operand1"]!!.value[0], conditional.groups["operand2"]!!.value.toInt(), conditional.groups["to"]!!.value ) } else { UnconditionalRule(it) } } } fun countAcceptable(to: String, x: IntRange, m: IntRange, a: IntRange, s: IntRange): Long { if (to == "A") { return x.size() * m.size() * a.size() * s.size() } else if (to == "R") { return 0L } else { return countAcceptable(rules[to]!!, x, m, a, s) } } fun countAcceptable(remainingRules: List<Rule>, x: IntRange, m: IntRange, a: IntRange, s: IntRange): Long { if (remainingRules.size == 0) { return 0 } val thisRule = remainingRules[0] if (thisRule !is ConditionalRule) { return countAcceptable(remainingRules[0].to, x, m, a, s) } return when (thisRule.operand1) { 'x' -> { val (x1, x2) = x.splitOn(thisRule.op, thisRule.operand2) val runRule = if (x1.size() == 0L) 0L else countAcceptable(thisRule.to, x1, m, a, s) val nextRules = if (x2.size() == 0L) 0L else countAcceptable(remainingRules.subList(1, remainingRules.size), x2, m, a, s) runRule + nextRules } 'm' -> { val (m1, m2) = m.splitOn(thisRule.op, thisRule.operand2) val runRule = if (m1.size() == 0L) 0L else countAcceptable(thisRule.to, x, m1, a, s) val nextRules = if (m2.size() == 0L) 0L else countAcceptable(remainingRules.subList(1, remainingRules.size), x, m2, a, s) runRule + nextRules } 'a' -> { val (a1, a2) = a.splitOn(thisRule.op, thisRule.operand2) val runRule = if (a1.size() == 0L) 0L else countAcceptable(thisRule.to, x, m, a1, s) val nextRules = if (a2.size() == 0L) 0L else countAcceptable(remainingRules.subList(1, remainingRules.size), x, m, a2, s) runRule + nextRules } 's' -> { val (s1, s2) = s.splitOn(thisRule.op, thisRule.operand2) val runRule = if (s1.size() == 0L) 0L else countAcceptable(thisRule.to, x, m, a, s1) val nextRules = if (s2.size() == 0L) 0L else countAcceptable(remainingRules.subList(1, remainingRules.size), x, m, a, s2) runRule + nextRules } else -> throw Exception("Unknown operand ${thisRule.operand1}") } } println(countAcceptable(rules["in"]!!, 1..4000, 1..4000, 1..4000, 1..4000))
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
4,656
adventofcode2023
MIT License
src/main/kotlin/adventofcode/year2020/Day20JurassicJigsaw.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 227}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput import adventofcode.common.product class Day20JurassicJigsaw(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val tiles by lazy { input.split("\n\n").map(::Tile) } override fun partOne(): Long { val tileMap = generateSequence(mapOf(Pair(0, 0) to tiles.first())) { previous -> previous + previous.keys.flatMap { tile -> val left = tiles .filter { previous.values.none { previousTile -> it.id == previousTile.id } } .firstNotNullOfOrNull { newTile -> val left = previous[tile]!!.left newTile.variations().firstOrNull { it.right == left }?.let { Pair(tile.first - 1, tile.second) to it } } val right = tiles .filter { previous.values.none { previousTile -> it.id == previousTile.id } } .firstNotNullOfOrNull { newTile -> val right = previous[tile]!!.right newTile.variations().firstOrNull { it.left == right }?.let { Pair(tile.first + 1, tile.second) to it } } val bottom = tiles .filter { previous.values.none { previousTile -> it.id == previousTile.id } } .firstNotNullOfOrNull { newTile -> val bottom = previous[tile]!!.bottom newTile.variations().firstOrNull { it.top == bottom }?.let { Pair(tile.first, tile.second - 1) to it } } val top = tiles .filter { previous.values.none { previousTile -> it.id == previousTile.id } } .firstNotNullOfOrNull { newTile -> val top = previous[tile]!!.top newTile.variations().firstOrNull { it.bottom == top }?.let { Pair(tile.first, tile.second + 1) to it } } listOfNotNull(left, right, bottom, top) }.toMap() } .first { it.size == tiles.size } return listOf( tileMap.entries.sortedBy { it.key.first }.minByOrNull { it.key.second }!!, tileMap.entries.sortedBy { it.key.first }.maxByOrNull { it.key.second }!!, tileMap.entries.sortedByDescending { it.key.first }.minByOrNull { it.key.second }!!, tileMap.entries.sortedByDescending { it.key.first }.maxByOrNull { it.key.second }!! ) .map { it.value.id } .product() } companion object { private data class Tile( val id: Long, val content: List<String> ) { constructor(tile: String) : this(tile.lines().first().split(" ").last().replace(":", "").toLong(), tile.lines().drop(1)) val left = col(0) val top = row(0) val right = col(content.first().length - 1) val bottom = row(content.size - 1) private fun col(n: Int) = content.fold("") { col, row -> col + row[n] } private fun row(n: Int) = content[n] // Rotate content 90 degrees clockwise private fun rotate() = copy(content = List(content.size) { n -> col(n).reversed() }) private fun flipX() = copy(content = content.map(String::reversed)) private fun flipY() = copy(content = content.reversed()) fun variations() = listOf(this, flipX(), flipY()).flatMap { listOf(it, it.rotate(), it.rotate().rotate(), it.rotate().rotate().rotate()) } } } }
0
Kotlin
0
0
72492c6a7d0c939b2388e13ffdcbf12b5a1cb838
3,678
AdventOfCode
MIT License
src/main/kotlin/aoc2023/Day12.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import readInput private class SpringRow(private val springs: String, damagedGroups: IntArray) { companion object { fun fromString(input: String): SpringRow { val split = input.split(" ") return SpringRow(split[0], split[1].split(",").map { it.toInt() }.toIntArray()) } fun fromPart2String(input: String): SpringRow { val split = input.split(" ") val springs = (split[0] + "?").repeat(5).dropLast(1) val damagedGroups = (split[1] + ",").repeat(5).dropLast(1).split(",").map { it.toInt() }.toIntArray() return SpringRow(springs, damagedGroups) } } // Part 1 val arrangements by lazy { findPossibleArrangements(springs) } private val regex = damagedGroups.map { length -> "(#|\\?)".repeat(length) } .joinToString(separator = "(\\.|\\?)+", prefix = "(\\.|\\?)*", postfix = "(\\.|\\?)*") { it }.toRegex() private fun findPossibleArrangements(input: String): List<String> { if (!input.matches(regex)) return emptyList() if (!input.contains('?')) return listOf(input) val test1 = input.replaceFirst('?', '.') val test2 = input.replaceFirst('?', '#') return findPossibleArrangements(test1) + findPossibleArrangements(test2) } // Part 2 val arrangementsPart2 by lazy { var currentBlock = 1 var regex = damagedGroups.take(currentBlock).map { length -> "(#|\\?)".repeat(length) } .joinToString(separator = "(\\.|\\?)+", prefix = "(\\.|\\?)*", postfix = "(\\.|\\?)*") { it }.toRegex() for (currentPosition in springs.indices) { val matches = getNumberOfMatches(springs.take(currentPosition), currentBlock, regex) if (matches > 0) { currentBlock++ regex = damagedGroups.take(currentBlock).map { length -> "(#|\\?)".repeat(length) } .joinToString(separator = "(\\.|\\?)+", prefix = "(\\.|\\?)*", postfix = "(\\.|\\?)*") { it } .toRegex() } } getNumberOfMatches(springs, damagedGroups.size, regex) } private val cache = mutableMapOf<Pair<String, Int>, Long>() private fun getNumberOfMatches(input: String, groupsToMatch: Int, regex: Regex): Long { val shrinked = input.replace("\\.+".toRegex(), ".") if (!shrinked.matches(regex)) return 0 if (!shrinked.contains('?')) return 1 if (cache.contains(shrinked to groupsToMatch)) return cache[shrinked to groupsToMatch]!! // matches but not in cache yet val test1 = shrinked.replaceFirst('?', '.') val test2 = shrinked.replaceFirst('?', '#') val matches = getNumberOfMatches(test1, groupsToMatch, regex) + getNumberOfMatches(test2, groupsToMatch, regex) return matches.also { cache[shrinked to groupsToMatch] = it } } } object Day12 { fun part1(input: List<String>) = input.map { SpringRow.fromString(it) }.sumOf { it.arrangements.size } fun part2(input: List<String>) = input.map { SpringRow.fromPart2String(it) }.sumOf { it.arrangementsPart2 } } fun main() { val testInput = readInput("Day12_test", 2023) check(Day12.part1(testInput) == 21) check(Day12.part2(testInput) == 525152L) val input = readInput("Day12", 2023) println(Day12.part1(input)) println("\n" + Day12.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
3,415
adventOfCode
Apache License 2.0
src/main/kotlin/aoc2021/Day09.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2021 import readInput private class HeightMap(input: List<String>) { // heightmap is internally represented as a 2D Byte array private val data = input.map { str -> str.map { it.digitToInt().toByte() }.toByteArray() }.toTypedArray() /** * all the 'low points' in this height map */ val lowPoints = sequence { for (x in data.indices) { for (y in data[x].indices) { val current = Point(x, y, data[x][y]) val neighbours = getNeighboursOf(current) if (neighbours.all { it.height > current.height }) { yield(current) } } } } /** * @param point a point within this height map to get the neighbouring points for * @return a list of all the neighbours of the given point (horizontal & vertical neighbours only) */ fun getNeighboursOf(point: Point) = buildList { val x = point.x val y = point.y // points on the edged and the corners have only 2 or 3 neighbours if (x > 0) { add(Point(x - 1, y, data[x - 1][y])) } if (x < data.size - 1) { add(Point(x + 1, y, data[x + 1][y])) } if (y > 0) { add(Point(x, y - 1, data[x][y - 1])) } if (y < data[x].size - 1) { add(Point(x, y + 1, data[x][y + 1])) } } /** * Represents a point in a height map * * @property x the x-coordinate * @property y the y-coordinate * @property height the height at that point */ data class Point(val x: Int, val y: Int, val height: Byte) } private fun part1(input: List<String>) = HeightMap(input).lowPoints.map { it.height + 1 }.sum() private fun part2(input: List<String>): Int { val heightMap = HeightMap(input) return heightMap.lowPoints.map { lowPoint -> val basin = mutableSetOf<HeightMap.Point>() val queue = mutableListOf(lowPoint) while (queue.isNotEmpty()) { val current = queue.removeFirst() if (basin.add(current)) { queue.addAll(heightMap.getNeighboursOf(current).filter { it.height < 9 }) } } basin.count() // value of the basin is the amount of its points, ignoring their height }.sortedDescending().take(3).reduce { acc, i -> acc * i } } fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 15) check(part2(testInput) == 1134) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
2,687
adventOfCode
Apache License 2.0
src/twentytwo/Day03.kt
Monkey-Matt
572,710,626
false
{"Kotlin": 73188}
package twentytwo fun main() { // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day03_test") println(part1(testInput)) check(part1(testInput) == 157) println(part2(testInput)) check(part2(testInput) == 70) println("---") val input = readInputLines("Day03_input") println(part1(input)) println(part2(input)) testAlternativeSolutions() } private const val points = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" private fun part1(input: List<String>): Int { val letters = input.map { val firstHalf = it.substring(0, it.length/2) val secondHalf = it.substring(it.length/2, it.length) val commonLetter = firstHalf.toSet().intersect(secondHalf.toSet()) commonLetter.first() } val scores = letters.map { letter -> points.indexOf(letter) + 1 } return scores.sum() } private fun part2(input: List<String>): Int { val groups = input.chunked(3) val badges = groups.map { (one, two, three) -> val oneSet = one.toSet() val twoSet = two.toSet() val threeSet = three.toSet() oneSet.intersect(twoSet).intersect(threeSet).first() } val scores = badges.map { letter -> points.indexOf(letter) + 1 } return scores.sum() } // ------------------------------------------------------------------------------------------------ private fun testAlternativeSolutions() { val testInput = readInputLines("Day03_test") check(part1AlternativeSolution(testInput) == 157) check(part2AlternativeSolution(testInput) == 70) println("Alternative Solutions:") val input = readInputLines("Day03_input") println(part1AlternativeSolution(input)) println(part2AlternativeSolution(input)) } private fun part1AlternativeSolution(input: List<String>): Int { return input .map { it.substring(0, it.length/2) to it.substring(it.length/2, it.length) } .map { (firstHalf, secondHalf) -> (firstHalf intersect secondHalf).single() } .sumOf { it.score } // or ever shorter // input.sumOf { // val firstHalf = it.substring(0, it.length/2) // val secondHalf = it.substring(it.length/2, it.length) // (firstHalf intersect secondHalf).single().score // } } private fun part2AlternativeSolution(input: List<String>): Int { return input .chunked(3) .map { (one, two, three) -> (one intersect two intersect three).single() } .sumOf { it.score } // shortened but less readable // input.chunked(3).sumOf { (one, two, three) -> // (one intersect two intersect three).single().score // } } private val Char.score get() = points.indexOf(this) + 1 infix fun String.intersect(other: String): Set<Char> = this.toSet() intersect other.toSet() infix fun Set<Char>.intersect(other: String): Set<Char> = this intersect other.toSet()
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
3,001
advent-of-code-solutions
Apache License 2.0
src/Day12.kt
JIghtuse
572,807,913
false
{"Kotlin": 46764}
package day12.aoc import readInput typealias Position = Pair<Int, Int> fun List<String>.at(p: Position): Char? { if (p.first < 0 || p.first > this.lastIndex) return null if (p.second < 0 || p.second > this[0].lastIndex) return null return this[p.first][p.second] } fun findPosition(input: List<String>, needle: Char): Position { val row = input.indexOfFirst { it.indexOf(needle) != -1 } val column = input[row].indexOf(needle) return row to column } fun findPositions(input: List<String>, needle: Char): Set<Position> { return input.withIndex() .filter { (_, line) -> line.indexOf(needle) != -1 } .flatMap { (r, line) -> line.withIndex() .filter { (_, c) -> c == needle } .map { (col, _) -> r to col } }.toSet() } fun neighbourPositions(p: Position): List<Position> = listOf(p.copy(first = p.first + 1), p.copy(first = p.first - 1), p.copy(second = p.second - 1), p.copy(second = p.second + 1)) fun lookAtNeighbours(input: List<String>, pos: Position, ok: (Position) -> Boolean): List<Position> { fun existingOkNeighbour(neighbourPosition: Position) = input.getOrNull(neighbourPosition.first)?.getOrNull(neighbourPosition.second)?.let { ok(neighbourPosition) } ?: false return neighbourPositions(pos) .filter(::existingOkNeighbour) } data class PositionPlusSteps(val pos: Position, val steps: Int) fun draw(input: List<String>, w: Int, h: Int, visited: Set<Position>) { for (r in 0 until w) { for (c in 0 until h) { print(if (visited.contains(Position(r, c))) "#" else input.at(Position(r, c))) } println() } } fun countSteps( input: List<String>, startPos: Position, endPos: List<Position>, charAt: (Position) -> Char, reachable: (Char, Char) -> Boolean): Int { val visited = mutableSetOf<Position>() var toVisit = listOf(PositionPlusSteps(startPos, 0)) while (toVisit.isNotEmpty() && !endPos.any { visited.contains(it) }) { toVisit = toVisit.flatMap { lookAtNeighbours(input, it.pos) { dst -> !visited.contains(it.pos) && reachable(charAt(it.pos), charAt(dst)) }.map { neighbourPosition -> PositionPlusSteps(neighbourPosition, it.steps + 1) }.also { _ -> if (it.pos in endPos) { return it.steps } visited.add(it.pos) } } } return 0 // TODO } fun main() { fun part1(input: List<String>): Int { val startPos = findPosition(input, 'S') val endPos = findPosition(input, 'E') return countSteps( input, startPos, listOf(endPos), { when (it) { startPos -> 'a' endPos -> 'z' else -> input.at(it)!! } }, { src, dst -> src + 1 >= dst }) } fun part2(input: List<String>): Int { val startPos = findPosition(input, 'E') val endPos = findPositions(input, 'a').plus(findPositions(input, 'S')).toList() return countSteps( input, startPos, endPos, { when (it) { startPos -> 'z' in endPos -> 'a' else -> input.at(it)!! } }, { src, dst -> src - 1 <= dst }) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) println("tests done") val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8f33c74e14f30d476267ab3b046b5788a91c642b
3,940
aoc-2022-in-kotlin
Apache License 2.0
src/day11/Day11.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day11 import readInput import java.util.LinkedList fun main() { println( solve1(testMonkeys())) println( solve1(taskMonkeys())) println( solve2(testMonkeys())) println( solve2(taskMonkeys())) } typealias Action = (Long) -> Unit class Monkey(val name: String, initial: List<Long>, private val operation: (Long) -> Long, val denom: Long, val positive : Action, val negative: Action) { var inspected = 0L private var levels = LinkedList(initial) private lateinit var worryReducer: (Long) -> Long fun receive(item : Long) { levels.add(item) } private fun test(v: Long): Boolean = v % denom == 0L fun calm(worryReducer: (Long) -> Long): Monkey { this.worryReducer = worryReducer return this } fun round() { val insp = levels.map(operation) inspected += insp.size levels.clear() insp.asSequence() .map{worryReducer(it)} .forEach{ if(test(it)) { positive(it) } else { negative(it) } } } } fun solve(monkeys: List<Monkey>, rounds: Int): Long { for(i in 1..rounds) { monkeys.forEach { it.round() } } val active = monkeys.sortedByDescending { it.inspected }.take(2) return active.map { it.inspected }.reduce{ x,y -> x*y } } fun solve1(monkeys: List<Monkey>): Long { monkeys.forEach { it.calm { v -> v / 3 } } return solve(monkeys, 20) } fun solve2(monkeys: List<Monkey>): Long { val d = monkeys.map { it.denom }.reduce { a, b -> a*b } monkeys.forEach { it.calm { v -> v % d } } return solve(monkeys, 10_000) } fun taskMonkeys(): List<Monkey> { return parse(readInput("day11/input")) } private fun testMonkeys(): List<Monkey> { return parse(readInput("day11/test")) } fun parse(lines: List<String>): List<Monkey> { val ctx = mutableMapOf<String, Monkey>() val monkeys = lines.chunked(7) .map { parseMonkey(it) { n -> ctx[n]!! } } ctx.putAll(monkeys.associateBy { it.name }) return monkeys } val nameRegexp = """\s(\d+):""".toRegex() val nameTest = """throw to monkey (\d+)""".toRegex() fun parseMonkey(rows: List<String>, sel: (String) -> Monkey): Monkey { val name = nameRegexp.find(rows[0])!!.groupValues[1] val initial = toItems(rows[1]) val modifier = toModifier(rows[2]) val divisor = rows[3].split("by")[1].trim().toLong() val positive = nameTest.find(rows[4])!!.groupValues[1] val negative = nameTest.find(rows[5])!!.groupValues[1] return Monkey(name, initial, modifier, divisor, {v -> sel(positive).receive(v)}, {v -> sel(negative).receive(v)}) } fun toModifier(str: String): (Long) -> Long { var old : Long = 0 fun toOper(s: String): (Long, Long) -> Long = when(s) { "+" -> {a,b -> a + b} "*" -> {a, b -> a * b} else -> throw IllegalArgumentException("$s not supported") } fun toV(s: String): () -> Long { return if(s == "old") { -> old} else { -> s.toLong() } } val tokens = str.split(" = ")[1].split(" ").map { it.trim() } val first = toV(tokens[0]) val second = toV(tokens[2]) val f = toOper(tokens[1]) return {x -> old = x f(first.invoke(), second.invoke()) } } fun toItems(s: String): List<Long> { return s.split(":")[1] .split(",").map { it.trim().toLong() } }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
3,534
aoc-2022
Apache License 2.0
src/main/kotlin/day9/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day9 import util.readTestInput import kotlin.math.abs enum class Direction(val symbol: String, val dx: Int, val dy: Int) { LEFT("L", -1, 0), RIGHT("R", 1, 0), UP("U", 0, -1), DOWN("D", 0, 1) } data class Move(val direction: Direction, val amount: Int = 1) { companion object { fun parse(str: String): Move { val (directionStr, amountStr) = str.split(" ") val direction = Direction.values().find {it.symbol == directionStr }!! return Move(direction, amountStr.toInt()) } } } data class Coord(val x: Int, val y: Int) { fun moveXTowards(coord: Coord) = Coord(x + if (coord.x > x) 1 else -1, y) fun moveYTowards(coord: Coord) = Coord(x, y + if (coord.y > y) 1 else -1) fun move(direction: Direction) = Coord(x + direction.dx, y + direction.dy) fun move(move: Move) = Coord(x + move.amount * move.direction.dx, y + move.amount * move.direction.dy) fun collectCoords(move: Move): List<Coord> = (1 .. move.amount).map { amount -> this.move(Move(move.direction, amount)) } fun isAdjacent(coord: Coord) = abs(x - coord.x) <= 1 && abs(y - coord.y) <= 1 } // For rope visualization fun drawPath(path: List<Coord>, width: Int = 6, height: Int = 5) { for (y in 0 until height) { for (x in 0 until width) { if (path.contains(Coord(x, y))) print('X') else print('.') } println() } } fun nextTailPos(headPos: Coord, tailPos: Coord): Coord? { return when { headPos.isAdjacent(tailPos) -> null // don't move headPos.x == tailPos.x -> tailPos.moveYTowards(headPos) // move up or down headPos.y == tailPos.y -> tailPos.moveXTowards(headPos) // move left or righ else -> tailPos.moveXTowards(headPos).moveYTowards(headPos) // move diagonally towards head } } fun headPath(moves: List<Move>, startingPos: Coord): List<Coord> = moves.fold(listOf(startingPos)) { path, move -> path + path.last().collectCoords(move) } fun knotPath(followPath: List<Coord>): List<Coord> { return followPath.fold(listOf(followPath.first())) { path, coord -> val nextTailPos = nextTailPos(coord, path.last()) if (nextTailPos != null) path + nextTailPos else path } } fun part1(moves: List<Move>, startingPos: Coord): Int { val headPath = headPath(moves, startingPos) val tailPath = knotPath(headPath) return tailPath.toSet().size } fun part2(moves: List<Move>, startingPos: Coord): Int { var currentPath = headPath(moves, startingPos) for (i in 1..9) { currentPath = knotPath(currentPath) } return currentPath.toSet().size } fun main() { // Solution for https://adventofcode.com/2022/day/9 // Downloaded the input from https://adventofcode.com/2022/day/9/input val moves = readTestInput("day9").map { Move.parse(it) } val startingPos = Coord(0, 4) println(part1(moves, startingPos)) // 13 println(part2(moves, startingPos)) // 1 }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
3,073
advent-of-code-2022
MIT License
kotlin/src/x2022/day11/day11.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package day11 import readInput enum class MathOperation { Multiply, Divide, Subtract, Add; } // -1 == old value data class Operation(val op: MathOperation, val value: Long, val useOld: Boolean) { fun compute(input: Long): Long { val v = when (useOld) { true -> input else -> value } return when (op) { MathOperation.Multiply -> input * v MathOperation.Divide -> input / v MathOperation.Add -> input + v MathOperation.Subtract -> input - v } } } data class Monkey( val items: MutableList<Long>, val operation: Operation, val test: Operation, val targets: Pair<Int, Int> ) { var inspected = 0 } fun lcm(divisors: List<Long>): Long { var lcm = divisors.maxOf { it } while (true) { if (divisors.all { lcm % it == 0.toLong() }) break else lcm++ } return lcm } class Barrel(private val monkeys: List<Monkey>) { private val lcm = lcm(monkeys.map { it.test.value }) fun play(relief: Int) { for (monkey in monkeys) { val oldItems = monkey.items.toList() monkey.items.clear() for (item in oldItems) { monkey.inspected++ var newItem = monkey.operation.compute(item) if (relief > 1) { newItem = monkey.operation.compute(item) / relief } if (newItem % monkey.test.value == 0.toLong()) { monkeys[monkey.targets.first].items.add(newItem % lcm) } else { monkeys[monkey.targets.second].items.add(newItem % lcm) } } } } fun monkeyBusiness(): Long { return monkeys.sortedBy { it.inspected }.takeLast(2).map { it.inspected.toLong() }.reduce { a, b -> a * b } } } fun main() { fun parseInput(input: List<String>): List<Monkey> { return input.map { it.split(" ").filter { i -> i.isNotEmpty() } }.chunked(7).map { parts -> Monkey( items = parts[1].mapNotNull { it.split(",").first().toLongOrNull() }.toMutableList(), operation = Operation( op = when (parts[2][4]) { "*" -> MathOperation.Multiply "+" -> MathOperation.Add else -> throw Exception("op input error: ${parts[2]}") }, value = if (parts[2][5] == "old") 0.toLong() else parts[2][5].toLong(), useOld = parts[2][5] == "old", ), test = Operation( op = when (parts[3][1]) { "divisible" -> MathOperation.Divide else -> throw Exception("test input error: ${parts[3]}") }, value = parts[3][3].toLong(), useOld = false, ), targets = Pair( parts[4].last().toInt(), parts[5].last().toInt() ) ) } } fun partOne(input: List<String>) { val monkeys = parseInput(input) val barrel = Barrel(monkeys) for (i in 1..20) { barrel.play(3) } for (monkey in monkeys) { println("inspected: ${monkey.inspected} - $monkey") } println("monkey business = ${barrel.monkeyBusiness()}") } fun partTwo(input: List<String>) { val monkeys = parseInput(input) val barrel = Barrel(monkeys) for (i in 1..10000) { barrel.play(1) } for (monkey in monkeys) { println("inspected: ${monkey.inspected} - $monkey") } println("monkey business = ${barrel.monkeyBusiness()}") } println("partOne test") partOne(readInput("day11.test")) println() println("partOne") partOne(readInput("day11")) println() println("partTwo with test input") partTwo(readInput("day11.test")) println() println("partTwo") partTwo(readInput("day11")) }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
4,204
adventOfCode
Apache License 2.0
src/Day09.kt
schoi80
726,076,340
false
{"Kotlin": 83778}
fun List<Long>.extrapolate(): List<List<Long>> { return (1..<this.size).map { i -> this[i] - this[i - 1] }.let { if (it.all { it == 0L }) listOf(this) else mutableListOf(this).apply { addAll(it.extrapolate()) } } } fun List<List<Long>>.lastSeq(): Long { return ((this.size - 1) downTo 0).fold(0L) { acc, i -> if (acc == 0L) this[i].last() else acc + this[i].last() } } fun List<List<Long>>.firstSeq(): Long { return ((this.size - 1) downTo 0).fold(0L) { acc, i -> if (acc == 0L) this[i].first() else this[i].first() - acc } } fun main() { val input = readInput("Day09") fun part1(input: List<String>): Long { return input.sumOf { line -> line.split("\\s+".toRegex()) .map { it.trim().toLong() } .extrapolate() // .onEach { println(it) } .lastSeq() // .also { println("extrapolated: $it") } } } fun part2(input: List<String>): Long { return input.sumOf { line -> line.split("\\s+".toRegex()) .map { it.trim().toLong() } .extrapolate() // .onEach { println(it) } .firstSeq() // .also { println("extrapolated: $it") } } } part1(input).println() part2(input).println() }
0
Kotlin
0
0
ee9fb20d0ed2471496185b6f5f2ee665803b7393
1,436
aoc-2023
Apache License 2.0
src/Day08.kt
esteluk
572,920,449
false
{"Kotlin": 29185}
fun main() { fun parseHeights(input: List<String>): Array<IntArray> { val width = input.first().length val array = Array(input.size) { IntArray(width) } for (i in 0..input.lastIndex) { for (j in 0 until width) { array[i][j] = input[i][j].toString().toInt() } } return array } fun part1(input: List<String>): Int { val width = input.first().length val array = parseHeights(input) var interiorTreeCount = (width+input.size)*2 - 4 for (i in 1 until input.lastIndex) { for (j in 1 until width-1) { val checkValue = array[i][j] val topVisible = (0 until i).map { array[it][j] }.any { it >= checkValue }.not() val leftVisible = (0 until j).map { array[i][it] }.any { it >= checkValue }.not() val bottomVisible = (i+1..input.lastIndex).map { array[it][j] }.any { it >= checkValue }.not() val rightVisible = (j+1 until width).map { array[i][it] }.any { it >= checkValue }.not() // If any value >= checkValue, return false if (topVisible || leftVisible || bottomVisible || rightVisible) { interiorTreeCount += 1 } } } return interiorTreeCount } fun part2(input: List<String>): Int { val width = input.first().length val array = parseHeights(input) var bestScore = 0 for (i in 1 until input.lastIndex) { for (j in 1 until width-1) { val checkValue = array[i][j] val topCount = ((i - 1 downTo 0).map { array[it][j] }.takeWhile { it < checkValue } .count() + 1).coerceAtMost((i - 1 downTo 0).count()) val leftCount = ((j-1 downTo 0).map { array[i][it] }.takeWhile { it < checkValue }.count() + 1) .coerceAtMost((j-1 downTo 0).count()) val bottomCount = ((i+1 .. input.lastIndex).map { array[it][j] }.takeWhile { it < checkValue }.count() + 1) .coerceAtMost((i+1 .. input.lastIndex).count()) val rightCount = ((j+1 until width).map { array[i][it] }.takeWhile { it < checkValue }.count() + 1).coerceAtMost((j+1 until width).count()) val score = topCount * leftCount * bottomCount * rightCount if (score > bestScore) { bestScore = score } } } return bestScore } // 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
5d1cf6c32b0c76c928e74e8dd69513bd68b8cb73
2,833
adventofcode-2022
Apache License 2.0
src/main/kotlin/Day05.kt
bent-lorentzen
727,619,283
false
{"Kotlin": 68153}
import java.time.LocalDateTime import java.time.ZoneOffset import java.util.SortedMap fun main() { fun readSeads(line: String) = line.substringAfter(": ").split(Regex(" ")).filterNot { it.isEmpty() }.map { it.toLong() } fun readSeadRanges(line: String): List<LongRange> { val numbers = line.substringAfter(": ").split(Regex(" ")).filterNot { it.isEmpty() }.map { it.toLong() } return (0..numbers.lastIndex / 2).mapIndexed { index, i -> val from = numbers[index * 2] val to = from + numbers[(index * 2) + 1] (from..to) } } fun readMap(label: String, lines: List<String>): Map<LongRange, Long> { val maplabelIndex = lines.indexOf(label) val sublist = lines.subList(maplabelIndex + 1, lines.size) val mapEndBlank = sublist.indexOf("") val ranges: List<Pair<LongRange, Long>> = sublist.subList(0, if (mapEndBlank > 0) mapEndBlank else sublist.size).map { val entry = it.split(" ") val sorceDestinationOffset = entry[0].toLong() - entry[1].toLong() (entry[1].toLong()..<entry[1].toLong() + entry[2].toLong()) to sorceDestinationOffset }.sortedBy { it.first.first } var previousRangeEnd = -1L val inBetweenRanges: List<Pair<LongRange, Long>> = ranges.mapNotNull { if (it.first.first > previousRangeEnd + 1) { val inBetweenRange = (previousRangeEnd + 1..<it.first.first) to 0L previousRangeEnd = it.first.last inBetweenRange } else if (it == ranges.last) { (it.first.last + 1..10_000_000_000) to 0L } else { previousRangeEnd = it.first.last null } } return (ranges + inBetweenRanges).toMap().toSortedMap { o1, o2 -> o1.first.compareTo(o2.first) } } fun mergeMaps(sourceMap: Map<LongRange, Long>, targetMap: Map<LongRange, Long>): SortedMap<LongRange, Long> { return sourceMap.entries.map { sourceEntry -> val newRanges = mutableMapOf<LongRange, Long>() var targetRangeLast = -1L var newFirst = sourceEntry.key.first while (targetRangeLast < sourceEntry.key.last + sourceEntry.value) { targetMap.entries.first { newFirst + sourceEntry.value in it.key }.let { targetRange -> if (targetRange.key.last >= sourceEntry.key.last + sourceEntry.value) { newRanges[newFirst..sourceEntry.key.last] = sourceEntry.value + targetRange.value targetRangeLast = targetRange.key.last } else { targetRangeLast = targetRange.key.last newRanges[newFirst..(targetRangeLast - sourceEntry.value)] = sourceEntry.value + targetRange.value newFirst = targetRangeLast - sourceEntry.value + 1 } } } newRanges }.fold(emptyMap<LongRange, Long>()) { acc, mutableMap -> acc + mutableMap }.toSortedMap { o1, o2 -> o1.first.compareTo(o2.first) } } fun seedToLocationMap(input: List<String>): Map<LongRange, Long> { val mapLabels = listOf( "seed-to-soil map:", "soil-to-fertilizer map:", "fertilizer-to-water map:", "water-to-light map:", "light-to-temperature map:", "temperature-to-humidity map:", "humidity-to-location map:" ) return mapLabels.reversed().fold(mapOf(0..10_000_000_000L to 0L)) { acc, mapLabel -> val sorceMap = readMap(mapLabel, input) mergeMaps(sorceMap, acc) } } fun part1(input: List<String>): Long { val seeds = readSeads(input.first) val seedToLocationMap = seedToLocationMap(input) return seeds.minOf { seed -> seedToLocationMap.entries.filter { seed in it.key }.let { seed + it.first.value } } } fun part2(input: List<String>): Long { val seedRanges: List<LongRange> = readSeadRanges(input.first).sortedBy { it.first } val seedToLocationMap = seedToLocationMap(input) val modifiedSeedRanges = seedRanges.map { seedRange -> val modifiedRanges = mutableListOf<LongRange>() var seedToLocationRange = (-1L..-1L) var newFirst = seedRange.first while (seedToLocationRange.last < seedRange.last) { seedToLocationRange = seedToLocationMap.keys.first { newFirst in it } if (seedToLocationRange.last > seedRange.last) { modifiedRanges.add(newFirst..seedRange.last) } else { modifiedRanges.add(newFirst..seedToLocationRange.last) newFirst = seedToLocationRange.last + 1 } } modifiedRanges }.flatten() return modifiedSeedRanges.minOf { seedRange -> seedToLocationMap.entries.filter { seedRange.first in it.key }.let { seedRange.first + it.first.value } } } val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() val input = readLines("day05-input.txt") seedToLocationMap(input) val result1 = part1(input) "Result1: $result1".println() val result2 = part2(input) "Result2: $result2".println() println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms") }
0
Kotlin
0
0
41f376bd71a8449e05bbd5b9dd03b3019bde040b
5,565
aoc-2023-in-kotlin
Apache License 2.0
src/Day11.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
enum class Operator { ADD, MULTIPLY, } class Monkey( private val id: Long, private val items: ArrayDeque<Long>, private val operation: Pair<Operator, Long?>, private val testDivisibleByValue: Long, private val testSuccessMonkeyId: Long, private val testFailureMonkeyId: Long, ) { var inspectedItemsCount = 0 fun turn(monkeys: List<Monkey>, damageRelief: Boolean = true) { repeat(items.size) { val item = items.removeFirst() val (op, opVal) = operation var newItem = when (op) { Operator.ADD -> item + (opVal ?: item) Operator.MULTIPLY -> item * (opVal ?: item) } if (damageRelief) { newItem = newItem.floorDiv(3) } else { newItem %= monkeys.map { it.testDivisibleByValue }.reduce { acc, test -> acc * test } } if (newItem % testDivisibleByValue == 0L) { monkeys.first { it.id == testSuccessMonkeyId }.items.addLast(newItem) } else { monkeys.first { it.id == testFailureMonkeyId }.items.addLast(newItem) } inspectedItemsCount++ } } } fun createMonkeys(input: List<String>): MutableList<Monkey> { val monkeys = mutableListOf<Monkey>() input.chunked(7).forEach { block -> val monkeyId = block[0].substringAfter("Monkey ").dropLast(1).toLong() val items = block[1].substringAfter("Starting items: ").split(", ").map { it.toLong() } val itemDeque = ArrayDeque(items) val (opStr, valStr) = """old\s([+*])\s(\d+|old)""".toRegex() .find(block[2].substringAfter("= "))!!.destructured val op = when (opStr) { "*" -> Operator.MULTIPLY "+" -> Operator.ADD else -> throw IllegalArgumentException() } val opVal = if (valStr == "old") null else valStr.toLong() val testValue = block[3].substringAfter("by ").toLong() val testTrueId = block[4].substringAfter("monkey ").toLong() val testFalseId = block[5].substringAfter("monkey ").toLong() monkeys.add(Monkey(monkeyId, itemDeque, op to opVal, testValue, testTrueId, testFalseId)) } return monkeys } fun main() { fun part1(input: List<String>): Int { val monkeys = createMonkeys(input) repeat(20) { monkeys.forEach { monkey -> monkey.turn(monkeys) } } return monkeys.map { it.inspectedItemsCount }.sorted().takeLast(2).reduce { m1, m2 -> m1 * m2 } } fun part2(input: List<String>): Long { val monkeys = createMonkeys(input) repeat(10000) { monkeys.forEach { monkey -> monkey.turn(monkeys, false) } } return monkeys.map { it.inspectedItemsCount.toLong() }.sorted().takeLast(2).reduce { m1, m2 -> m1 * m2 } } val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
3,104
advent-of-code-2022
Apache License 2.0
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/problems/AE_List.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.problems import com.nalin.datastructurealgorithm.ds.LinkedListNode import kotlin.math.max import kotlin.math.min /** * Merge overlapping intervals. They are not likely to be in order */ fun mergeOverlappingIntervals(intervals: List<List<Int>>): List<List<Int>> { val sortedInterval = intervals.sortedBy { it[0] } val result = mutableListOf<MutableList<Int>>() for (item in sortedInterval) { if (result.size != 0 && checkIntervalOveralps(result.last(), item)) { result.last()[0] = min(item[0], result.last()[0]) result.last()[1] = max(item[1], result.last()[1]) } else { result.add(mutableListOf(item[0], item[1])) } } return result } fun checkIntervalOveralps(item1: List<Int>, item2: List<Int>): Boolean { // item1 left is not in item2 right // item1 right is not in item2 left return !((item1[0] < item2[0] && item1[1] < item2[0]) || (item1[0] > item2[0] && item1[0] > item2[1])) } fun firstDuplicateValue(array: MutableList<Int>): Int { val map = hashMapOf<Int, Int>() for (item in array) { map.put(item, (map.get(item) ?: 0) + 1) if (map.get(item)!! > 1) { return item } } return -1 } /** * Check if a given linked list is palindrome or not */ fun linkedListPalindrome(linkedList: LinkedListNode<Int>?): Boolean { fun _traverse( head: LinkedListNode<Int>, tail: LinkedListNode<Int> ): Pair<LinkedListNode<Int>?, Boolean> { var result = true var newHead: LinkedListNode<Int>? = head if (tail.nextNode !== null) { val (resHead, newResult) = _traverse(head, tail.nextNode!!) newHead = resHead result = newResult } return Pair(newHead?.nextNode, result && newHead?.value == tail.value) } return _traverse(linkedList!!, linkedList!!).second } /** * https://www.algoexpert.io/questions/tandem-bicycle * Given 2 players and set of speed, find maximum total speed and minimum total speed */ fun tandemBicycle( redShirtSpeeds: MutableList<Int>, blueShirtSpeeds: MutableList<Int>, fastest: Boolean ): Int { if (redShirtSpeeds.size != blueShirtSpeeds.size) { return -1 } redShirtSpeeds.sortDescending() blueShirtSpeeds.sortDescending() var redPointer = 0 var bluePointer = if (fastest) redShirtSpeeds.size - 1 else 0 var totalPoint = 0 while (redPointer < redShirtSpeeds.size) { totalPoint += max(redShirtSpeeds[redPointer], blueShirtSpeeds[bluePointer]) redPointer++ bluePointer = if (fastest) bluePointer - 1 else bluePointer + 1 } return totalPoint } /** * Find 2 number whose sum = target number */ fun twoNumberSum(array: MutableList<Int>, targetSum: Int): List<Int> { val arraySet = mutableSetOf<Int>() for (num in array) { arraySet.add(num) } for (num in array) { if (num != targetSum - num && arraySet.contains(targetSum - num)) { return listOf(targetSum - num, num) } } // Write your code here. return listOf<Int>() } /** * https://www.algoexpert.io/questions/class-photos * 1. All red shirts student will stand in one row and all blue in another * 2. Student in front is always smaller than student in back */ fun classPhotos(redShirtHeights: MutableList<Int>, blueShirtHeights: MutableList<Int>): Boolean { // Write your code here. if (redShirtHeights.size == blueShirtHeights.size) { val sortedRed = redShirtHeights.sorted() val sortedBlue = blueShirtHeights.sorted() var directionSmall: Boolean? = null for (i in sortedRed.indices) { val diff = sortedRed[i] - sortedBlue[i] if (directionSmall == null) { directionSmall = diff < 0 } else if ((directionSmall == true && diff < 0) || directionSmall == false && diff > 0) { continue; } else { return false } } return true } return false } fun getNthFib(n: Int): Double { if (n <= 0) return 0.0 val dp = mutableMapOf<Int, Double>() dp[0] = 0.0 dp[1] = 1.0 for (i in 2 until n) { dp[i] = dp[i - 1]!! + dp[i - 2]!! } return dp[n - 1]!! // fun fib(n: Int, dp: MutableMap<Int, Double>): Double { // if (dp.contains(n)) { // return dp[n]!! // } // var output = 0.0; // if (n == 0) { // output = 0.0 // } // if (n == 1) { // output = 1.0 // } // // if (n >= 2) { // output = fib(n - 1, dp) + fib(n - 2, dp) // dp[n] = output; // } // // return output; // } // if (n == 0) return 0.0; // return fib(n-1, dp) } /** * Find Islands in given matrix */ fun riverSizes(matrix: List<List<Int>>): List<Int> { // DFS val output = mutableListOf<Int>() if (matrix.isEmpty()) return output val visited = mutableListOf<MutableList<Int>>() for (list in matrix) { val visitedList = mutableListOf<Int>() visited.add(visitedList) for (item in list) { visitedList.add(0) } } var nextNumber = 1; fun validatePosAndAdd(queue: MutableSet<Pair<Int, Int>>, i: Int, j: Int, isRiver: Int) { if (i < matrix.size && i >= 0 && j < matrix[i].size && j >= 0 && matrix[i][j] == isRiver && visited[i][j] == 0 ) { queue.add(Pair(i, j)) } } fun explorePos(pos: Pair<Int, Int>) { val isRiver = matrix[pos.first][pos.second] var count = 0 // run a dfs and mark all point is visited or not val number = if (isRiver == 0) { -1 } else { nextNumber } val queue = mutableSetOf<Pair<Int, Int>>() queue.add(pos) while (queue.size > 0) { val currentPos = queue.firstOrNull()!! queue.remove(currentPos); count++ visited[currentPos.first][currentPos.second] = number // right validatePosAndAdd(queue, currentPos.first + 1, currentPos.second, isRiver) // bottom validatePosAndAdd(queue, currentPos.first, currentPos.second + 1, isRiver) // top validatePosAndAdd(queue, currentPos.first - 1, currentPos.second, isRiver) // left validatePosAndAdd(queue, currentPos.first, currentPos.second - 1, isRiver) } if (isRiver == 1) { output.add(count) nextNumber++ } } for (i in matrix.indices) { for (j in matrix[i].indices) { if (visited[i][j] == 0) { explorePos(Pair(i, j)) } } } return output } /** * Subarray Sort -> Find unsorted subarray * https://www.algoexpert.io/questions/subarray-sort */ fun unsortedSubarray(array: List<Int>): List<Int> { // take from back, find min value in wrong position // take from front, find max value in wrong position if (array.size > 1) { var foundMinIndex = -1 var foundMaxIndex = -1 var minValue = Int.MAX_VALUE var maxValue = Int.MIN_VALUE for (i in array.indices) { // place where failure occur if (i < array.size - 1 && array[i] > array[i + 1]) { minValue = min(minValue, array[i + 1]) foundMinIndex = i + 1 } if (i > 0 && array[i - 1] > array[i]) { maxValue = max(maxValue, array[i - 1]) foundMaxIndex = i - 1 } } if (foundMaxIndex >= 0 || foundMinIndex >= 0) { var posInsertMin = 0 for (i in array.indices) { if (array[i] > minValue) { posInsertMin = i break; } } var posInsertMax = array.size - 1 for (i in array.indices.reversed()) { if (array[i] < maxValue) { posInsertMax = i break; } } return listOf(posInsertMin, posInsertMax) } } // Write your code here. return listOf(-1, -1) }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
8,465
kotlin-ds-algo
MIT License
src/main/kotlin/io/github/aarjavp/aoc/day04/Day04.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day04 import io.github.aarjavp.aoc.readFromClasspath import io.github.aarjavp.aoc.split class Day04 { data class Location(val x: Int, val y: Int) class BingoBoard(val mapping: Map<Int, Location>, val gridSize: Int) { val markedLocations = mutableSetOf<Location>() companion object { fun parseBoard(lines: List<String>): BingoBoard { val mapping = buildMap<Int, Location> { for ((rowIndex, line) in lines.withIndex()) { for ((colIndex, rawInt) in line.split(' ').filter { it.isNotBlank() }.withIndex()) { val location = Location(colIndex, rowIndex) val number = rawInt.toInt() put(number, location) } } } return BingoBoard(mapping, lines.size) } } fun mark(n: Int): Location? = mapping[n]?.also { markedLocations.add(it) } fun hasWon(): Boolean { if (markedLocations.size < gridSize) return false if (markedLocations.groupBy { it.x }.any { it.value.size == gridSize}) return true return markedLocations.groupBy { it.y }.any { it.value.size == gridSize } } fun score(multiplier: Int): Int { return mapping.entries.filter { it.value !in markedLocations }.sumOf { it.key } * multiplier } } fun parseSetup(lines: Sequence<String>): Pair<Sequence<Int>, List<BingoBoard>> { val split = lines.split { it.isBlank() }.toList() val numbers = split.first().first().splitToSequence(',').map { it.toInt() } val boards = split.subList(1, split.size).map { BingoBoard.parseBoard(it) } return numbers to boards } fun part1(numbers: Sequence<Int>, boards: List<BingoBoard>): Int { for (number in numbers) { for (board in boards) { board.mark(number)?.let { if (board.hasWon()) { return board.score(number) } } } } println("winner not found") println(numbers) println(boards.count()) return 0 } fun part2(numbers: Sequence<Int>, boards: List<BingoBoard>): Int { val remainingBoards = boards.toMutableList() for (number in numbers) { val iterator = remainingBoards.iterator() while (iterator.hasNext()) { val board = iterator.next() board.mark(number)?.let { if (board.hasWon()) { if (remainingBoards.size == 1) { // this was the last remaining board, and it just won! return board.score(number) } else { iterator.remove() } } } } } println("last winner score not found / undefined") println(numbers) println(boards.count()) return 0 } } fun main() { val solution = Day04() readFromClasspath("Day04.txt").useLines { lines -> val (numbers, boards) = solution.parseSetup(lines) val part1score = solution.part1(numbers, boards) val part2score = solution.part2(numbers, boards) println(part1score) println(part2score) } }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
3,523
advent-of-code-2021
MIT License
src/day08/Day08.kt
Ciel-MC
572,868,010
false
{"Kotlin": 55885}
package day08 import readInput fun <T> List<T>.splitExclusive(index: Int): Pair<List<T>, List<T>> = this.take(index) to this.drop(index + 1) data class Vertical(val x: Int) operator fun <T> List<List<T>>.get(vertical: Vertical): List<T> = this.map { it[vertical.x] } fun <T> List<List<T>>.splitExclusiveVertical(y: Int, x: Int): Pair<List<T>, List<T>> = this[Vertical(x)].splitExclusive(y) fun <T> List<List<T>>.xyv(): List<Triple<Int, Int, T>> = this.withIndex().flatMap { (i, v) -> v.withIndex().map { i to it } }.map { (y, v) -> val (x, value) = v Triple(x, y, value) } fun <T> List<T>.indexOfFirstOrLast(predicate: (T) -> Boolean): Int = this.indexOfFirst(predicate).takeIf { it != -1 } ?: this.lastIndex fun main() { fun part1(input: List<String>): Int { val grid = input.map { string -> string.toCharArray().map(Char::digitToInt) } return grid.xyv().count { (x, y, value) -> val (left, right) = grid[y].splitExclusive(x) val (top, bottom) = grid.splitExclusiveVertical(y, x) return@count listOf(left, right, top, bottom).any { it.all { it < value } } } } fun part2(input: List<String>): Int { val grid = input.map { string -> string.toCharArray().map { char -> char.digitToInt() } } return grid.xyv().maxOf { (x, y, value) -> buildList(4) { grid[y].splitExclusive(x).let { (l, r) -> add(l.reversed()) add(r) } grid.splitExclusiveVertical(y, x).let { (t, b) -> add(t.reversed()) add(b) } }.map { it.indexOfFirstOrLast { it >= value } + 1 }.reduce(Int::times) } } val testInput = readInput(8, true) part1(testInput).let { check(it == 21) { println(it) } } part2(testInput).let { check(it == 8) { println(it) } } val input = readInput(8) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7eb57c9bced945dcad4750a7cc4835e56d20cbc8
2,021
Advent-Of-Code
Apache License 2.0
src/main/kotlin/day3/Day03.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day3 fun solveA(input: List<String>) = input .map { it.half() } .map { it.distinctLetters() } .sumOf { it.sumOf { c -> convertToPriority(c) } } fun solveB(input: List<String>) = input .chunked(3) .map { it.distinctLetters() } .sumOf { it.sumOf { c -> convertToPriority(c) } } fun convertToPriority(char: Char) = if (char.isUpperCase()) char.code - 38 else char.code - 96 fun String.toDistinct() = this.toSet().joinToString() fun String.half() = this.chunked(this.length / 2) fun List<String>.distinctLetters() = this.first() .filter { c -> this.all { s -> s.contains(c) } } .toDistinct() // naive approach //fun solveA(input: List<String>): Int { // // // val items = input.map { // val halfed = it.chunked(it.length / 2) // halfed.first().filter { inner -> halfed.last().contains(inner) }.toSet().joinToString() // } // // return items.map { it.map { c -> convert(c) }.sum() }.sum() //} // //fun convert(char: Char): Int { // return if (char.isUpperCase()) char.code - 38 // else char.code - 96 //} // //fun solveB(input: List<String>): Int { // // val groups = input.chunked(3) // .map { it[0].filter { inner -> it[1].contains(inner) && it[2].contains(inner) }.toSet().joinToString() } // .map { it.map { c -> convert(c) }.sum() } // .sum() // return groups //}
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
1,368
advent-of-code-2022
Apache License 2.0
src/Day08.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
fun main() { Day8.printSolutionIfTest(21, 8) } object Day8 : Day<Int, Int>(8) { override fun part1(lines: List<String>): Int = buildGrid(lines) { tagVisible(it) }.flatten().count { it.visible } override fun part2(lines: List<String>): Int = buildGrid(lines) { tagScores(it) }.flatten().maxOf { it.score ?: 0 } private fun buildGrid(lines: List<String>, process: (List<Tree>) -> Unit): List<List<Tree>> = lines.map { line -> line.map { Tree(it.digitToInt()) } }.also { grid -> grid.sightLines().forEach { process(it) } } private fun tagVisible(trees: List<Tree>) = trees.map { it.height }.runningFold(0) { acc, h -> maxOf(acc, h) }.dropLast(1).withIndex() .filter { (index, max) -> trees[index].height > max }.forEach { (index, _) -> trees[index].visible = true } .also { trees.last().visible = true } private fun tagScores(trees: List<Tree>) = trees.drop(1).dropLast(1).forEachIndexed { index, tree -> val score = (index downTo 0).indexOfFirst { trees[it].height >= tree.height }.let { 1 + if (it < 0) index else it } tree.score = tree.score?.times(score) ?: score } data class Tree(val height: Int, var visible: Boolean = false, var score: Int? = null) private fun <T> List<List<T>>.toCols() = List(this[0].size) { index -> this.map { it[index] } } private fun <T> List<List<T>>.sightLines() = listOf(this, this.toCols()).flatten().flatMap { listOf(it, it.reversed()) } }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
1,560
advent-of-code-2022
Apache License 2.0
src/day05/Day05.kt
TheJosean
573,113,380
false
{"Kotlin": 20611}
package day05 import readInput import splitList fun main() { data class Step(val amount: Int, val from: Int, val to: Int) fun transpose(matrix: List<List<Char>>): List<List<Char>> { matrix.filter { it.isNotEmpty() }.let { list -> return when { list.isNotEmpty() -> listOf(list.map { it.first() }) .plus(transpose(list.map { it.takeLast(it.size - 1) })) else -> emptyList() } } } fun parseStacks(stacks: List<String>) = transpose(stacks.map { it.toList() }) .mapIndexedNotNull { index, list -> when { index % 4 == 1 -> list else -> null } } .associateBy( { it.last().digitToInt() }, { it.subList(0, it.lastIndex).filter { l -> l.isLetter() }.reversed() } ).toMutableMap() fun parseSteps(steps: List<String>) = steps.map { s -> val (amount, from, to) = s.split(" ").mapNotNull { it.toIntOrNull() } Step(amount, from, to) } fun parseInput(input: List<String>):Pair<MutableMap<Int, List<Char>>, List<Step>> { val (rawStacks, rawSteps) = splitList(input) return parseStacks(rawStacks) to parseSteps(rawSteps) } fun part1(input: List<String>): String { val (stacks, steps) = parseInput(input) steps.forEach { stacks[it.to] = stacks.getValue(it.to).plus(stacks.getValue(it.from).takeLast(it.amount).reversed()) stacks[it.from] = stacks.getValue(it.from).dropLast(it.amount) } return stacks.values.map { it.last() }.joinToString("") } fun part2(input: List<String>): String { val (stacks, steps) = parseInput(input) steps.forEach { stacks[it.to] = stacks.getValue(it.to).plus(stacks.getValue(it.from).takeLast(it.amount)) stacks[it.from] = stacks.getValue(it.from).dropLast(it.amount) } return stacks.values.map { it.last() }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("/day05/Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("/day05/Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
798d5e9b1ce446ba3bac86f70b7888335e1a242b
2,409
advent-of-code
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day12/day12.kt
mrugacz95
317,354,321
false
null
import kotlin.math.abs private operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>): Pair<Int, Int> { return Pair(this.first + other.first, this.second + other.second) } open class Point(var pos: Pair<Int, Int> = Pair(0, 0)) { var angle = 90 open fun apply(command: Pair<Char, Int>) { when (command.first) { 'N' -> pos += Pair(-command.second, 0) 'S' -> pos += Pair(command.second, 0) 'E' -> pos += Pair(0, command.second) 'W' -> pos += Pair(0, -command.second) 'L' -> angle = (angle - command.second + 360) % 360 // counter- clockwise 'R' -> angle = (angle + command.second + 360) % 360 // clockwise 'F' -> when (angle) { 0 -> apply(Pair('N', command.second)) 90 -> apply(Pair('E', command.second)) 180 -> apply(Pair('S', command.second)) 270 -> apply(Pair('W', command.second)) } } } fun distance(): Int { return abs(pos.first) + abs(pos.second) } override fun toString(): String { return "<${printPos()}, angle: $angle>" } fun printPos(): String { return "pos: ${abs(pos.first)}${if (pos.first > 0) 'S' else 'N'} ${abs(pos.second)}${if (pos.second > 0) 'E' else 'W'}" } } class PointWithWaypoint : Point() { private val waypoint = Point(Pair(-1, 10)) override fun apply(command: Pair<Char, Int>) { when (command.first) { 'N' -> waypoint.apply(command) 'S' -> waypoint.apply(command) 'E' -> waypoint.apply(command) 'W' -> waypoint.apply(command) 'L' -> waypoint.pos = when (command.second) { // counter-clockwise 0 -> waypoint.pos 90 -> { Pair(-waypoint.pos.second, waypoint.pos.first) } 180 -> { Pair(-waypoint.pos.first, -waypoint.pos.second) } 270 -> { Pair(waypoint.pos.second, -waypoint.pos.first) } else -> throw RuntimeException("Wrong angle: ${command.second}") } 'R' -> apply(Pair('L', (-command.second + 360) % 360)) // clockwise 'F' -> pos += Pair(waypoint.pos.first * command.second, waypoint.pos.second * command.second) } } override fun toString(): String { return "<${printPos()}, waypoint: ${waypoint.printPos()}>" } } fun solve(commands: List<Pair<Char, Int>>, ferry: Point): Int { for (command in commands) { ferry.apply(command) } return ferry.distance() } fun main() { val commands = {}::class.java.getResource("/day12.in") .readText() .split("\n") .map { Pair(it[0], it.substring(1, it.length).toInt()) } println("Answer part 1: ${solve(commands, Point())}") println("Answer part 2: ${solve(commands, PointWithWaypoint())}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
3,018
advent-of-code-2020
Do What The F*ck You Want To Public License
src/day13/d13_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val graph = input.lines().map { parseChange(it) }.groupBy { it.who }.mapValues { (_, v) -> v.associateBy({ it.nextTo }) { it.delta } } val keys = graph.keys.toList() println(forEachPermutation(keys.size) { (0 until keys.size).map { i -> keys[it[i]].let { who -> (if (i == keys.size - 1) 0 else graph[who]!![keys[it[i + 1]]]!!) + (if (i == 0) 0 else graph[who]!![keys[it[i - 1]]]!!) } }.sum() }.max()) } data class Change(val who: String, val nextTo: String, val delta: Int) fun parseChange(s: String): Change { return s.split(" ").let { Change(it[0], it[10].dropLast(1), (if ("gain" == it[2]) 1 else -1) * it[3].toInt()) } } fun <T> forEachPermutation(n: Int, f: (Array<Int>) -> T): List<T> { val arr = Array<Int>(n) { 0 } return genRecursive(arr, 0, (0 until n).toSet(), f) } fun <T> genRecursive(arr: Array<Int>, nextIdx: Int, options: Set<Int>, f: (Array<Int>) -> T): List<T> { if (nextIdx == arr.size) { return listOf(f(arr)) } val result = mutableListOf<T>() for (opt in options) { arr[nextIdx] = opt result.addAll(genRecursive(arr, nextIdx + 1, options - opt, f)) } return result }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
1,199
aoc2015
MIT License
src/y2022/Day18.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput typealias Vector = Triple<Int, Int, Int> object Day18 { private fun parse(input: List<String>): Set<Vector> { return input.map { line -> val (x, y, z) = line.split(",").map { it.toInt() } Vector(x, y, z) }.toSet() } fun Vector.neighbors(): List<Vector> { return listOf( Vector(first - 1, second, third), Vector(first + 1, second, third), Vector(first, second - 1, third), Vector(first, second + 1, third), Vector(first, second, third - 1), Vector(first, second, third + 1), ) } fun part1(input: List<String>): Long { val positions = parse(input) return positions.map { it.neighbors() }.flatten().filter { it !in positions }.size.toLong() } fun part2(input: List<String>): Long { val lava = parse(input) val neighboring = lava.map { it.neighbors() }.flatten().filter { it !in lava } val minX = neighboring.minOf { it.first } val minY = neighboring.minOf { it.second } val minZ = neighboring.minOf { it.third } val maxX = neighboring.maxOf { it.first } val maxY = neighboring.maxOf { it.second } val maxZ = neighboring.maxOf { it.third } val air = (minX - 1..maxX + 1).flatMap { x -> (minY - 1..maxY + 1).flatMap { y -> (minZ - 1..maxZ + 1).map { Vector(x, y, it) } } }.toSet() - lava val outside = connected(Triple(minX - 1, minY - 1, minZ - 1), air) return neighboring.filter { it in outside }.size.toLong() } private fun connected(seed: Vector, others: Set<Vector>): Set<Vector> { val frontier = mutableSetOf(seed) val result = mutableSetOf<Vector>() while (frontier.isNotEmpty()) { val current = frontier.first() frontier.remove(current) result.add(current) frontier.addAll(current.neighbors().filter { it in others && it !in result }) } return result } } fun main() { val testInput = """ 2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5 """.trimIndent().split("\n") println("------Tests------") println(Day18.part1(testInput)) println(Day18.part2(testInput)) println("------Real------") val input = readInput("resources/2022/day18") println(Day18.part1(input)) println(Day18.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,617
advent-of-code
Apache License 2.0
src/Day04.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
private class Assignment(start: Int, end: Int) { val range = start..end infix fun containsAllOf(other: Assignment) = range.intersect(other.range).size == other.range.count() infix fun containsAnyOf(other: Assignment) = range.intersect(other.range).isNotEmpty() companion object { fun parse(input: String) = input.split("-").map { id -> id.toInt() }.let { (start, end) -> Assignment(start, end) } } } private class AssignmentPair(val first: Assignment, val second: Assignment) { fun hasFullOverlap() = first containsAllOf second || second containsAllOf first fun hasAnyOverlap() = first containsAnyOf second || second containsAnyOf first companion object { fun parse(input: String) = input.split(",").map(Assignment::parse).let { (first, second) -> AssignmentPair(first, second) } } } fun main() { fun part1(input: List<AssignmentPair>): Int = input.count { it.hasFullOverlap() } fun part2(input: List<AssignmentPair>): Int = input.count { it.hasAnyOverlap() } val testInput = readInput("Day04_test").map(AssignmentPair::parse) check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04").map(AssignmentPair::parse) println(part1(input)) println(part2(input)) }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
1,280
advent-of-code-in-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day8.kt
MisterJack49
574,081,723
false
{"Kotlin": 35586}
package days import common.Coordinates class Day8 : Day(8) { override fun partOne(): Any { val forest: Forest = inputList.mapIndexed { y, s -> s.mapIndexed { x, c -> Tree(c.digitToInt(), Coordinates(x, y)) } }.flatten() val innerForest = forest.getInnerForest() innerForest.onEach { tree -> forest.getTreesAround(tree.coordinates).onEach { orientation -> tree.isVisible = tree.isVisible || orientation.value.none { it.height >= tree.height } } } return forest.getEdge().count() + innerForest.count { it.isVisible } } override fun partTwo(): Any { val forest: Forest = inputList.mapIndexed { y, s -> s.mapIndexed { x, c -> Tree(c.digitToInt(), Coordinates(x, y)) } }.flatten() return forest.getInnerForest().onEach { tree -> tree.scenicScore = forest.getViewableFrom(tree).map { it.count() }.reduce { acc, i -> acc * i } }.maxOf { it.scenicScore } } } data class Tree( val height: Int, val coordinates: Coordinates = Coordinates(0, 0), var isVisible: Boolean = false, var scenicScore: Int = 0 ) { fun canSee(trees: List<Tree>): List<Tree> { val firstBlockingTree = (trees.indexOfFirst { it.height >= this.height }) .let { if (it == -1) trees.size - 1 else it } return trees.subList(0, firstBlockingTree + 1) } override fun toString(): String { return "$coordinates: $height" } } typealias Forest = List<Tree> fun Forest.getSize(): Coordinates = last().coordinates fun Forest.getEdge(): Forest = filter { it.coordinates.x == 0 || it.coordinates.y == 0 || it.coordinates.x == getSize().x || it.coordinates.y == getSize().y }.copy() fun Forest.copy() = map { it.copy() } fun Forest.getInnerForest(): Forest = copy() - getEdge().toSet() fun Forest.getTreesAround(coordinates: Coordinates): Map<Orientation, Forest> = Orientation.values().associateWith { orientation -> when (orientation) { Orientation.NORTH -> { filter { it.coordinates.x == coordinates.x && it.coordinates.y < coordinates.y }.copy() } Orientation.EAST -> { filter { it.coordinates.x > coordinates.x && it.coordinates.y == coordinates.y }.copy() } Orientation.SOUTH -> { filter { it.coordinates.x == coordinates.x && it.coordinates.y > coordinates.y }.copy() } Orientation.WEST -> { filter { it.coordinates.x < coordinates.x && it.coordinates.y == coordinates.y }.copy() } } } fun Forest.getViewableFrom(tree: Tree) = getTreesAround(tree.coordinates).map { (orientation, trees) -> when (orientation) { Orientation.NORTH, Orientation.WEST -> { tree.canSee(trees.reversed().copy()) } Orientation.EAST, Orientation.SOUTH -> { tree.canSee(trees.copy()) } } } enum class Orientation { NORTH, EAST, SOUTH, WEST } //+---> x N //| | //| O--+--E //| | //v y S
0
Kotlin
0
0
e82699a06156e560bded5465dc39596de67ea007
3,305
AoC-2022
Creative Commons Zero v1.0 Universal
src/Day11.kt
oleskrede
574,122,679
false
{"Kotlin": 24620}
fun main() { class Monkey( val id: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val handleWorryLevel: (Long) -> Long, val test: (Long) -> Int, val monkies: List<Monkey>, ) { var activityCounter = 0L fun takeTurn() { while (items.isNotEmpty()) { activityCounter++ var worryLevel = items.removeAt(0) worryLevel = operation(worryLevel) worryLevel = handleWorryLevel(worryLevel) val receivingMonkeyId = test(worryLevel) monkies[receivingMonkeyId].items.add(worryLevel) } } } fun toOperation(operatorToken: String, operandToken: String): (Long) -> Long { val operator = if (operatorToken == "+") { a: Long, b: Long -> a + b } else { a: Long, b: Long -> a * b } if (operandToken == "old") { return { old: Long -> operator(old, old) } } else { val constant = operandToken.toLong() return { old: Long -> operator(old, constant) } } } fun handleMonkeyBusiness(input: List<String>, numRounds: Int, handleWorryLevel: (Long) -> Long): Long { val monkies = mutableListOf<Monkey>() var commonFactor = 1L input.filter { it.isNotBlank() }.windowed(size = 6, step = 6).forEach { monkeyInfo -> val id = monkeyInfo[0].removeSuffix(":").split(" ").last().toInt() val startingItems = monkeyInfo[1].split(": ").last().split(", ").map { it.toLong() } val operationTokens = monkeyInfo[2].split(" ").takeLast(2) val operation = toOperation(operationTokens[0], operationTokens[1]) val testValue = monkeyInfo[3].split(" ").last().toLong() commonFactor *= testValue val testTrueMonkey = monkeyInfo[4].split(" ").last().toInt() val testFalseMonkey = monkeyInfo[5].split(" ").last().toInt() val test = { worryLevel: Long -> if (worryLevel % testValue == 0L) testTrueMonkey else testFalseMonkey } val monkey = Monkey(id, startingItems.toMutableList(), operation, handleWorryLevel, test, monkies) monkies.add(monkey) } repeat(numRounds) { monkies.forEach { monkey -> monkey.takeTurn() } } val sortedActivityCounters = monkies.map { it.activityCounter }.sortedDescending() return sortedActivityCounters[0] * sortedActivityCounters[1] } fun part1(input: List<String>): Long { return handleMonkeyBusiness( input = input, numRounds = 20, handleWorryLevel = { wl: Long -> wl / 3 } ) } fun part2(input: List<String>): Long { val commonFactor = input .filter { it.contains("divisible by") } .map { it.split(" ").last().toLong() } .reduce { acc, testValue -> acc * testValue } return handleMonkeyBusiness( input = input, numRounds = 10_000, handleWorryLevel = { wl: Long -> wl % commonFactor } ) } val testInput = readInput("Day11_test") test(part1(testInput), 10605L) test(part2(testInput), 2713310158L) val input = readInput("Day11") timedRun { part1(input) } timedRun { part2(input) } }
0
Kotlin
0
0
a3484088e5a4200011335ac10a6c888adc2c1ad6
3,384
advent-of-code-2022
Apache License 2.0
jvm/src/main/kotlin/io/prfxn/aoc2021/day15.kt
prfxn
435,386,161
false
{"Kotlin": 72820, "Python": 362}
// Chiton (https://adventofcode.com/2021/day/15) package io.prfxn.aoc2021 fun main() { fun getMinRisk(rlm: List<List<Int>>, start: CP, end: CP): Int { val riskAndPrevOf = PriorityMap(sequenceOf(start to (0 to start))) { (a, _), (b, _) -> a - b } val visited = mutableSetOf<CP>() fun getUnvisitedNeighbors(cp: CP) = cp.let { (r, c) -> sequenceOf(r - 1 to c, r + 1 to c, r to c - 1, r to c + 1) .filter { (r, c) -> r in rlm.indices && c in rlm[0].indices } .filterNot(visited::contains) } return generateSequence { if (end in visited) null else { val (here, riskAndVia) = riskAndPrevOf.extract() val (riskToHere, _) = riskAndVia getUnvisitedNeighbors(here).forEach { next -> val (nr, nc) = next val riskToNextViaHere = riskToHere + rlm[nr][nc] if (next !in riskAndPrevOf || riskToNextViaHere < riskAndPrevOf[next]!!.first) riskAndPrevOf[next] = riskToNextViaHere to here } visited.add(here) riskToHere } }.last() } fun getMinRisk(rlm: List<List<Int>>) = getMinRisk(rlm, 0 to 0, (rlm.size - 1) to (rlm[0].size - 1)) val rlm1 = textResourceReader("input/15.txt").readLines() .map { ln -> ln.map { it.digitToInt() } } val answer1 = getMinRisk(rlm1) val rlm2 = (0 until rlm1.size * 5).map { r2 -> val tr = r2 / rlm1.size val r = r2 % rlm1.size (0 until rlm1[0].size * 5).map { c2 -> val tc = c2 / rlm1[0].size val c = c2 % rlm1[0].size ((rlm1[r][c] - 1 + tr + tc) % 9) + 1 } } val answer2 = getMinRisk(rlm2) sequenceOf(answer1, answer2).forEach(::println) } /** output 595 2914 */
0
Kotlin
0
0
148938cab8656d3fbfdfe6c68256fa5ba3b47b90
1,979
aoc2021
MIT License
src/main/kotlin/days/Day7.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days class Day7 : Day(7) { private val hands = inputList.map { it.split(' ') }.map { (cards, bid) -> Hand(cards, bid.toInt()) } override fun partOne(): Any { return getTotalWinnings(hands, false) } override fun partTwo(): Any { return getTotalWinnings(hands, true) } private fun getTotalWinnings(hands: List<Hand>, jIsJoker: Boolean): Int { return rank(hands, jIsJoker).foldIndexed(0) { index, total, hand -> total + (hand.bid * (index + 1)) } } fun rank(hands: List<Hand>, jIsJoker: Boolean): List<Hand> { return hands.sortedWith { h1, h2 -> val h1Type = h1.getType(jIsJoker) val h2Type = h2.getType(jIsJoker) if (h1Type != h2Type) h2Type.ordinal - h1Type.ordinal else { val firstDifference = h1.cards.zip(h2.cards).first { it.first != it.second } strength(firstDifference.first, jIsJoker) - strength(firstDifference.second, jIsJoker) } } } private fun strength(card: Char, jIsJoker: Boolean): Int { return when (card) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> if (jIsJoker) 1 else 11 'T' -> 10 else -> card.digitToInt() } } data class Hand(val cards: String, val bid: Int = 0) { fun getType(jIsJoker: Boolean): HandType { var cards = cards if (jIsJoker && cards.contains('J') && cards.count { it == 'J' } != 5) { val mcc = cards.filterNot { it == 'J' }.map { c -> cards.count { c == it } to c }.maxBy { it.first }.second cards = cards.replace('J', mcc) } val set = cards.toSet() return when (set.size) { 1 -> HandType.FIVE_KIND 2 -> { if (set.any { c -> cards.count { c == it } == 4 }) HandType.FOUR_KIND else HandType.FULL_HOUSE } 3 -> { if (set.any { c -> cards.count { c == it } == 3 }) HandType.THREE_KIND else HandType.TWO_PAIR } 4 -> HandType.ONE_PAIR else -> HandType.HIGH_CARD } } } enum class HandType { FIVE_KIND, FOUR_KIND, FULL_HOUSE, THREE_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
2,420
aoc-2023
Creative Commons Zero v1.0 Universal
app/src/main/kotlin/com/engineerclark/advent2022/Day02.kt
engineerclark
577,449,596
false
{"Kotlin": 10394}
package com.engineerclark.advent2022 import com.engineerclark.advent2022.utils.readInput import com.engineerclark.advent2022.utils.readTestInput fun main() { // challenge 1 val rounds = readRounds(readInput(2)) println("Day 2, Challenge 1 -- My total points: ${rounds.totalScores().myPoints}") // challenge 2 val decodedRounds = readEncodedRounds(readInput(2)) println("Day 2, Challenge 2 -- My total points: ${decodedRounds.totalScores().myPoints}") } fun readMove(moveChar: String): Move = when(moveChar) { "A", "X" -> Move.rock "B", "Y" -> Move.paper "C", "Z" -> Move.scissors else -> throw RuntimeException("Unrecognized move") } fun readEncodedMove(opponentMove: Move, moveChar: String): Move = when(moveChar) { "X" -> Move.values().first { move -> move.against(opponentMove) == Outcome.lost } "Y" -> opponentMove "Z" -> Move.values().first { move -> move.against(opponentMove) == Outcome.won } else -> throw RuntimeException("Unrecognized move") } fun readRound(line: String): Round { val moveChars = line.split(" ") return Round(line, readMove(moveChars[0]), readMove(moveChars[1])) } fun readEncodedRound(line: String): Round { val moveChars = line.split(" ") val opponentMove = readMove(moveChars[0]) return Round(line, opponentMove, readEncodedMove(opponentMove, moveChars[1])) } fun readRounds(input: String): List<Round> = input.trim().split("\n").map { readRound (it.trim()) } fun readEncodedRounds(input: String): List<Round> = input.trim().split("\n").map { readEncodedRound(it.trim()) } enum class Outcome(val value: Int) { lost(0), draw(3), won(6) } enum class Move(val value: Int) { rock(1), paper(2), scissors(3) } fun Move.against(opponentMove: Move): Outcome = when ((this.value - opponentMove.value - 1) % 3) { -1 -> Outcome.draw 0 -> Outcome.won else -> Outcome.lost } fun playerScore(move: Move, outcome: Outcome): Int = move.value + outcome.value data class Round(val source: String, val opponentMove: Move, val myMove: Move) { val scores: Scores = Scores ( playerScore(myMove, myMove.against(opponentMove)), playerScore(opponentMove, opponentMove.against(myMove)) ) } data class Scores (val myPoints: Int, val opponentPoints: Int) fun List<Scores>.totals() = this.reduce { total, score -> Scores(total.myPoints + score.myPoints, total.opponentPoints + score.opponentPoints) } fun List<Round>.totalScores() = this.map { it.scores }.totals()
0
Kotlin
0
0
3d03ab2cc9c83b3691fede465a6e3936e7c091e9
2,504
advent-of-code-2022
MIT License
src/year2022/day13/Day13.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day13 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day13_test") check(part1(testInput), 13) check(part2(testInput), 140) val input = readInput("2022", "Day13") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int = input.toPairs() .mapIndexed { i, p -> val (left, right) = p val inOrder = compareSignals(left, right) == -1 inOrder to i + 1 } .filter { it.first } .sumOf { it.second } private fun part2(input: List<String>): Int { val packet1 = "[[2]]" val packet2 = "[[6]]" val sortedInput = (input + packet1 + packet2).filter { it.isNotEmpty() }.sortedWith(signalComparator) val packetPos1 = sortedInput.indexOf(packet1) + 1 val packetPos2 = sortedInput.indexOf(packet2) + 1 return packetPos1 * packetPos2 } private val signalComparator = Comparator<String> { a, b -> compareSignals(a, b) } private fun compareSignals(left: String, right: String): Int { val leftSignal = left.removeOuterBrackets() val rightSignal = right.removeOuterBrackets() var index = 0 var leftPacket = leftSignal.getPacket(index) var rightPacket = rightSignal.getPacket(index) while (leftPacket != null && rightPacket != null) { if (leftPacket.isArray() || rightPacket.isArray()) { val result = compareSignals(leftPacket, rightPacket) if (result != 0) return result } else { val comparison = leftPacket.toInt().compareTo(rightPacket.toInt()) if (comparison != 0) return comparison } index++ leftPacket = leftSignal.getPacket(index) rightPacket = rightSignal.getPacket(index) } return when { leftPacket == null && rightPacket != null -> -1 leftPacket != null -> 1 else -> 0 } } private fun List<String>.toPairs() = (this + "").chunked(3).map { Pair(it[0], it[1]) } private fun String.isArray() = startsWith("[") private fun String.removeOuterBrackets() = if (isArray()) substring(1, lastIndex) else this private fun String.getPacket(index: Int): String? { if (isEmpty()) return null var brackets = 0 val commas = mutableListOf<Int>() forEachIndexed { i, char -> when (char) { '[' -> brackets++ ']' -> brackets-- ',' -> if (brackets == 0) commas += i } } if (index > commas.size) return null val start = if (index == 0) 0 else commas[index - 1] + 1 val end = if (index > commas.lastIndex) length else commas[index] return substring(start, end) }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,723
AdventOfCode
Apache License 2.0
src/Day15.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import kotlin.math.abs data class Sensor(val source: Pair<Int, Int>, val target: Pair<Int, Int>, val radius: Int) { fun inRange(other: Pair<Int, Int>): Boolean { return (abs(source.first - other.first) + abs(source.second - other.second)) <= radius } } fun readSensor(input: List<String>): List<Sensor> { val xPattern = Regex("x=(-?\\d*)") val yPattern = Regex("y=(-?\\d*)") return input.map { line -> val (x1, x2) = xPattern.findAll(line).map { it.groupValues[1].toInt() }.toList() val (y1, y2) = yPattern.findAll(line).map { it.groupValues[1].toInt() }.toList() val radius = abs(x1 - x2) + abs(y1 - y2) Sensor(x1 to y1, x2 to y2, radius) } } fun main() { fun part1(input: List<Sensor>, y: Int): Int { val covered = mutableSetOf<Int>() for (sensor in input) { val (x1, y1) = sensor.source val yDist = abs(y1 - y) if (yDist > sensor.radius) continue val xDist = sensor.radius - yDist covered += (x1 - xDist)..(x1 + xDist) } return covered.size - input.map { it.target }.filter { it.second == y }.toSet().size } fun part2(input: List<Sensor>, range: IntRange): Long { for (sensor in input) { // extend each sensor by 1, see if it's contained in other sensors or not for (i in -sensor.radius - 1 .. sensor.radius + 1) { val x = sensor.source.first + i val dy = sensor.radius - abs(i) + 1 for (y in arrayOf(sensor.source.second - dy, sensor.source.second + dy)) { if (x !in range) continue if (y !in range) continue if (input.all { !it.inRange(x to y) }) { println("${x to y}") return x * 4_000_000L + y } } } } return 0 } val test = readInput("Day15_test") val testSensors = readSensor(test) println(testSensors) println(part1(testSensors, 10)) println(part2(testSensors, 0..20)) val input = readInput("Day15") val inputSensors = readSensor(input) println(inputSensors) println(part1(inputSensors, 2_000_000)) println(part2(inputSensors, 0..4_000_000)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
2,322
Advent-Of-Code-2022
Apache License 2.0
src/Day07.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
data class Directory(val name: String, val parent: Directory? = null) { private val files = mutableMapOf<String, Int>() val children = mutableMapOf<String, Directory>() fun addFile(size: Int, name: String) = files.putIfAbsent(name, size) fun addChild(directory: Directory) = children.putIfAbsent(directory.name, directory) fun getSize(): Int = files.values.sum() + children.values.sumOf { it.getSize() } } fun String.isCD() = startsWith("$ cd") fun String.isDir() = startsWith("dir") fun String.isFile() = first().isDigit() fun String.toFile() = split(" ").first().toInt() to split(" ")[1] fun main() { fun buildTree(input: List<String>): Directory { // cd ==> add dir to stack OR pop from stack // ls ==> dir contents // dir _x_ ==> child dir to curr dir // file ==> add to file size for dir val root = Directory("/") var cwd = root input.drop(1).forEach { when { it.isDir() -> cwd.addChild(Directory(it.drop(3).trim(), parent = cwd)) it.isFile() -> cwd.addFile(it.toFile().first, it.toFile().second) it == "$ cd .." -> cwd = cwd.parent!! it.isCD() -> cwd = cwd.children[it.drop(4).trim()]!! } } return root } fun part1(input: List<String>): Int { val root = buildTree(input) val q = ArrayDeque<Directory>().apply { addFirst(root) } var total = 0 while (q.isNotEmpty()) { val d = q.removeFirst() val size = d.getSize() if (size <= 100_000) { total += size } d.children.values.forEach { q.addFirst(it) } } return total } fun part2(input: List<String>): Int { val root = buildTree(input) val targetSize = 30_000_000 - (70_000_000 - root.getSize()) var total = Int.MAX_VALUE val q = ArrayDeque<Directory>().apply { addFirst(root) } while (q.isNotEmpty()) { val d = q.removeFirst() val size = d.getSize() if (size >= targetSize) { total = total.coerceAtMost(size) } d.children.values.forEach { q.addFirst(it) } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
2,578
advent-of-code-2022
Apache License 2.0
src/y2023/Day02.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.product import util.readInput import util.timingStatistics object Day02 { private fun parse(input: List<String>): List<List<Map<String, Int>>> { return input.map { line -> line.substringAfter(": ").split("; ").map { game -> game.split(", ").associate { colorCount -> val (count, color) = colorCount.split(" ") color to count.toInt() } } } } fun part1(input: List<String>, target: Map<String, Int>): Int { val games = parse(input) val maxGameResults = games.map { game -> target.keys.associateWith { color -> game.maxOf { it[color] ?: 0 } } } return maxGameResults .mapIndexedNotNull { index, maxes -> if (target.all { (color, count) -> (maxes[color] ?: 0) <= count }) { index + 1 } else { null } }.sum() } private val colors = listOf("red", "green", "blue") fun part2(input: List<String>): Int { val games = parse(input) val maxGameResults = games.map { game -> colors.associateWith { color -> game.maxOf { it[color] ?: 0 } } } return maxGameResults.sumOf { maxes -> maxes.values.product() } } } fun main() { val target = mapOf("red" to 12, "green" to 13, "blue" to 14) 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().split("\n") println("------Tests------") println(Day02.part1(testInput, target)) println(Day02.part2(testInput)) println("------Real------") val input = readInput("resources/2023/day02") println("Part 1 result: ${Day02.part1(input, target)}") println("Part 2 result: ${Day02.part2(input)}") timingStatistics { Day02.part1(input, target) } timingStatistics { Day02.part2(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
2,333
advent-of-code
Apache License 2.0
src/Day09.kt
Xacalet
576,909,107
false
{"Kotlin": 18486}
/** * ADVENT OF CODE 2022 (https://adventofcode.com/2022/) * * Solution to day 9 (https://adventofcode.com/2022/day/9) * */ import kotlin.math.abs private data class Point(val x: Int, val y: Int) { operator fun minus(otherPoint: Point): Point = Point(x - otherPoint.x, y - otherPoint.y) } private class Knot( var position: Point = Point(0, 0), val registerVisitedPositions: Boolean = false, ) { var visitedPositions: MutableSet<Point> = mutableSetOf(position) fun move(x: Int = position.x, y: Int = position.y) { position = Point(x, y) if (registerVisitedPositions) { visitedPositions += position } } } fun main() { fun solve(motions: List<String>, knotCount: Int): Int { val knots = List(knotCount) { index -> Knot(registerVisitedPositions = index == knotCount - 1) } val head = knots.first() val tail = knots.last() motions.forEach { direction -> when (direction) { "L" -> head.move(x = head.position.x - 1) "R" -> head.move(x = head.position.x + 1) "U" -> head.move(y = head.position.y + 1) "D" -> head.move(y = head.position.y - 1) } knots.windowed(2).forEach { (knot, nextKnot) -> (knot.position - nextKnot.position).takeIf { diff -> abs(diff.x) > 1 || abs(diff.y) > 1 }?.let { diff -> nextKnot.move( x = knot.position.x + when { diff.x > 1 -> -1 diff.x < -1 -> 1 else -> 0 }, y = knot.position.y + when { diff.y > 1 -> -1 diff.y < -1 -> 1 else -> 0 } ) } } } return tail.visitedPositions.count() } val motions = buildList { readInputLines("day09_dataset").forEach { line -> "([RLUD]) (\\d+)".toRegex().find(line)!!.destructured.let { (direction, steps) -> repeat((1..steps.toInt()).count()) { add(direction) } } } } solve(motions, 2).println() solve(motions, 10).println() }
0
Kotlin
0
0
5c9cb4650335e1852402c9cd1bf6f2ba96e197b2
2,333
advent-of-code-2022
Apache License 2.0
kotlin/src/katas/kotlin/leetcode/shortest_subarray/ShortestSubarray.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.shortest_subarray import datsok.shouldEqual import org.junit.jupiter.api.Test import java.io.File import kotlin.collections.ArrayDeque import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.forEach import kotlin.collections.indices import kotlin.collections.isNotEmpty import kotlin.collections.lastIndex import kotlin.collections.map import kotlin.collections.sliceArray import kotlin.collections.sum import kotlin.collections.toIntArray // https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k // // Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. // If there is no non-empty subarray with sum at least K, return -1. // // Example 1: // Input: A = [1], K = 1 // Output: 1 // // Example 2: // Input: A = [1,2], K = 4 // Output: -1 // // Example 3: // Input: A = [2,-1,2], K = 3 // Output: 3 // [10, 5, 8, 9, 11] <- prefix sum // [10, -5, 3, 1, 2] // f t // [10, -5, -2, -1, 1] <- prefix sum // [10, -15, 3, 1, 2] // f t fun shortestSubarray_(ints: IntArray, minSum: Int): Int { return ints.findShortestSubarray_bruteForce(minSum = minSum)?.size ?: -1 } fun IntArray.findShortestSubarray_bruteForce(minSum: Int): IntArray? { val subArrays = sequence { (0..lastIndex).forEach { i1 -> (i1..lastIndex).forEach { i2 -> yield(sliceArray(i1..i2)) } } } return subArrays .filter { it.sum() >= minSum } .minByOrNull { it.size } } class MonoQueue<T : Comparable<T>> { private val deque = ArrayDeque<T>() fun addLast(element: T) { while (deque.isNotEmpty() && element <= deque.last()) { deque.removeLast() } deque.addLast(element) } fun removeFirstWhile(f: (T) -> Boolean): List<T> { val removed = ArrayList<T>() while (deque.isNotEmpty() && f(deque.first())) { removed.add(deque.removeFirst()) } return removed } } fun shortestSubarray(ints: IntArray, minSum: Int): Int { data class Entry(val index: Int, val prefixSum: Long): Comparable<Entry> { override fun compareTo(other: Entry) = prefixSum.compareTo(other.prefixSum) } val monoq = MonoQueue<Entry>() val candidates = ints.prefixSum().flatMapIndexed { index, prefixSum -> monoq.addLast(Entry(index, prefixSum)) monoq.removeFirstWhile { prefixSum - it.prefixSum >= minSum } .map { index - it.index } } return candidates.minOrNull() ?: -1 } private fun IntArray.prefixSum(): LongArray { val result = LongArray(size + 1) indices.forEach { i -> result[i + 1] = result[i] + this[i] } return result } fun shortestSubarray__(ints: IntArray, minSum: Int): Int { val prefixSum = ints.prefixSum() val minSize = sequence { val monoq = ArrayDeque<Int>() prefixSum.indices.forEach { toIndex -> while (monoq.isNotEmpty() && prefixSum[monoq.last()] >= prefixSum[toIndex]) { monoq.removeLast() } monoq.addLast(toIndex) while (monoq.isNotEmpty() && prefixSum[toIndex] - prefixSum[monoq.first()] >= minSum) { val fromIndex = monoq.removeFirst() yield(fromIndex..toIndex) } } }.minOfOrNull { it.last - it.first } return minSize ?: -1 } class Examples { @Test fun `some examples`() { shortestSubarray(intArrayOf(1), minSum = 1) shouldEqual 1 shortestSubarray(intArrayOf(1, 2), minSum = 4) shouldEqual -1 shortestSubarray(intArrayOf(2, -1, 2), minSum = 3) shouldEqual 3 shortestSubarray(intArrayOf(2, -1, 3, 5), minSum = 3) shouldEqual 1 shortestSubarray(intArrayOf(2, -1, 3, 9), minSum = 10) shouldEqual 2 } @Test fun `large input`() { val (intArray, k) = File("src/katas/kotlin/leetcode/shortest_subarray/large-testcase.txt") .readLines().let { (inputLine, minSumLine) -> Pair( inputLine.drop(1).dropLast(1).split(",").map { it.toInt() }.toIntArray(), minSumLine.toInt() ) } shortestSubarray(intArray, k) shouldEqual 25813 } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
4,328
katas
The Unlicense
src/day11/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day11 import readInput import splitBy fun main() { fun part1(input: List<String>): Long { val monkeys = Monkeys.ofNotes(input) return monkeys.start(20, 3).sumOfTwoMostActive() } fun part2(input: List<String>): Long { val monkeys = Monkeys.ofNotes(input) return monkeys.start(10000, 1).sumOfTwoMostActive() } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) } class Monkeys( private val monkeys: List<Monkey> ) { private val commonDivisor = monkeys.map { it.throwCondition.divisor }.reduce(Int::times) fun start(rounds: Int, divisor: Int): Monkeys { repeat(rounds) { monkeys.forEach { it.takeTurn(monkeys, divisor, commonDivisor) } } return this } fun sumOfTwoMostActive() = monkeys .sortedByDescending(Monkey::inspected) .take(2) .map(Monkey::inspected) .reduce(Long::times) companion object { fun ofNotes(notes: List<String>): Monkeys { return Monkeys(notes.splitBy(String::isBlank).map(Monkey::ofNotes)) } } } data class ItemToThrow(val level: Long, val toMonkey: Int) data class ThrowCondition( val divisor: Int, val onTrue: Int, val onFalse: Int, ) { fun chooseMonkeyAndItem(level: Long): ItemToThrow { return if (level.rem(divisor) == 0L) ItemToThrow(level, onTrue) else ItemToThrow(level, onFalse) } } data class Monkey( val id: Int, val items: MutableList<Long>, val inspect: (Long) -> Long, val throwCondition: ThrowCondition, var inspected: Long = 0 ) { fun takeTurn(monkeys: List<Monkey>, divisor: Int, commonDivisor: Int) { fun throwToOther(item: ItemToThrow) = monkeys[item.toMonkey].items.add(item.level) inspected += items .asSequence() .map(inspect) .map { bored(it, divisor, commonDivisor) } .map(throwCondition::chooseMonkeyAndItem) .onEach(::throwToOther) .count() items.clear() } private fun bored(level: Long, divisor: Int, commonDivisor: Int): Long { return (level / divisor) % commonDivisor } companion object { fun ofNotes(notes: List<String>): Monkey { val id = notes.first().substringAfter(" ").substringBefore(":").toInt() val (st, op, tst, tr, fl) = notes.slice(1..notes.lastIndex) val startingItems = st.substringAfter(": ").split(", ").mapTo(ArrayDeque()) { it.toLong() } val operation = op.substringAfter(": ") val test = tst.substringAfter(": ") val condition = ThrowCondition( test.substringAfter("divisible by ").toInt(), tr.substringAfter(": ").substringAfter("throw to monkey ").toInt(), fl.substringAfter(": ").substringAfter("throw to monkey ").toInt() ) return Monkey( id = id, items = startingItems, inspect = operation.toWorryOp(), throwCondition = condition ) } } } private fun String.toWorryOp(): (Long) -> Long { val assignment = substringAfter(" = ") val op = assignment[assignment.indexOfAny("*+-/".toCharArray())] val first = substringAfter(" = ").substringBefore(op).trim() val second = substringAfter(op).trim() fun toVar(old: Long, variable: String): Long = when (variable) { "old" -> old else -> variable.toLong() } return { old -> when (op) { '*' -> toVar(old, first) * toVar(old, second) '+' -> toVar(old, first) + toVar(old, second) '-' -> toVar(old, first) - toVar(old, second) '/' -> toVar(old, first) / toVar(old, second) else -> error(op) } } }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
3,954
AoC-2022
Apache License 2.0
src/year2023/day08/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2023.day08 import arrow.core.nonEmptyListOf import io.kotest.matchers.shouldBe import utils.ProblemPart import utils.cyclical import utils.findCycle import utils.leastCommonMultiple import utils.leastCommonMultipleOf import utils.readInputs import utils.runAlgorithm fun main() { val (realInput, testInputs) = readInputs(2023, 8, "test_input_2", transform = ::parse) runAlgorithm( realInput = realInput, testInputs = testInputs, part1 = ProblemPart( expectedResultsForTests = nonEmptyListOf(2, 6), algorithm = { (steps, map) -> part1(steps, map) }, ), part2 = ProblemPart( expectedResultsForTests = nonEmptyListOf(2, 3), algorithm = { (steps, map) -> part2(steps, map) }, ), ) } private fun parse(input: List<String>): Pair<String, Map<String, Pair<String, String>>> { return input.first() to input.asSequence() .drop(2) .mapNotNull(parsingRegex::matchEntire) .map { it.groupValues } .associate { (_, nodeId, leftNodeId, rightNodeId) -> nodeId to (leftNodeId to rightNodeId) } } private val parsingRegex = "([A-Z]{3}) = \\(([A-Z]{3}), ([A-Z]{3})\\)".toRegex() private fun part1(steps: String, map: Map<String, Pair<String, String>>): Int { return steps.asSequence().cyclical() .runningFold("AAA") { currentNode, direction -> val (leftNode, rightNode) = map.getValue(currentNode) if (direction == 'L') leftNode else rightNode } .takeWhile { it != "ZZZ" } .count() } private fun part2(steps: String, map: Map<String, Pair<String, String>>): Long { val endCyclePositions = map.mapValues { (start, _) -> steps.fold(start) { currentPosition, nextStep -> val (left, right) = map.getValue(currentPosition) if (nextStep == 'R') right else left } } return map.keys.asSequence() .filter { it.last() == 'A' } .map { generateSequence(it, endCyclePositions::get).findCycle() } .leastCommonMultipleOf { it.loopSize.toLong() } .let { it * steps.length } }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
2,169
Advent-of-Code
Apache License 2.0
src/Day12.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
import java.util.* fun main() { fun part1(input: List<String>): Int { val (graph, start) = parseInput(input, 'S') val path = bfs( graph = graph, start = start, isAdjacentValid = { current, adj -> adj.value - current.value <= 1 }, isDestination = { current -> current.char == 'E' } ) return path.size } fun part2(input: List<String>): Int { val (graph, start) = parseInput(input, 'E') val path = bfs( graph = graph, start = start, isAdjacentValid = { current, adj -> current.value - adj.value <= 1 }, isDestination = { current -> current.value == 0 } ) return path.size } val input = readInput("Day12") println(part1(input)) println(part2(input)) } private typealias Graph = Map<Int, MutableMap<Int, Node>> private data class Node(val x: Int, val y: Int, val value: Int, val char: Char) private fun parseInput(input: List<String>, start: Char): Pair<Graph, Node> { val nodes = mutableMapOf<Int, MutableMap<Int, Node>>() var startNode: Node? = null input.forEachIndexed { y, line -> line.forEachIndexed { x, c -> val node = when (c) { 'S' -> Node(x = x, y = y, char = c, value = 0) 'E' -> Node(x = x, y = y, char = c, value = range.indexOf('z')) else -> Node(x = x, y = y, char = c, value = range.indexOf(c)) } if (node.char == start) startNode = node nodes.getOrPut(y) { mutableMapOf() }[x] = node } } return nodes to startNode!! } private fun bfs( graph: Graph, start: Node, isAdjacentValid: (Node, Node) -> Boolean, isDestination: (Node) -> Boolean ): List<Node> { val queue = LinkedList<Node>() val visited = mutableSetOf<Node>() val predecessors = mutableMapOf<Node, Node?>() val distances = mutableMapOf<Node, Int>() queue.push(start) predecessors[start] = null distances[start] = 0 while (queue.isNotEmpty()) { val node = queue.pop() val nodeDistance = distances[node]!! visited.add(node) graph.getPossibleAdjacentNodes(node, isValid = isAdjacentValid) .filter { adj -> !visited.contains(adj) } .forEach { adj -> val distance = distances[adj] if (distance == null || distance > nodeDistance + 1) { predecessors[adj] = node distances[adj] = nodeDistance + 1 queue.add(adj) } } } val path = mutableListOf<Node>() val destination = graph.values.flatMap { it.values } .filter { isDestination(it) } .minBy { distances[it] ?: Integer.MAX_VALUE } var current = destination while (predecessors[current] != null) { path.add(predecessors[current]!!); current = predecessors[current]!! } return path } private fun Map<Int, MutableMap<Int, Node>>.getPossibleAdjacentNodes( node: Node, isValid: (Node, Node) -> Boolean ): List<Node> = listOfNotNull( get(node.y - 1)?.get(node.x), get(node.y)?.get(node.x + 1), get(node.y + 1)?.get(node.x), get(node.y)?.get(node.x - 1) ).filter { adj -> isValid(node, adj) } private val range = CharRange('a', 'z')
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
3,415
aoc-2022
Apache License 2.0
src/Day05.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun List<String>.parseStacksAndInstructions(): Pair<List<Triple<Int, String, String>>, Map<String, ArrayDeque<Char>>> { val sepIndex = indexOfFirst(String::isEmpty) val stacksLines = take(sepIndex) val stacks = stacksLines.last().trim().split(" ").associateWith { ArrayDeque<Char>() } for (line in stacksLines.reversed().drop(1)) { var count = 1 for (i in 1 until line.length step 4) { val crate = line[i] if (crate != ' ') { stacks[count.toString()]!!.addLast(crate) } count++ } } val instructions = drop(sepIndex + 1) .map { ins -> ins.split(" ") .let { Triple(it[1].toInt(), it[3], it[5]) } } return instructions to stacks } fun Map<String, ArrayDeque<Char>>.joinSortedHeadsToString() = entries .sortedBy { it.key.toInt() } .joinToString(separator = "") { it.value.last().toString() } fun part1(input: List<String>): String { val (instructions, stacks) = input.parseStacksAndInstructions() instructions.forEach { (count, origin, dest) -> repeat(count) { stacks[dest]!!.addLast(stacks[origin]!!.removeLast()) } } return stacks.joinSortedHeadsToString() } fun part2(input: List<String>): String { val (instructions, stacks) = input.parseStacksAndInstructions() instructions.forEach { (count, origin, dest) -> val queue = ArrayDeque<Char>() repeat(count) { queue.addFirst(stacks[origin]!!.removeLast()) } queue.forEach { stacks[dest]!!.addLast(it) } } return stacks.joinSortedHeadsToString() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") println(part1(input)) // part 2 check(part2(testInput) == "MCD") println(part2(input)) }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
2,115
advent-of-code-2022
Apache License 2.0
src/day07/Solution.kt
abhabongse
576,594,038
false
{"Kotlin": 63915}
/* Solution to Day 7: No Space Left On Device * https://adventofcode.com/2022/day/7 */ package day07 import day07.Command.ChangeDirectory import day07.Command.ListDirectoryContent import day07.Command.ListDirectoryContent.ListDirectoryResult import utils.splitBefore import java.io.File fun main() { val fileName = // "day07_sample.txt" "day07_input.txt" val histories = readInput(fileName) val fileSizes = listFileSizes(histories) val dirSizes = computeDirSizes(fileSizes) // Part 1: directories with total size at most 100_000 val p1SumTotalSize = dirSizes .map { (_, size) -> size } .filter { it <= 100_000 } .sum() println("Part 1: $p1SumTotalSize") // Part 2: find directory just large enough to remove so that // there is enough available space to system upgrade val currentUsage = dirSizes[Path.root]!! val spaceToRemove = currentUsage - 40_000_000 val p2MatchedSize = dirSizes .map { (_, size) -> size } .filter { it >= spaceToRemove } .min() println("Part 2: $p2MatchedSize") } /** * Reads and parses input data according to the problem statement. */ fun readInput(fileName: String): List<History> { return File("inputs", fileName) .readLines() .asSequence() .map { it.trim() } .splitBefore { it.startsWith("$ ") } .map { lines -> History from lines } .toList() } /** * Obtains the mapping of file paths to their sizes * based on the list of command histories. */ fun listFileSizes(histories: List<History>): List<Pair<Path, Int>> { val fileSizes: ArrayList<Pair<Path, Int>> = ArrayList() var workingDir = Path.root for (history in histories) { when (val command = Command from history.command) { is ChangeDirectory -> { workingDir = when (command.arg) { ".." -> workingDir.parent "/" -> Path.root else -> workingDir + command.arg } } is ListDirectoryContent -> { for (historyResult in history.results) { val result = ListDirectoryResult from historyResult if (result is ListDirectoryResult.FileResult) { val path = workingDir + result.name fileSizes.add(Pair(path, result.size)) } } } } } return fileSizes } /** * Computes the mapping of container directories to their sizes * based on the files sizes information returned by [listFileSizes]. */ fun computeDirSizes(fileSizes: List<Pair<Path, Int>>): HashMap<Path, Int> { val dirSizes: HashMap<Path, Int> = HashMap() for ((path, size) in fileSizes) { var currPath = path while (currPath.isNotRoot()) { currPath = currPath.parent dirSizes[currPath] = dirSizes.getOrDefault(currPath, 0) + size } } return dirSizes }
0
Kotlin
0
0
8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb
3,039
aoc2022-kotlin
Apache License 2.0
src/Day16Part2.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
// Fast solution that builds upon Part1 // n - number of interesting valves with r > 0 // m - number of connections // t - number of time steps // // O(t * 2^n * m) time to solve Part1 // + O(3^n) time to solve Part2 fun main() { val dayId = "16" val input = readInput("Day${dayId}") class VD(val id: Int, val r: Int, val us: List<String>) var cnt = 0 val vs = HashMap<String, VD>() for (s in input) { val (v, r, t) = Regex("Valve ([A-Z][A-Z]) has flow rate=(\\d+); tunnel[s]? lead[s]? to valve[s]? ([A-Z, ]+)") .matchEntire(s)!!.groupValues.drop(1) check(vs.put(v, VD(cnt++, r.toInt(), t.split(", "))) == null) } val tl = 26 data class ST(val m: Long, val c: String) val dp = Array(tl + 1) { HashMap<ST, Int>() } fun put(t: Int, m: Long, c: String, p: Int) { val st = ST(m, c) val cur = dp[t][st] if (cur == null || p > cur) dp[t][st] = p } put(0, 0, "AA", 0) for (t in 0 until tl) { println("$t ${dp[t].size}") for ((st, p) in dp[t]) { val (m, c) = st val v = vs[c]!! val mask = 1L shl v.id if (v.r > 0 && (mask and m) == 0L) { put(t + 1, m or mask, c, p + (tl - t - 1) * v.r) } for (u in v.us) { put(t + 1, m, u, p) } } } val bm = dp[tl].toList() .groupingBy { it.first.m } .fold(0) { a, e -> maxOf(a, e.second) } val g = vs.values.filter { it.r > 0 }.map { it.id } fun find(i: Int, m1: Long, m2: Long): Int { if (i == g.size) { val b1 = bm[m1] ?: return 0 val b2 = bm[m2] ?: return 0 return b1 + b2 } val r1 = find(i + 1, m1, m2) val r2 = find(i + 1, m1 or (1L shl g[i]), m2) val r3 = find(i + 1, m1, m2 or (1L shl g[i])) return maxOf(r1, r2, r3) } val ans = find(0, 0, 0) println(ans) }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,979
aoc-2022
Apache License 2.0
2023/src/main/kotlin/day5.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parse import utils.Parser import utils.Solution import utils.tesselateWith fun main() { Day5.run() } object Day5 : Solution<Day5.Input>() { override val name = "day5" override val parser = Parser { parseInput(it) } @Parse("{state}s: {r ' ' nums}\n\n{r '\n\n' rules}") data class Input( val state: String, val nums: List<Long>, @Parse("{key}-{value}") val rules: Map<String, RuleTable>, ) // this is a bit ugly, line was {src}-to-{dst}, but we took {src} already as map key @Parse("to-{dst} map:\n{r '\n' rules}") data class RuleTable( val dst: String, val rules: List<MapRule> ) @Parse("{dstRangeStart} {srcRangeStart} {length}") data class MapRule( val dstRangeStart: Long, val srcRangeStart: Long, val length: Long, ) private fun mapRange(range: LongRange, mapRule: MapRule): LongRange { val off = mapRule.dstRangeStart - mapRule.srcRangeStart return range.first + off .. range.last + off } private fun applyRule(range: LongRange, mapRule: MapRule): Pair<LongRange?, List<LongRange>> { val rule = mapRule.srcRangeStart until (mapRule.srcRangeStart + mapRule.length) val (intersect, unmapped) = range tesselateWith rule return intersect?.let { mapRange(intersect, mapRule) } to unmapped } private tailrec fun solve( state: String, nums: List<LongRange>, ): List<LongRange> { val map = input.rules[state] ?: return nums val newNums = map.rules.fold(emptyList<LongRange>() to nums) { (mapped, unmapped), rule -> val applied = unmapped.map { applyRule(it, rule) } val newMapped = mapped + applied.mapNotNull { it.first } val newUnmapped = applied.flatMap { it.second } newMapped to newUnmapped } return solve(map.dst, newNums.first + newNums.second) } override fun part1(input: Input): Long { val inputRanges = input.nums.map { it..it } return solve("seed", inputRanges).minOf { it.first } } override fun part2(input: Input): Long { val inputRanges = input.nums.chunked(2).map { (start, len) -> start until (start + len) } return solve("seed", inputRanges).minOf { it.first } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,171
aoc_kotlin
MIT License
src/Day06.kt
laricchia
434,141,174
false
{"Kotlin": 38143}
fun firstPart06(list : List<LanternFish>) { val totalDays = 80 val updatedList = list.toMutableList() var fishToAdd : Int (0 until totalDays).map { fishToAdd = 0 updatedList.mapIndexed { index, fish -> if (fish.daysToNextBirth == 0) { fishToAdd++ } updatedList[index] = fish.decreaseNextBirth() } (0 until fishToAdd).map { updatedList.add(LanternFish(8)) } // println("Updated list at day ${it + 1}: ${updatedList.map { it.daysToNextBirth }}") } println("Lanternfish number after $totalDays: ${updatedList.size}") } fun secondPart06(list : List<LanternFish>) { val totalDays = 256 var fishMap = mutableMapOf<Int, Long>() for (i in 0 until 9) fishMap[i] = list.count { it.daysToNextBirth == i }.toLong() for (i in 0 until totalDays) { val updatedMap = fishMap.toMutableMap() for (key in fishMap.keys.sortedDescending()) { if (key > 0) { updatedMap[key - 1] = fishMap[key]!! } else { updatedMap[6] = fishMap[7]!! + fishMap[0]!! updatedMap[8] = fishMap[0]!! } } // println(updatedMap) fishMap = updatedMap } println(fishMap.values.sum()) } fun main() { val input : List<String> = readInput("Day06") val list = input.filter { it.isNotBlank() }.map { it.split(",").filter { it.isNotBlank() }.map { LanternFish(it.toInt()) } } firstPart06(list.first()) secondPart06(list.first()) } data class LanternFish(val daysToNextBirth : Int) fun LanternFish.decreaseNextBirth() : LanternFish = copy(daysToNextBirth = if (this.daysToNextBirth == 0) 6 else this.daysToNextBirth - 1)
0
Kotlin
0
0
7041d15fafa7256628df5c52fea2a137bdc60727
1,756
Advent_of_Code_2021_Kotlin
Apache License 2.0
solutions/src/Day11.kt
khouari1
573,893,634
false
{"Kotlin": 132605, "HTML": 175}
fun main() { fun part1(input: List<String>): Long { val monkeys = buildMonkeys(input) return run(20, monkeys) { monkey, itemWorryLevel -> val operation = monkey.operation(itemWorryLevel) operation / 3 } } fun part2(input: List<String>): Long { val monkeys = buildMonkeys(input) val lowestCommonMultiple = monkeys.map { it.testDivisibleBy }.reduce { acc, i -> acc * i } return run(10_000, monkeys) { monkey, itemWorryLevel -> val operation = monkey.operation(itemWorryLevel) operation % lowestCommonMultiple } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10_605L) check(part2(testInput) == 2_713_310_158) val input = readInput("Day11") println(part1(input)) println(part2(input)) } private fun buildMonkeys(input: List<String>): Array<Monkey> = input.filterNot { it == "" } .chunked(6) .map { buildMonkey(it) } .toTypedArray() private fun buildMonkey(lines: List<String>): Monkey { val (operand1, operator, operand2) = lines[2].split(" = ")[1].split(" ") val op1Function = operandFunction(operand1) val op2Function = operandFunction(operand2) val op = operatorFunction(operator) return Monkey( items = lines[1].split(":")[1] .filterNot { it.isWhitespace() } .split(",") .map { it.toLong() } .toMutableList(), operation = { old: Long -> op(op1Function(old), op2Function(old)) }, testDivisibleBy = lines[3].getLastCharAsInt(), monkeyIfTrue = lines[4].getLastCharAsInt(), monkeyIfFalse = lines[5].getLastCharAsInt(), ) } private fun String.getLastCharAsInt() = split(" ").last().toInt() private fun operandFunction(operand: String) = if (operand == "old") { old: Long -> old } else { _ -> operand.toLong() } private fun operatorFunction(operatorString: String): (Long, Long) -> Long = when (operatorString) { "*" -> { op1: Long, op2: Long -> op1 * op2 } "+" -> { op1: Long, op2: Long -> op1 + op2 } else -> throw UnsupportedOperationException("Unsupported operation = $operatorString") } private fun run( rounds: Int, monkeys: Array<Monkey>, calcNewWorryLevel: (monkey: Monkey, itemWorryLevel: Long) -> Long, ): Long { for (round in 1..rounds) { monkeys.forEach { monkey -> monkey.items.forEach { itemWorryLevel -> monkey.itemsInspected++ val newWorryLevel = calcNewWorryLevel(monkey, itemWorryLevel) val monkeyToThrowTo = when (newWorryLevel % monkey.testDivisibleBy == 0L) { true -> monkey.monkeyIfTrue false -> monkey.monkeyIfFalse } monkeys[monkeyToThrowTo].items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.sortedByDescending { it.itemsInspected } .take(2) .map { it.itemsInspected } .reduce { acc, i -> acc * i } } data class Monkey( val items: MutableList<Long>, val operation: (old: Long) -> Long, val testDivisibleBy: Int, val monkeyIfTrue: Int, val monkeyIfFalse: Int, ) { var itemsInspected: Long = 0 }
0
Kotlin
0
1
b00ece4a569561eb7c3ca55edee2496505c0e465
3,377
advent-of-code-22
Apache License 2.0
src/shmulik/klein/day02/Day02.kt
shmulik-klein
573,426,488
false
{"Kotlin": 9136}
package shmulik.klein.day02 import readInput fun main() { fun getGame(input: List<String>): List<Pair<String, String>> { val result: MutableList<Pair<String, String>> = mutableListOf() for (row in input) { val pair = row.split(" ") result.add(Pair(pair[0], pair[1])) } return result.toList() } fun part1(input: List<String>): Int { val list: List<Pair<String, String>> = getGame(input) return list.stream().map { Pair(Choice.convert(it.first), Choice.convert(it.second)) } .mapToInt { p -> Choice.result(p.first, p.second) + p.second.value }.sum() } fun part2(input: List<String>): Int { val list: List<Pair<String, String>> = getGame(input) return list.stream().map { Pair(Choice.convert(it.first), Outcome.valueOf(it.second)) } .mapToInt { p -> p.second.result(p.first) }.sum() } val input = readInput("shmulik/klein/day02/Day02_test") val result1 = part1(input) println(result1) val result2 = part2(input) println(result2) } enum class Outcome { X, // lose Y, // draw Z; // win fun result(c: Choice): Int { when (this.toString()) { "X" -> { return when (c) { Choice.Paper -> Choice.Rock.value + 0 Choice.Rock -> Choice.Scissors.value + 0 Choice.Scissors -> Choice.Paper.value + 0 } } "Y" -> { return c.value + 3 } "Z" -> { return when (c) { Choice.Paper -> Choice.Scissors.value + 6 Choice.Rock -> Choice.Paper.value + 6 Choice.Scissors -> Choice.Rock.value + 6 } } else -> throw IllegalArgumentException() } } } enum class Choice(val value: Int) { Rock(1), Paper(2), Scissors(3); companion object { fun convert(input: String): Choice { when (input) { "A", "X" -> return Rock "B", "Y" -> return Paper "C", "Z" -> return Scissors } throw IllegalArgumentException("Argument was$input") } fun result(c1: Choice, c2: Choice): Int { if (c1 == c2) { return 3 } if ((c2 == Rock && c1 == Scissors) || (c2 == Scissors && c1 == Paper) || (c2 == Paper && c1 == Rock)) { return 6 } return 0 } } }
0
Kotlin
0
0
4d7b945e966dad8514ec784a4837b63a942882e9
2,605
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Day09.kt
akowal
434,506,777
false
{"Kotlin": 30540}
fun main() { println(Day09.solvePart1()) println(Day09.solvePart2()) } object Day09 { private val heightMap = readInput("day09").map { it.map(Char::digitToInt) } fun solvePart1() = findLowPoints().sumOf { heightMap[it.x][it.y] + 1 } fun solvePart2() = findLowPoints() .map { calculateBasinSize(it) } .sortedDescending() .take(3) .reduce(Int::times) private fun findLowPoints(): List<Point> { val result = mutableListOf<Point>() for (x in 0..heightMap.lastIndex) { for (y in 0..heightMap.first().lastIndex) { val value = heightMap[x][y] val adjacentValues = adjacentPoints(x, y).mapNotNull { getOrNull(it) } if (adjacentValues.all { it > value }) { result += Point(x, y) } } } return result } private fun calculateBasinSize(start: Point): Int { val seen = mutableSetOf<Point>() val queue = ArrayDeque<Point>().also { it.add(start) } var result = 0 while (queue.isNotEmpty()) { val p = queue.removeFirst() seen.add(p) || continue result++ queue += adjacentPoints(p.x, p.y).filter { getOrNull(it)?.let { v -> v < 9 } ?: false } } return result } private fun getOrNull(p: Point): Int? = heightMap.getOrNull(p.x)?.getOrNull(p.y) private fun adjacentPoints(x: Int, y: Int) = listOf( x - 1 to y, x + 1 to y, x to y - 1, x to y + 1 ).map { (x, y) -> Point(x, y) } }
0
Kotlin
0
0
08d4a07db82d2b6bac90affb52c639d0857dacd7
1,613
advent-of-kode-2021
Creative Commons Zero v1.0 Universal
2017/src/twenty/ParticleSwarmChallenge.kt
Mattias1
116,139,424
false
null
package twenty import kotlin.math.absoluteValue class ParticleSwarmChallenge { fun closestParticleToOrigin(input: List<String>): Int { val particles = parseParticles(input) return particles.sorted().first().index } private fun parseParticles(input: List<String>): List<Particle> = input.mapIndexed { i, v -> buildParticle(i, v) } fun particlesThatDontCollide(input: List<String>): Int { val particles = parseParticles(input) return (0..10_000).fold(particles) { ps, _ -> simulateRound(ps) }.count() } private fun simulateRound(particles: List<Particle>): List<Particle> { val collidingIds: List<Int> = particles.flatMap { it.collidingParticleIds(particles) }.distinct() return particles .filter { it.index !in collidingIds } .map { it.step() } } private fun buildParticle(index: Int, input: String): Particle { val values = input.split(", ") return Particle(index, buildVec3(values[0]), buildVec3(values[1]), buildVec3(values[2])) } private fun buildVec3(input: String): Vec3 { val values = input.filter { it in ",-0123456789" }.split(',').map { it.toInt() } return Vec3(values[0], values[1], values[2]) } } class Particle(val index: Int, val p: Vec3, val v: Vec3, val a: Vec3) : Comparable<Particle> { fun step(): Particle = Particle(index, p + v + a, v + a, a) fun collidingParticleIds(particles: List<Particle>): List<Int> = particles .filter { it.index != this.index && it.p.x == this.p.x && it.p.y == this.p.y && it.p.z == this.p.z } .map { it.index } override fun compareTo(other: Particle): Int = compareValuesBy(this, other, { it.a.manhattanMagnitude }, { it.v.manhattanMagnitude }, { it.p.manhattanMagnitude }) } class Vec3(val x: Int, val y: Int, val z: Int) { val manhattanMagnitude: Int get() = x.absoluteValue + y.absoluteValue + z.absoluteValue operator fun plus(increment: Vec3): Vec3 = Vec3(x + increment.x, y + increment.y, z + increment.z) }
0
Kotlin
0
0
6bcd889c6652681e243d493363eef1c2e57d35ef
2,165
advent-of-code
MIT License
src/Day15.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
import kotlin.math.max import kotlin.math.min fun main() { data class SensorGroup(val sensor: Pair<Int, Int>, val beacon: Pair<Int, Int>, val distance: Int) fun String.parse() = "(-?\\d+)".toRegex().findAll(this).map { it.groupValues[1].toInt() }.toList().chunked(2) .map { Pair(it[0], it[1]) }.let { SensorGroup(it.first(), it.last(), it.first().manhattan(it.last())) } fun MutableList<Pair<Int, Int>>.minus(other: Pair<Int,Int>): MutableList<Pair<Int, Int>> { val values = mutableListOf<Pair<Int, Int>>() for(p in this) { if(other.first <= p.first && other.second >= p.second) continue else if(other.first >= p.first && other.first <= p.second && other.second >= p.second) values.add(p.first to other.first - 1) else if(other.first <= p.first && other.second >= p.first) values.add(other.second + 1 to p.second) else if(other.first >= p.first && other.second <= p.second) { values.add(p.first to other.first - 1) values.add(other.second + 1 to p.second) } else values.add(p) } return values } fun inRow(sensorGroup: List<SensorGroup>, row: Int, limits: Pair<Int, Int>? = null) = buildMap { for (g in sensorGroup) { val d = when { g.sensor.second >= row && g.sensor.second - g.distance <= row -> row - (g.sensor.second - g.distance) g.sensor.second <= row && g.sensor.second + g.distance >= row -> g.sensor.second + g.distance - row else -> continue } val range = if (limits != null) max(limits.first, g.sensor.first - d) to min( limits.second, g.sensor.first + d ) else g.sensor.first - d to g.sensor.first + d for (i in range.first..range.second) { this[i] = true } } } fun notInRow(sensorGroup: List<SensorGroup>, row: Int, limits: Pair<Int, Int>): MutableList<Pair<Int, Int>> { var line = mutableListOf(limits) for (g in sensorGroup) { val d = when { g.sensor.second >= row && g.sensor.second - g.distance <= row -> row - (g.sensor.second - g.distance) g.sensor.second <= row && g.sensor.second + g.distance >= row -> g.sensor.second + g.distance - row else -> continue } if (g.sensor.first - d >= limits.first && g.sensor.first - d <= limits.second || g.sensor.first + d >= limits.first && g.sensor.first + d <= limits.second) { val range = max(limits.first, g.sensor.first - d) to min(limits.second, g.sensor.first + d) line = line.minus(range) } } return line } fun part1(input: List<String>, row: Int): Int { val sensors = input.map { it.parse() } return inRow(sensors, row).size - sensors.asSequence().map { listOf(it.sensor, it.beacon) }.flatten() .filter { it.second == row }.toSet() .count() } fun part2(input: List<String>, limits: Pair<Int, Int>): Long { val sensors = input.map { it.parse() } for (i in limits.first..limits.second) { val row = notInRow(sensors, i, limits) if (notInRow(sensors, i, limits).isNotEmpty()) return row.first().first.toLong() * 4000000 + i } return 0L } val testInput = readInput("Day15_test") val input = readInput("Day15") check(part1(testInput, 10) == 26) println(part1(testInput, 10)) println(part1(input, 2000000)) println(part2(testInput, 0 to 20)) println(part2(input, 0 to 4000000)) }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
3,730
AoC-2022
Apache License 2.0
src/Day15.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
import kotlin.math.absoluteValue fun main() { val day = 15 data class Beacon(val sx: Int, val sy: Int, val bx: Int, val by: Int) { val range = (sx - bx).absoluteValue + (sy - by).absoluteValue fun isCovered(x: Int, y: Int): Boolean { val checkRange = rangeAt(y) return (checkRange >= 0) && (x >= (sx - checkRange)) && (x <= (sx + checkRange)) } fun rangeAt(y: Int): Int { return range - (sy - y).absoluteValue } } val matcher = """x=(\-?\d+), y=(\-?\d+)""".toRegex() fun parseInput(input: List<String>) = input.flatMap { matcher.findAll(it) } .map { it.groups } .map { it[1]!!.value.toInt() to it[2]!!.value.toInt() } .chunked(2) .map { (sp, bp) -> Beacon(sp.first, sp.second, bp.first, bp.second) } fun part1(input: List<String>, row: Int): Int { val sensors = parseInput(input) val minX = sensors.minOf { it.sx - it.range } val maxX = sensors.maxOf { it.sx + it.range } val beacons = sensors.filter { it.by == row } .map { it.bx } .toSet() return (minX..maxX).count { x -> beacons.contains(x).not() && sensors.any { it.isCovered(x, row) } } } fun part2(input: List<String>, max: Int): Long { val sensors = parseInput(input) var y = 0 while (y <= max) { var x = 0 while (x <= max) { val s = sensors.firstOrNull { it.isCovered(x, y) } ?: return x * 4000000L + y x = s.sx + s.rangeAt(y) + 1 } y++ } throw IllegalStateException("Too many possible locations!") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${day.pad(2)}_test") checkTest(26) { part1(testInput, 10) } checkTest(56000011) { part2(testInput, 20) } val input = readInput("Day${day.pad(2)}") solution { part1(input, 2000000) } solution { part2(input, 4000000) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
2,089
aoc22
Apache License 2.0
src/main/kotlin/aoc2017/RecursiveCircus.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2017 import komu.adventofcode.utils.nonEmptyLines fun recursiveCircusBottom(input: String): String = buildTree(input).name fun recursiveCircusBalance(input: String): Int = adjustBalance(buildTree(input), 0) // expected value does not matter at the root private fun adjustBalance(node: Node, expected: Int): Int { val nodesByWeights = node.children.groupBy { it.totalWeight }.entries // Either we had no children or the children were already in balance, we need to adjust // the weight of this node directly. if (nodesByWeights.size < 2) return node.weight - (node.totalWeight - expected) // Otherwise we assume that exactly one node has illegal weight: all nodes are grouped into two slots check(nodesByWeights.size == 2) val unbalancedNode = nodesByWeights.find { it.value.size == 1 }!!.value.single() val expectedWeight = nodesByWeights.find { it.value.size > 1 }!!.key return adjustBalance(unbalancedNode, expectedWeight) } private fun buildTree(input: String): Node { val definitions = input.nonEmptyLines().map(Definition.Companion::parse) val nodesByName = definitions.map { Node(it.name, it.weight) }.associateBy { it.name } val rootCandidates = nodesByName.values.toMutableSet() for (definition in definitions) { val node = nodesByName[definition.name]!! for (childName in definition.children) { val child = nodesByName[childName]!! node.children += child rootCandidates -= child } } return rootCandidates.single() } private class Node(val name: String, val weight: Int) { val children = mutableListOf<Node>() val totalWeight: Int get() = weight + children.sumBy { it.totalWeight } } private data class Definition(val name: String, val weight: Int, val children: List<String>) { companion object { private val regex = Regex("""(\w+) \((\d+)\)( -> (.+))?""") fun parse(s: String): Definition { val m = regex.matchEntire(s) ?: error("no match for '$s'") return Definition( name = m.groupValues[1], weight = m.groupValues[2].toInt(), children = m.groups[4]?.value?.split(", ") ?: emptyList()) } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,318
advent-of-code
MIT License
src/year2022/day21/Day21.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2022.day21 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2022", "Day21_test") check(part1(testInput), 152) check(part2(testInput), 301) val input = readInput("2022", "Day21") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Long { return parseNumberSupplierByMonkeyName(input).getValue("root")() } private fun part2(input: List<String>): Long { val map = parseNumberSupplierByMonkeyName(input) val dependentMonkeys = getMonkeysDependingOnHuman(input) val (_, monkeyA, _, monkeyB) = input.first { it.startsWith("root: ") }.split(": ").flatMap { it.split(' ') } val isMonkeyADependent = monkeyA in dependentMonkeys val dependingMonkey = if (isMonkeyADependent) monkeyA else monkeyB val targetNum = if (isMonkeyADependent) map.getValue(monkeyB)() else map.getValue(monkeyA)() val solution = binarySearchHumanNumbers(map, dependingMonkey, targetNum) ?: binarySearchHumanNumbers(map, dependingMonkey, targetNum, true) ?: error("no number found") val solutions = mutableSetOf<Long>() for (num in solution - 100..solution + 100) { map["humn"] = { num } if (targetNum == map.getValue(dependingMonkey)()) { solutions += num } } return solutions.first() } private fun binarySearchHumanNumbers( map: MutableMap<String, NumberSupplier>, monkey: String, target: Long, descending: Boolean = false, min: Long = Long.MIN_VALUE / 1_000_000, max: Long = Long.MAX_VALUE / 1_000_000, ): Long? { if (min > max) return null val mid = (min + max) / 2 map["humn"] = { mid } val num = map.getValue(monkey)() return if (num == target) mid else if (descending && num < target) binarySearchHumanNumbers(map, monkey, target, true, mid + 1, max) else if (!descending && num > target) binarySearchHumanNumbers(map, monkey, target, false, mid + 1, max) else binarySearchHumanNumbers(map, monkey, target, descending, min, mid - 1) } private fun getMonkeysDependingOnHuman(input: List<String>): Set<String> { val dependentMonkeys = mutableSetOf<String>() val queue = ArrayDeque<String>().apply { add("humn") } while (queue.isNotEmpty()) { val name = queue.removeFirst() val dependent = input.filter { name in it && !it.startsWith(name) }.map { it.substringBefore(":") } dependentMonkeys += dependent queue += dependent } return dependentMonkeys } private typealias NumberSupplier = () -> Long private fun parseNumberSupplierByMonkeyName(input: List<String>): MutableMap<String, NumberSupplier> { val map = mutableMapOf<String, NumberSupplier>() for (line in input) { val (name, job) = line.split(": ") val parts = job.split(' ') if (parts.size == 1) { val num = parts.first().toLong() map[name] = { num } } else { val (monkeyA, operationString, monkeyB) = parts val operation: Long.(Long) -> Long = when (operationString) { "+" -> Long::plus "-" -> Long::minus "*" -> Long::times "/" -> Long::div else -> error("Unknown operation $operationString") } map[name] = { map.getValue(monkeyA)().operation(map.getValue(monkeyB)()) } } } return map }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,509
AdventOfCode
Apache License 2.0
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day02.kt
loehnertz
573,145,141
false
{"Kotlin": 53239}
package codes.jakob.aoc import codes.jakob.aoc.Day02.Outcome.* import codes.jakob.aoc.Day02.RockPaperScissors.* import codes.jakob.aoc.shared.splitMultiline class Day02 : Solution() { override fun solvePart1(input: String): Any { return input .splitMultiline() .map { it.split(" ") } .map { RockPaperScissors.fromSign(it[0].first()) to RockPaperScissors.fromSign(it[1].first()) } .sumOf { (opponent, me) -> me.score + me.play(opponent).points } } override fun solvePart2(input: String): Any { return input .splitMultiline() .map { it.split(" ") } .map { RockPaperScissors.fromSign(it[0].first()) to Outcome.fromSign(it[1].first()) } .sumOf { (opponent, outcome) -> pick(opponent, outcome).score + outcome.points } } private fun pick(opponent: RockPaperScissors, outcome: Outcome): RockPaperScissors { return when { outcome == DRAW -> opponent opponent == ROCK && outcome == WIN -> PAPER opponent == ROCK && outcome == LOSE -> SCISSORS opponent == PAPER && outcome == WIN -> SCISSORS opponent == PAPER && outcome == LOSE -> ROCK opponent == SCISSORS && outcome == WIN -> ROCK opponent == SCISSORS && outcome == LOSE -> PAPER else -> error("Not possible: $opponent + $outcome") } } enum class RockPaperScissors(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun play(other: RockPaperScissors): Outcome { return when { this == other -> DRAW this == ROCK && other == PAPER -> LOSE this == ROCK && other == SCISSORS -> WIN this == PAPER && other == ROCK -> WIN this == PAPER && other == SCISSORS -> LOSE this == SCISSORS && other == ROCK -> LOSE this == SCISSORS && other == PAPER -> WIN else -> error("Not possible: $this + $other") } } companion object { fun fromSign(sign: Char): RockPaperScissors { return when (sign) { 'A' -> ROCK 'B' -> PAPER 'C' -> SCISSORS 'X' -> ROCK 'Y' -> PAPER 'Z' -> SCISSORS else -> error("Not a valid sign: $sign") } } } } enum class Outcome(val points: Int) { WIN(6), DRAW(3), LOSE(0); companion object { fun fromSign(sign: Char): Outcome { return when (sign) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> error("Not a valid sign: $sign") } } } } } fun main() = Day02().solve()
0
Kotlin
0
0
ddad8456dc697c0ca67255a26c34c1a004ac5039
3,018
advent-of-code-2022
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2023/day11/day11.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day11 import biz.koziolek.adventofcode.LongCoord import biz.koziolek.adventofcode.findInput import biz.koziolek.adventofcode.parse2DMap fun main() { val inputFile = findInput(object {}) val map = parseGalaxyMap(inputFile.bufferedReader().readLines()) println("Sum of shortest paths between every pair of galaxies in universe scaled:") println("- by 2 is: ${map.scale(2).distances.sum()}") println("- by 1 000 000: ${map.scale(1_000_000).distances.sum()}") } const val GALAXY = '#' const val VOID = '.' data class GalaxyMap(val galaxies: Set<LongCoord>) { val width = galaxies.maxOf { it.x } + 1 val height = galaxies.maxOf { it.y } + 1 val distances: List<Long> by lazy { val galaxiesList = galaxies.toList() galaxiesList .flatMapIndexed { firstIdx, firstCoord -> galaxiesList .filterIndexed { secondIndex, _ -> secondIndex > firstIdx } .map { secondCoord -> firstCoord to secondCoord } } .map { it.first.manhattanDistanceTo(it.second) } } fun scale(scale: Int = 2): GalaxyMap { val emptyColumns = (0..width) - galaxies.map { it.x }.toSet() val emptyRows = (0..height) - galaxies.map { it.y }.toSet() return GalaxyMap( galaxies = galaxies.map { oldCoord -> LongCoord( x = oldCoord.x + (scale - 1) * emptyColumns.count { it < oldCoord.x }, y = oldCoord.y + (scale - 1) * emptyRows.count { it < oldCoord.y }, ) }.toSet(), ) } override fun toString() = buildString { for (y in 0 until height) { for (x in 0 until width) { val coord = LongCoord(x, y) if (coord in galaxies) { append(GALAXY) } else { append(VOID) } } if (y != height - 1) { append("\n") } } } } fun parseGalaxyMap(lines: Iterable<String>): GalaxyMap = lines.parse2DMap() .filter { (_, char) -> char == GALAXY } .map { it.first.toLong() } .let { GalaxyMap(it.toSet()) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,348
advent-of-code
MIT License
src/Day02.kt
roxspring
573,123,316
false
{"Kotlin": 9291}
enum class Play(val score: Int) { Rock(1), Paper(2), Scissors(3); fun next(): Play = values()[(3 + ordinal + 1) % 3] fun prev(): Play = values()[(3 + ordinal - 1) % 3] } enum class Result(val score: Int) { Loss(0), Draw(3), Win(6); companion object { fun of(opponent: Play, strategy: Play): Result = when (strategy) { opponent.next() -> Win opponent.prev() -> Loss else -> Draw } } } data class Round( val opponent: Play, val strategy: Play, val result: Result ) { val score = strategy.score + result.score init { if (result != Result.of(opponent, strategy)) { throw Exception("Inconsistent round! $this should end in ${Result.of(opponent, strategy)}") } } override fun toString(): String { return "$opponent vs $strategy => $result ($score)" } } fun main() { fun part1(lines: List<String>): Int = lines .map { line -> val split = line.split(" ") val opponent = Play.values()["ABC".indexOf(split[0])] val strategy = Play.values()["XYZ".indexOf(split[1])] Round( opponent, strategy, Result.of(opponent, strategy) ) } .sumOf { it.score } fun part2(lines: List<String>): Int { return lines .map { line -> val split = line.split(" ") val opponent = Play.values()["ABC".indexOf(split[0])] val result = Result.values()["XYZ".indexOf(split[1])] Round( opponent, strategy = when (result) { Result.Draw -> opponent Result.Win -> opponent.next() Result.Loss -> opponent.prev() }, result ) } .sumOf { it.score } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) check(part2(testInput) == 12) println(part2(input)) }
0
Kotlin
0
0
535beea93bf84e650d8640f1c635a430b38c169b
2,222
advent-of-code-2022
Apache License 2.0
src/Day24.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
import java.util.BitSet import java.util.PriorityQueue import kotlin.math.abs private enum class WinDir { UP, DOWN, LEFT, RIGHT } fun main() { class StormMap(val map: Map<Pair<Int, Int>, BitSet>, val dimensions: Pair<Int, Int>) { val start = Pair(0, 1) val end = Pair(dimensions.first - 1, dimensions.second - 2) fun step(): StormMap { val newStormMap = mutableMapOf<Pair<Int, Int>, BitSet>() map.forEach { (pos, bitSet) -> val (y, x) = pos WinDir.values().filter { dir -> bitSet.get(dir.ordinal + 1) }.forEach { dir -> val (dy, dx) = when (dir) { WinDir.UP -> Pair(-1, 0) WinDir.DOWN -> Pair(1, 0) WinDir.LEFT -> Pair(0, -1) WinDir.RIGHT -> Pair(0, 1) } var next = Pair(y + dy, x + dx) if (next.first <= 0 || next.second <= 0 || next.first >= dimensions.first - 1 || next.second >= dimensions.second - 1) { next = when (dir) { WinDir.DOWN -> Pair(1, x) WinDir.UP -> Pair(dimensions.first - 2, x) WinDir.LEFT -> Pair(y, dimensions.second - 2) WinDir.RIGHT -> Pair(y, 1) } } if (next !in newStormMap) { newStormMap[next] = BitSet().apply { set(dir.ordinal + 1) } } else { newStormMap[next]!!.set(dir.ordinal + 1) } } } return StormMap(newStormMap.toMap(), dimensions) } fun destinations(y: Int, x: Int): List<Pair<Int, Int>> { return listOf( Pair(y - 1, x), Pair(y + 1, x), Pair(y, x - 1), Pair(y, x + 1), Pair(y, x), ).filter { it == start || it == end || it.first > 0 && it.first < dimensions.first - 1 && it.second > 0 && it.second < dimensions.second - 1 } .filter { it !in map } } } fun parseInput(input: List<String>): StormMap { val storms = input.mapIndexed { y, line -> line.withIndex().filter { x -> listOf('>', '<', '^', 'v').contains(x.value) }.map { x -> val winDir = when (x.value) { '>' -> WinDir.RIGHT '<' -> WinDir.LEFT '^' -> WinDir.UP 'v' -> WinDir.DOWN else -> throw IllegalArgumentException() } Pair(y, x.index) to BitSet().apply { set(winDir.ordinal + 1) } } }.flatten().toMap() return StormMap(storms, Pair(input.size, input[0].length)) } fun part1(input: List<String>): Int { val stormMap = parseInput(input) val stormAtTime = mutableListOf(stormMap) fun heuristic(pos: Pair<Int, Int>): Int { return abs(pos.first - stormMap.end.first) + abs(pos.second - stormMap.end.second) } val queue: PriorityQueue<Pair<Int, Pair<Int, Int>>> = PriorityQueue( compareBy { it.first + heuristic(it.second) }, ) queue.add(Pair(0, stormMap.start)) val visited = mutableSetOf(Pair(0, stormMap.start)) while (queue.isNotEmpty()) { val (cost, pos) = queue.poll() if (pos == stormMap.end) { return cost - 1 } if (stormAtTime.indices.last < cost) { stormAtTime.add(stormAtTime.last().step()) } stormAtTime[cost].destinations(pos.first, pos.second) .map { dest -> Pair(cost + 1, dest) } .filter { visited.add(it) } .forEach { queue.add(it) } } // no solution throw IllegalArgumentException() } fun part2(input: List<String>): Int { val stormMap = parseInput(input) val stormAtTime = mutableListOf(stormMap) val minRoundTrip = abs(stormMap.start.first - stormMap.end.first) + abs(stormMap.start.second - stormMap.end.second) fun heuristic(targetAndPos: Pair<Int, Pair<Int, Int>>): Int { val (targetId, pos) = targetAndPos return when (targetId) { 0 -> 2 * minRoundTrip + abs(pos.first - stormMap.end.first) + abs(pos.second - stormMap.end.second) 1 -> minRoundTrip + abs(pos.first - stormMap.start.first) + abs(pos.second - stormMap.start.second) 2 -> abs(pos.first - stormMap.end.first) + abs(pos.second - stormMap.end.second) else -> throw IllegalArgumentException() } } val queue: PriorityQueue<Triple<Int, Int, Pair<Int, Int>>> = PriorityQueue( compareBy { it.first + heuristic(Pair(it.second, it.third)) }, ) queue.add(Triple(0, 0, stormMap.start)) val visited = mutableSetOf(Triple(0, 0, stormMap.start)) while (queue.isNotEmpty()) { val (cost, targetId, pos) = queue.poll() var nextTargetId = targetId if (targetId == 0 && pos == stormMap.end) { nextTargetId = 1 } else if (targetId == 1 && pos == stormMap.start) { nextTargetId = 2 } else if (targetId == 2 && pos == stormMap.end) { return cost - 1 } if (stormAtTime.indices.last < cost) { stormAtTime.add(stormAtTime.last().step()) } stormAtTime[cost].destinations(pos.first, pos.second) .map { dest -> Triple(cost + 1, nextTargetId, dest) } .filter { visited.add(it) } .forEach { queue.add(it) } } // no solution throw IllegalArgumentException() } val testInput = readInput("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
6,256
aoc-2022
Apache License 2.0
src/main/kotlin/me/astynax/aoc2023kt/Day03.kt
astynax
726,011,031
false
{"Kotlin": 9743}
package me.astynax.aoc2023kt private val Pair<Int, Int>.neighbors: Iterable<Pair<Int, Int>> get() = listOf( (first - 1) to (second - 1), first to (second - 1), (first + 1) to (second - 1), (first - 1) to second, (first + 1) to second, (first - 1) to (second + 1), first to (second + 1), (first + 1) to (second + 1), ) private fun Iterable<Int>.product(): Int = fold(1) { a, b -> a * b } object Day03 { fun step1(lines: List<String>): Int = scan(lines) { c, ns -> if (!c.isDigit() && c != '.') ns.value else listOf() } fun step2(lines: List<String>): Int = scan(lines) { c, ns -> if (c == '*' && ns.value.size == 2) listOf(ns.value.product()) else listOf() } private fun scan( lines: List<String>, step: (Char, Lazy<Set<Int>>) -> Iterable<Int> ): Int { val numbers = lines.map(::findNumbers) return lines.flatMapIndexed { y, row -> row.flatMapIndexed { x, c -> step(c, lazy { (x to y).neighbors.map { (nx, ny) -> numbers[ny][nx] }.filter { it != 0 }.toSet() }) } }.sum() } fun findNumbers(line: String): List<Int> = (line + ' ').fold( listOf<Char>() to listOf<Int>() ) { (cs, ds), c -> when { c.isDigit() -> (cs + c) to ds cs.isNotEmpty() -> listOf<Char>() to ( ds + cs.joinToString("").toInt().let { v -> List(cs.size) { _ -> v } } + 0 ) else -> cs to (ds + 0) } }.second.dropLast(1) val input = lazy { Input.linesFrom("/Day03.input") } }
0
Kotlin
0
0
9771b5ccde4c591c7edb413578c5a8dadf3736e0
1,617
aoc2023kt
MIT License
src/main/kotlin/day6/Day6.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day6 import java.io.File fun parseInput(line: String) = line.split(",").map { it.toInt() } data class LanternFish(val daysToEngender: Int) { fun ageOneDay(): List<LanternFish> = if (daysToEngender == 0) listOf(LanternFish(6), LanternFish(8)) else listOf(LanternFish(daysToEngender - 1)) } fun naivelyCountLanternfishPopulationAfterNDays(listOfDays: List<Int>, days: Int): Int { tailrec fun loop(lanternFish: List<LanternFish>, remainingDays: Int): List<LanternFish> = if (remainingDays == 0) lanternFish else loop(lanternFish.flatMap { it.ageOneDay() }, remainingDays - 1) return loop(listOfDays.map { LanternFish(it) }, days).count() } fun countLanternfishPopulationAfterNDays(listOfDays: List<Int>, days: Int): Long { // cluster population by remaining days to give birth; 9 days for the first time, then 7 days val clusters = listOfDays.groupingBy { it }.eachCount() val population = Array(9) { clusters.getOrDefault(it, 0).toLong() } repeat(days) { val births = population[0] (1..8).forEach { i -> population[i - 1] = population[i] } // reduce days to give birth of population population[6] += births population[8] = births } return population.sum() } fun main() { File("./input/day6.txt").useLines { lines -> val lanternFish = parseInput(lines.first()) println("First part: ${countLanternfishPopulationAfterNDays(lanternFish, 80)}") println("Second part: ${countLanternfishPopulationAfterNDays(lanternFish, 256)}") } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
1,509
advent-of-code-2021
MIT License
src/main/kotlin/solutions/day07/Day7.kt
Dr-Horv
112,381,975
false
null
package solutions.day07 import solutions.Solver import utils.splitAtWhitespace import java.util.* data class Program(val name: String, val weight: Int, var parent: Program?, var children: List<Program>, var totalWeight: Int, var level: Int) data class Tuple(val program: Program, val diff: Int) class LevelComparator : Comparator<Program> { override fun compare(p0: Program?, p1: Program?): Int { return p1!!.level - p0!!.level } } class Day7 : Solver { override fun solve(input: List<String>, partTwo: Boolean): String { val map: Map<String, Program> = constructTree(input) val root = findRoot(map.values.first()) if (!partTwo) { return root.name } correctLevels(root) correctTotalWeights(map) val (p, diff) = findCulprit(root) return (p.weight + diff).toString() } private fun correctTotalWeights(map: Map<String, Program>) { val queue: Queue<Program> = PriorityQueue(LevelComparator()) queue.addAll(map.values) while (queue.isNotEmpty()) { val next = queue.poll() if (next.parent != null) { val parent = next.parent!! parent.totalWeight += next.totalWeight if (!queue.contains(parent)) { queue.add(parent) } } } } private fun constructTree(input: List<String>): Map<String, Program> { val map: MutableMap<String, Program> = mutableMapOf() val programsWithChildren: MutableMap<Program, List<String>> = mutableMapOf() input .map { it.split("->").map(String::trim) } .forEach { createProgramNode(it, map, programsWithChildren) } programsWithChildren.forEach { (p, cs) -> val children = cs.map { map.getValue(it) }.toList() p.children = children children.forEach { it.parent = p } } return map } private fun createProgramNode(parts: List<String>, map: MutableMap<String, Program>, programsWithChildren: MutableMap<Program, List<String>>) { val firstParts = parts[0].splitAtWhitespace() val name = firstParts[0] val weightStr = firstParts[1] val weight = weightStr.substring(1, weightStr.lastIndex).toInt() val p = Program(name, weight, null, mutableListOf(), weight, -1) map.put(name, p) if (parts.size > 1) { val children = parts[1].split(",").map(String::trim) programsWithChildren.put(p, children) } } private fun correctLevels(root: Program, level: Int = 0) { root.level = level root.children.forEach { correctLevels(it, level + 1) } } private fun findCulprit(root: Program): Tuple { val weightSorted = root.children.sortedBy { it.totalWeight } if (weightSorted.size < 3) { throw RuntimeException("Cannot determine too heavy or too light") } val first = weightSorted.first() val last = weightSorted.last() val middle = weightSorted[weightSorted.size / 2] return if (first.totalWeight != middle.totalWeight) { find(first, first.totalWeight - middle.totalWeight, { it.totalWeight }) } else { find(last, middle.totalWeight - last.totalWeight, { -it.totalWeight }) } } private fun find(p: Program, diff: Int, sortedBy: (Program) -> Int ): Tuple { val sorted = p.children.sortedBy(sortedBy) return if (sorted.first().totalWeight == sorted.last().totalWeight) { Tuple(p, diff) } else { find(sorted.first(), diff, sortedBy) } } private fun findRoot(program: Program): Program { return if (program.parent != null) { findRoot(program.parent!!) } else { program } } }
0
Kotlin
0
2
975695cc49f19a42c0407f41355abbfe0cb3cc59
3,964
Advent-of-Code-2017
MIT License
src/aoc2023/Day12.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day12" fun countArrangements(row: String, foldFactor: Int): Long { val (springsStr, groupsStr) = row.split(" ") val groupList = groupsStr.split(",").map { it.toInt() } val springs = (1..foldFactor).flatMap { listOf(springsStr) }.joinToString("?") val groups = (1..foldFactor).flatMap { groupList } val arrForState = mutableMapOf<CounterState, Long>() fun count(state: CounterState): Long { return if (state.springIndex >= springs.length) { when { state.groupIndex >= groups.size || state.groupIndex == groups.size - 1 && state.damageCount == groups[state.groupIndex] -> 1 else -> 0 } } else { when (state) { in arrForState -> arrForState.getValue(state) else -> { var arr = 0L when (springs[state.springIndex]) { '?', '.' -> { if (state.damageCount > 0 && groups[state.groupIndex] == state.damageCount) { arr += count(state.next(spring = true, group = true)) } else if (state.damageCount == 0) { arr += count(state.next(spring = true)) } } } when (springs[state.springIndex]) { '?', '#' -> { if (state.groupIndex < groups.size && state.damageCount < groups[state.groupIndex]) { arr += count(state.next(spring = true, damage = true)) } } } arrForState[state] = arr arr } } } } return count(CounterState()) } fun sumArrangements(input: List<String>, unfolded: Boolean = false) = input.sumOf { countArrangements(row = it, foldFactor = if (unfolded) 5 else 1) } fun part1(input: List<String>) = sumArrangements(input, unfolded = false) fun part2(input: List<String>) = sumArrangements(input, unfolded = true) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 21) println(part1(input)) checkValue(part2(testInput), 525152) println(part2(input)) } data class CounterState(val springIndex: Int = 0, val groupIndex: Int = 0, val damageCount: Int = 0) { fun next(spring: Boolean = false, group: Boolean = false, damage: Boolean = false) = CounterState( springIndex = springIndex + (if (spring) 1 else 0), groupIndex = groupIndex + (if (group) 1 else 0), damageCount = if (group) 0 else damageCount + (if (damage) 1 else 0), ) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
3,126
aoc-kotlin
Apache License 2.0
src/Day11.kt
a2xchip
573,197,744
false
{"Kotlin": 37206}
import java.io.File class Monkey( val items: MutableList<Long>, val worryLevelOperation: String, val worryLevelOperationValue: String, val testDivisibleBy: Int, val ifTrueThrowToMonkey: Int, val ifFalseThrowToMonkey: Int, var inspected: Int ) { companion object { fun from(monkeyStringBlock: String): Monkey { val seq = monkeyStringBlock.split("\n") val items = seq[1].split(":").last().trim().split(",").map { it.trim().toLong() } val (_, opOperation, opValue) = seq[2].split("=").last().trim().split(" ") val testDivisible = seq[3].split(" ").last().toInt() val ifTrue = seq[4].split(" ").last().trim().toInt() val ifFalse = seq[5].split(" ").last().trim().toInt() return Monkey( items.toMutableList(), opOperation, opValue, testDivisible, ifTrue, ifFalse, 0 ) } } } class Monkeys(val list: Array<Monkey>) { private val divisor = list.map { it.testDivisibleBy.toLong() }.reduce(Long::times) fun interact(times: Int, reduceWorryLevel: Boolean = true) { repeat(times) { for (monkey in list) { for (currentWorryLevel in monkey.items) { val target: Long = if (monkey.worryLevelOperationValue == "old") currentWorryLevel else monkey.worryLevelOperationValue.toLong() val newWorryLevel = if (reduceWorryLevel) calculateReducedWorryLevel( monkey, currentWorryLevel, target ) else calculateSelfPacedWorryLevel(monkey, currentWorryLevel, target) list[if (newWorryLevel % monkey.testDivisibleBy == 0L) monkey.ifTrueThrowToMonkey else monkey.ifFalseThrowToMonkey].items.add( newWorryLevel ) monkey.inspected += 1 } monkey.items.clear() } } } private fun calculateSelfPacedWorryLevel(monkey: Monkey, itemWorryLevel: Long, target: Long): Long { return calculateWorryLevel(monkey.worryLevelOperation, itemWorryLevel, target) % this.divisor } private fun calculateReducedWorryLevel(monkey: Monkey, itemWorryLevel: Long, target: Long): Long { return calculateWorryLevel(monkey.worryLevelOperation, itemWorryLevel, target) / 3L } private fun calculateWorryLevel(worryLevelOperation: String, itemWorryLevel: Long, target: Long): Long { return when (worryLevelOperation) { "*" -> itemWorryLevel * target "/" -> itemWorryLevel / target "+" -> itemWorryLevel + target "-" -> itemWorryLevel - target else -> error("Unexpected operation") } } companion object { fun create(listOfMonkeys: Array<Monkey>): Monkeys { return Monkeys(listOfMonkeys) } } } private fun List<String>.ofMonkeys(): Monkeys { return Monkeys.create(this.map { Monkey.from(it) }.toTypedArray()) } fun main() { fun readInput(name: String) = File("src", "$name.txt").readText().split("\n\n") fun part1(input: List<String>): Long { val monkeys = input.ofMonkeys() monkeys.interact(20) return monkeys.list.sortedBy { it.inspected }.map { it.inspected }.takeLast(2).fold(1) { acc, i -> acc * i } } fun part2(input: List<String>): Long { val monkeys = input.ofMonkeys() monkeys.interact(10000, false) println(monkeys.list.sortedBy { it.inspected }.map { it.inspected }.takeLast(2)) return monkeys.list.sortedBy { it.inspected }.map { it.inspected }.takeLast(2).fold(1) { acc, i -> acc * i } } val testInput = readInput("Day11_test") println("Test 1 - ${part1(testInput)}") check(part1(testInput) == 10605.toLong()) println("Test 2 - ${part2(testInput)}") check(part2(testInput) == 2713310158L) val input = readInput("Day11") println("Part 1 - ${part1(input)}") println("Part 2 - ${part2(input)}") }
0
Kotlin
0
2
19a97260db00f9e0c87cd06af515cb872d92f50b
4,078
kotlin-advent-of-code-22
Apache License 2.0
src/Day15.kt
kpilyugin
572,573,503
false
{"Kotlin": 60569}
import kotlin.math.abs fun main() { data class Point(val x: Int, val y: Int) { fun dist(other: Point) = abs(x - other.x) + abs(y - other.y) fun add(dx: Int, dy: Int) = Point(x + dx, y + dy) } class Sensor(val pos: Point, val closestBeacon: Point) fun parse(input: List<String>): List<Sensor> = input.map { line -> val (sensorPos, beaconPos) = line.split(":").map { desc -> val (x, y) = desc.substringAfter("at ").split(", ").map { it.substringAfter("=").toInt() } Point(x, y) } Sensor(sensorPos, beaconPos) } fun part1(input: List<String>, targetY: Int): Int { val sensors = parse(input) val minX = sensors.minOf { it.pos.x - it.pos.dist(it.closestBeacon) } val maxX = sensors.maxOf { it.pos.x + it.pos.dist(it.closestBeacon) } return (minX..maxX).count { x -> val point = Point(x, targetY) val isCloser = sensors.any { it.pos.dist(point) <= it.pos.dist(it.closestBeacon) } val noExisting = sensors.all { it.closestBeacon != point } isCloser && noExisting } } fun part2(input: List<String>, limit: Int): Long { val sensors = parse(input) fun check(p: Point) = p.x in 0..limit && p.y in 0..limit && sensors.all { it.pos.dist(p) > it.pos.dist(it.closestBeacon) } val result = mutableSetOf<Point>() fun walk(start: Point, dx: Int, dy: Int, size: Int) { var cur = start repeat(size) { if (check(cur)) { result += cur } cur = cur.add(dx, dy) } } for (sensor in sensors) { val pos = sensor.pos val dist = pos.dist(sensor.closestBeacon) walk(pos.add(dist + 1, 0), -1, -1, dist + 1) walk(pos.add(dist + 1, 0), -1, 1, dist + 1) walk(pos.add(-(dist + 1), 0), 1, -1, dist + 1) walk(pos.add(-(dist + 1), 0), 1, 1, dist + 1) } if (result.size != 1) throw IllegalStateException(result.toString()) val p = result.first() return p.x.toLong() * 4000000L + p.y.toLong() } val testInput = readInputLines("Day15_test") check(part1(testInput, 10), 26) check(part2(testInput, 20), 56000011L) val input = readInputLines("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
1
7f0cfc410c76b834a15275a7f6a164d887b2c316
2,510
Advent-of-Code-2022
Apache License 2.0
src/Day03.kt
arturkowalczyk300
573,084,149
false
{"Kotlin": 31119}
fun main() { fun calculateItemTypePriority(itemType: Char): Int { val charCode = itemType.code if (charCode in ('a'.code..'z'.code)) return charCode - 'a'.code + 1 else return charCode - 'A'.code + 27 return charCode } fun part1(input: List<String>): Int { var prioritiesOfMutualElementInEveryRucksack = 0 input.forEach { val compartments = it.chunked(it.length / 2) //find mutual element - assuming concept, there is only one val prioritiesOfCompartmentOne = compartments[0].toCharArray().map { char -> calculateItemTypePriority(char) } val prioritiesOfCompartmentTwo = compartments[1].toCharArray().map { char -> calculateItemTypePriority(char) } val mutualElementPriority = prioritiesOfCompartmentOne.intersect(prioritiesOfCompartmentTwo) prioritiesOfMutualElementInEveryRucksack += mutualElementPriority.toList()[0] } return prioritiesOfMutualElementInEveryRucksack } fun part2(input: List<String>): Int { //divide elves to groups of 3 val groupsOf3 = input.chunked(3) var sumOfBadgeCodes = 0 //find mutual element in every group (badge) groupsOf3.forEach {rucksackContent-> val rucksack1 = rucksackContent[0].toCharArray().map { calculateItemTypePriority(it) } val rucksack2 = rucksackContent[1].toCharArray().map { calculateItemTypePriority(it) } val rucksack3 = rucksackContent[2].toCharArray().map { calculateItemTypePriority(it) } val badgeCode = (rucksack1.intersect(rucksack2).intersect(rucksack3)).toList()[0] sumOfBadgeCodes += badgeCode } return sumOfBadgeCodes } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) val input = readInput("Day03") println(part1(input)) val testInputSecond = readInput("Day03_test_second") check(part2(testInputSecond) == 70) println(part2(input)) }
0
Kotlin
0
0
69a51e6f0437f5bc2cdf909919c26276317b396d
2,187
aoc-2022-in-kotlin
Apache License 2.0
src/Day15.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
import kotlin.math.abs import kotlin.math.max fun main() { fun getBlockedOnLine(sensors: List<List<Int>>, shouldCountUsed: Boolean, whichRow: Int, whichLimit: Int? = null): Pair<Int, Int> { val blockedRangesOnRowEvents: MutableList<Pair<Int, Int>> = mutableListOf() sensors.forEach { (x1, y1, x2, y2) -> run { val dist = abs(x1 - x2) + abs(y1 - y2) val distOnThatRow = dist - abs(whichRow - y1) if (distOnThatRow >= 0) { blockedRangesOnRowEvents.add(x1 - distOnThatRow to 1) blockedRangesOnRowEvents.add(x1 + distOnThatRow + 1 to -1) } if (y2 == whichRow && shouldCountUsed) { blockedRangesOnRowEvents.add(x2 to 0) } } } if (whichLimit != null) { blockedRangesOnRowEvents.add(whichLimit to -1000) } blockedRangesOnRowEvents.sortWith(compareBy({ it.first }, { it.second })) var answer = 0 var currentOpened = 0 var previous = if (whichLimit == null) blockedRangesOnRowEvents[0].first else 0 var firstEmpty = -1 blockedRangesOnRowEvents.forEach { (pos, type) -> run { if (currentOpened > 0) { answer += max(0, pos - previous - if (type == 0) 1 else 0) } else { if (pos > previous && whichLimit != null && previous < whichLimit) { firstEmpty = previous } } previous = max(pos, previous) currentOpened += type } } return answer to firstEmpty } fun part1(input: List<String>, whichRow: Int): Int { val sensors = input.map { it.split("=", ",", ":").mapNotNull { it2 -> it2.toIntOrNull() } } return getBlockedOnLine(sensors, true, whichRow).first } fun part2(input: List<String>, highestCoordinate: Int): Long { val mySensors = input.map { it.split("=", ",", ":").mapNotNull { it2 -> it2.toIntOrNull() }} (0..highestCoordinate).forEach { val (amount, candidate) = getBlockedOnLine(mySensors, false, it, highestCoordinate) if (highestCoordinate - amount > 0) { return 4000000L * candidate + it } } return -1L } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 4000000)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
2,756
advent-of-kotlin-2022
Apache License 2.0
2021/src/main/kotlin/Day16.kt
eduellery
433,983,584
false
{"Kotlin": 97092}
class Day16(val input: String) { private val transmission = input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString("") fun solve1() = parse(transmission).sumOfVersions() fun solve2() = parse(transmission).value() private fun parse(packet: String): Packet { val type = packet.drop(3).take(3).toInt(2) val rest = packet.drop(6) return when (type) { 4 -> { rest.chunked(5).let { it.takeWhile { g -> g[0] == '1' } + it.first { g -> g[0] == '0' } } .let { Literal("${packet.take(6)}${it.joinToString("")}") } } else -> { when (rest.first()) { '0' -> { val totalLength = rest.drop(1).take(15).toInt(2) val subPackets = buildList<Packet> { while (totalLength - sumOf { it.bits.length } > 0) { parse(rest.drop(16 + sumOf { it.bits.length })).also { add(it) } } } Operator("${packet.take(22)}${subPackets.joinToString("") { it.bits }}", subPackets) } else -> { val subPacketsNumber = rest.drop(1).take(11).toInt(2) val subPackets = buildList<Packet> { repeat(subPacketsNumber) { parse(rest.drop(12 + sumOf { it.bits.length })).also { add(it) } } } Operator("${packet.take(18)}${subPackets.joinToString("") { it.bits }}", subPackets) } } } } } private sealed class Packet(val bits: String) { abstract fun sumOfVersions(): Int abstract fun value(): Long val type = bits.drop(3).take(3).toInt(2) } private class Literal(bits: String) : Packet(bits) { override fun sumOfVersions() = bits.take(3).toInt(2) override fun value() = bits.drop(6).chunked(5).joinToString("") { it.drop(1) }.toLong(2) } private class Operator(bits: String, private val subs: List<Packet>) : Packet(bits) { override fun sumOfVersions() = bits.take(3).toInt(2) + subs.sumOf { it.sumOfVersions() } override fun value(): Long = when (type) { 0 -> subs.sumOf { it.value() } 1 -> subs.fold(1) { acc, packet -> acc * packet.value() } 2 -> subs.minOf { it.value() } 3 -> subs.maxOf { it.value() } 5 -> (subs[0].value() > subs[1].value()).toLong() 6 -> (subs[0].value() < subs[1].value()).toLong() 7 -> (subs[0].value() == subs[1].value()).toLong() else -> error("Unsupported type $type") } private fun Boolean.toLong() = if (this) 1L else 0L } }
0
Kotlin
0
1
3e279dd04bbcaa9fd4b3c226d39700ef70b031fc
2,940
adventofcode-2021-2025
MIT License
src/twentythree/Day06.kt
mihainov
573,105,304
false
{"Kotlin": 42574}
package twentythree import readInputTwentyThree import java.util.stream.IntStream import kotlin.math.ceil import kotlin.math.max import kotlin.math.min import kotlin.math.sqrt import kotlin.streams.asSequence data class Race(val time: Long, val distance: Long) fun main() { fun part1(input: List<String>): Int { val times = input[0].substringAfter(':') .split(" ") .filter(String::isNotBlank) .map(String::trim) .map(String::toLong) val distances = input[1].substringAfter(':') .split(" ") .filter(String::isNotBlank) .map(String::trim) .map(String::toLong) val races: List<Race> = IntStream.range(0, times.size) .asSequence() .map { i -> Race(times[i], distances[i]).also { println("Parsed race $it") } } .toList() return races.map { race -> println("Handling race $race") val a = -1.0 val b = race.time.toDouble() val c = -race.distance.toDouble() val d = b * b - 4 * a * c val root1 = ((-b + sqrt(d)) / (2 * a)).also { println("Root 1 $it") } val root2 = ((-b - sqrt(d)) / (2 * a)).also { println("Root 2 $it") } val biggerRoot = max(root1, root2) val smallerRoot = min(root1, root2) IntStream.range(ceil(smallerRoot + 0.000000000001).toInt(), ceil(biggerRoot - 0.000000000001).toInt()) .count() .toInt() }.fold(1) { acc, i -> acc * i } } fun part2(input: List<String>): Int { val t = input[0] .replace(" ", "") .substringAfter(':') .toLong() val d = input[1] .replace(" ", "") .substringAfter(':') .toLong() val race = Race(t, d) println("Handling race $race") val time = race.time.toDouble() val distance = -race.distance.toDouble() val discriminant = time * time - 4 * -distance val root1 = ((-time + sqrt(discriminant)) / (2 * -1)) val root2 = ((-time - sqrt(discriminant)) / (2 * -1)) val biggerRoot = max(root1, root2) val smallerRoot = min(root1, root2) // hack with 0.000000001 to avoid situations in which the solution is an exact integer return IntStream.range(ceil(smallerRoot + 0.000000000001).toInt(), ceil(biggerRoot - 0.000000000001).toInt()) .count() .toInt() } // test if implementation meets criteria from the description, like: val testInput = readInputTwentyThree("Day06_test") check(part1(testInput).also(::println) == 288) check(part2(testInput).also(::println) == 71503) val input = readInputTwentyThree("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a9aae753cf97a8909656b6137918ed176a84765e
2,866
kotlin-aoc-1
Apache License 2.0
src/Day12.kt
ivancordonm
572,816,777
false
{"Kotlin": 36235}
import java.util.* import kotlin.collections.ArrayDeque import kotlin.collections.set fun main() { fun bfs(input: List<String>, start: Pair<Int, Int>): MutableMap<Pair<Int, Int>, Pair<Int, Int>> { val visited = mutableMapOf<Pair<Int, Int>, Boolean>() val edgeTo = mutableMapOf<Pair<Int, Int>, Pair<Int, Int>>() val queue = ArrayDeque<Pair<Int, Int>>() fun adjacents(c: Pair<Int, Int>): List<Pair<Int, Int>> { return buildList { listOf(-1 to 0, 0 to 1, 1 to 0, 0 to -1).forEach { p -> val next = c.first + p.first to c.second + p.second if (next.first >= 0 && next.first <= input.lastIndex && next.second >= 0 && next.second <= input.first().lastIndex && input.element(next).value() <= input.element(c).value() + 1 && !visited.contains(next) ) add(next) } } } visited[start] = true queue.add(start) while (queue.isNotEmpty()) { val vertex = queue.removeFirst() for (adjacent in adjacents(vertex)) { if (!visited.contains(adjacent)) { edgeTo[adjacent] = vertex visited[adjacent] = true queue.add(adjacent) } } } return edgeTo } fun MutableMap<Pair<Int, Int>, Pair<Int, Int>>.pathTo( source: Pair<Int, Int>, destination: Pair<Int, Int> ): List<Pair<Int, Int>> { val stack = Stack<Pair<Int, Int>>() var x = destination while (x != source) { stack.push(x) x = this[x]!! } return stack.toList() } fun part1(input: List<String>) = bfs(input, input.position('S')).pathTo(input.position('S'), input.position('E')).count() fun part2(input: List<String>) = input.allPositions('a').minOf { bfs(input, it).pathTo(it, input.position('E')).count() } val testInput = readInput("Day12_test") val input = readInput("Day12") check(part1(testInput) == 31) println(part1(testInput)) println(part1(input)) println(part2(testInput)) check(part2(testInput) == 29) println(part2(input)) } private fun List<String>.element(pos: Pair<Int, Int>) = this[pos.first][pos.second] private fun List<String>.position(c: Char) = mapIndexed { index, s -> index to s }.filter { it.second.contains(c) } .map { elem -> elem.first to elem.second.indexOf(c) }.first() private fun List<String>.allPositions(c: Char) = mapIndexed { index, s -> index to s }.filter { it.second.contains(c) } .map { elem -> elem.first to elem.second.indexOf(c) } private fun Char.value() = when (this) { 'S' -> 'a' - 1 'E' -> 'z' + 1 else -> this }
0
Kotlin
0
2
dc9522fd509cb582d46d2d1021e9f0f291b2e6ce
2,991
AoC-2022
Apache License 2.0
src/Day08.kt
mandoway
573,027,658
false
{"Kotlin": 22353}
fun parseRowsAndColumns(input: List<String>): Pair<List<List<Int>>, List<List<Int>>> { val rows = input.map { row -> row.map { it.digitToInt() } } val cols = MutableList(input.size) { mutableListOf<Int>() } rows.forEach { row -> row.forEachIndexed { index, height -> cols[index].add(height) } } return rows to cols } fun List<Int>.blockedBy(height: Int) = if (isEmpty()) { false } else { any { it >= height } } fun List<Int>.visibleTreesAt(height: Int) = when { isEmpty() -> 0 all { it < height } -> size else -> takeWhile { it < height }.size + 1 } fun List<Int>.takeBefore(index: Int) = take(index).reversed() fun List<Int>.takeAfter(index: Int) = takeLast(lastIndex - index) fun main() { fun part1(input: List<String>): Int { val (rows, cols) = parseRowsAndColumns(input) return rows.withIndex() .sumOf { (rowIndex, row) -> row.withIndex() .count { (columnIndex, height) -> val blockedFromLeft = row.takeBefore(columnIndex).blockedBy(height) val blockedFromRight = row.takeAfter(columnIndex).blockedBy(height) val currentColumn = cols[columnIndex] val blockedFromTop = currentColumn.takeBefore(rowIndex).blockedBy(height) val blockedFromBottom = currentColumn.takeAfter(rowIndex).blockedBy(height) !blockedFromLeft || !blockedFromRight || !blockedFromTop || !blockedFromBottom } } } fun part2(input: List<String>): Int { val (rows, cols) = parseRowsAndColumns(input) return rows.withIndex() .maxOf { (rowIndex, row) -> row.withIndex() .maxOf { (columnIndex, height) -> val leftVisibleTrees = row.takeBefore(columnIndex).visibleTreesAt(height) val rightVisibleTrees = row.takeAfter(columnIndex).visibleTreesAt(height) val currentColumn = cols[columnIndex] val topVisibleTrees = currentColumn.takeBefore(rowIndex).visibleTreesAt(height) val bottomVisibleTrees = currentColumn.takeAfter(rowIndex).visibleTreesAt(height) leftVisibleTrees * rightVisibleTrees * topVisibleTrees * bottomVisibleTrees } } } // 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
0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2
2,795
advent-of-code-22
Apache License 2.0
src/2022/Day07.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun readFileSystem(input: List<String>): Directory { val root = Directory(name = "/", children = mutableListOf()) var currentFolder = root input.drop(1).forEach { command -> if (command.startsWith("\$ cd")) { val folder = command.split(" ")[2] currentFolder = if (currentFolder.children.any { it.name == folder }) { currentFolder.children.find { it.name == folder } as Directory } else if (folder == "..") { currentFolder.parent!! } else { val newFolder = Directory(parent = currentFolder, name = folder, children = mutableListOf()) currentFolder.children.add(newFolder) newFolder } } else if (!command.startsWith("\$")) { val split = command.split(" ") if (split[0] == "dir") { val newFolder = Directory(parent = currentFolder, name = split[1], children = mutableListOf()) currentFolder.children.add(newFolder) } else { val newFile = File(parent = currentFolder, name = split[1], size = split[0].toInt()) currentFolder.children.add(newFile) } } } return root } fun findSmallFoldersToDelete(folder: Directory): List<Directory> { val smallDirectories = if (folder.size < 100_000) listOf(folder) else listOf() return if (folder.children.any { it is Directory }) { folder.children.filterIsInstance<Directory>().flatMap { findSmallFoldersToDelete(it) } + smallDirectories } else { smallDirectories } } fun findBigFoldersToDelete(folder: Directory, atLeastSize: Int): List<Directory> { val bigDirectories = if (folder.size >= atLeastSize) listOf(folder) else listOf() return if (folder.children.any { it is Directory }) { folder.children.filterIsInstance<Directory>().flatMap { findBigFoldersToDelete(it, atLeastSize) } + bigDirectories } else { bigDirectories } } fun part1(input: List<String>): Int { val root = readFileSystem(input) val folders = findSmallFoldersToDelete(root) return folders.sumOf { it.size } } fun part2(input: List<String>): Int { val root = readFileSystem(input) val needToFreeSize = 30000000 - (70000000 - root.size) return findBigFoldersToDelete(root, needToFreeSize).minOf { it.size } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) } interface Path { val parent: Directory? val name: String val size: Int } class Directory(override val parent: Directory? = null, override val name: String, val children: MutableList<Path>): Path { override val size: Int get() = children.sumOf { it.size } } data class File(override val parent: Directory, override val name: String, override val size: Int): Path
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
3,342
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/day08/TreetopTreeHouse.kt
iamwent
572,947,468
false
{"Kotlin": 18217}
package day08 import readInput class TreetopTreeHouse( private val name: String ) { private fun readMap(): List<List<Int>> { return readInput(name).map { it.map { height -> height.digitToInt() } } } fun part1(): Int { val map = readMap() val width = map.first().size val height = map.size fun isVisible(x: Int, y: Int): Boolean { val horizontal = listOf(map[y].slice(0 until x), map[y].slice((x + 1) until width)) val vertical = listOf(0 until y, (y + 1) until height) .map { ys -> ys.map { map[it][x] } } return (horizontal + vertical).any { it.all { height -> height < map[y][x] } } } val interior = (1 until (width - 1)) .flatMap { x -> (1 until (height - 1)).map { y -> x to y } } .filter { (x, y) -> isVisible(x, y) } .size return interior + width * 2 + (height - 2) * 2 } fun part2(): Int { val map = readMap() val width = map.first().size val height = map.size fun scenicScore(x: Int, y: Int): Int { val horizontal = listOf(map[y].slice(0 until x).reversed(), map[y].slice((x + 1) until width)) val vertical = listOf(y - 1 downTo 0, (y + 1) until height).map { ys -> ys.map { map[it][x] } } return (horizontal + vertical) .map { trees -> val distance = trees.indexOfFirst { it >= map[y][x] } return@map if (distance == -1) { trees.size } else { distance + 1 } } .reduce(Int::times) } return (1 until (width - 1)) .flatMap { x -> (1 until (height - 1)).map { y -> x to y } } .maxOf { (x, y) -> scenicScore(x, y) } } }
0
Kotlin
0
0
77ce9ea5b227b29bc6424d9a3bc486d7e08f7f58
1,899
advent-of-code-kotlin
Apache License 2.0
advent-of-code-2023/src/Day18.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import lib.matrix.Direction import lib.matrix.Direction.* import lib.matrix.Direction.Companion.moveInDirection import lib.matrix.Direction.Companion.nextInDirection import lib.matrix.Position import kotlin.math.abs private const val DAY = "Day18" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 62 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 952408144115 measureAnswer { part2(input()) } } } private fun part1(input: List<Command>): Int { var position = Position.Zero val seenPositions = mutableSetOf(position) for (command in input) { repeat(command.distance) { position = position.nextInDirection(command.direction) seenPositions += position } } val queue = ArrayDeque<Position>() queue += Position(1, 1) while (queue.isNotEmpty()) { val pos = queue.removeFirst() for (n in pos.neighbors()) { if (n !in seenPositions) queue.addLast(n) seenPositions += n } } return seenPositions.size } private fun part2(input: List<Command>): Long { val commands = input.map { (_, _, color) -> val direction = when (color.last()) { '0' -> RIGHT '1' -> DOWN '2' -> LEFT else -> UP } val distance = color.drop(1).dropLast(1).toInt(radix = 16) Command(direction, distance, "") } var position = Position.Zero val points = mutableListOf(position) for (command in commands) { position = position.moveInDirection(command.direction, command.distance) points += position } val area = points.windowed(2) { (p1, p2) -> p1.row.toLong() * p2.column - p2.row.toLong() * p1.column }.sum() / 2 val p = commands.sumOf { it.distance } return abs(area) + p / 2 + 1 } fun Position.neighbors(): List<Position> = Direction.entries.map { nextInDirection(it) } private fun readInput(name: String) = readLines(name).map { line -> val (dir, dist, color) = line.split(" ") val direction = when (dir) { "U" -> UP "D" -> DOWN "L" -> LEFT else -> RIGHT } Command(direction, dist.toInt(), color.trim('(', ')')) } private data class Command(val direction: Direction, val distance: Int, val color: String)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
2,441
advent-of-code
Apache License 2.0
src/Day07.kt
JohannesPtaszyk
573,129,811
false
{"Kotlin": 20483}
const val PATH_DELIMITER = "/" const val TOTAL_DISK_CAPACITY = 70_000_000 const val NEEDED_SPACE = 30_000_000 data class File(val size: Int, val name: String, val path: String) { fun parentDirs(): List<String> = path.removeSuffix(PATH_DELIMITER).let { path -> if (path == PATH_DELIMITER) { listOf("/") } else { val segments = path.split(PATH_DELIMITER) List(segments.size) { index -> segments.subList(0, index + 1).joinToString(separator = PATH_DELIMITER, postfix = PATH_DELIMITER) { it } } } } } data class Dir(val path: String, var size: Int) fun getDirs(input: List<String>): MutableList<Dir> { var currentPath = "" val dirs = input.asSequence().mapNotNull { line -> if (line.startsWith("dir") || line.startsWith("$ ls")) return@mapNotNull null if (!line.contains("$")) { val (size, name) = line.split(" ") return@mapNotNull File(size.toInt(), name, currentPath) } when (val cd = line.split(" ")[2]) { "/" -> currentPath = PATH_DELIMITER ".." -> { currentPath = currentPath.split(PATH_DELIMITER) .dropLast(2) .joinToString(separator = PATH_DELIMITER, postfix = PATH_DELIMITER) { it } } else -> currentPath += cd + PATH_DELIMITER } null }.fold(mutableListOf()) { dirs: MutableList<Dir>, file: File -> file.parentDirs().forEach { parent -> val dir = dirs.find { it.path == parent } if (dir == null) { dirs.add(Dir(parent, file.size)) } else { dir.size += file.size } } dirs } return dirs } fun main() { fun part1(input: List<String>): Int { val dirs = getDirs(input) return dirs.filter { it.size <= 100_000 }.sumOf { it.size } } fun part2(input: List<String>): Int { val dirs = getDirs(input) val rootSize = dirs.first { it.path == PATH_DELIMITER }.size val neededSpace = NEEDED_SPACE - (TOTAL_DISK_CAPACITY - rootSize) return dirs.sortedBy { it.size }.also { println(it) }.first { it.size > neededSpace }.size } val testInput = readInput("Day07_test") val input = readInput("Day07") val part1TestResult = part1(testInput) println("Part1 test: $part1TestResult") check(part1TestResult == 95437) println("Part 1: ${part1(input)}") val part2TestResult = part2(testInput) println("Part2 test: $part2TestResult") check(part2TestResult == 24933642) println("Part 2: ${part2(input)}") }
0
Kotlin
0
1
6f6209cacaf93230bfb55df5d91cf92305e8cd26
2,716
advent-of-code-2022
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day03/Day03.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day03 import eu.janvdb.aocutil.kotlin.readNonSeparatedDigits const val FILENAME = "input03.txt" fun main() { val data = readNonSeparatedDigits(2021, FILENAME) part1(data) part2(data) } private fun part1(data: List<List<Int>>) { val gamma = keepBits(data, ::mostCommonAt) val epsilon = keepBits(data, ::leastCommonAt) println("gamma=$gamma, epsilon=$epsilon, result=${gamma * epsilon}") } private fun part2(data: List<List<Int>>) { val oxygen = reduceList(data, ::mostCommonAt) val co2scrubber = reduceList(data, ::leastCommonAt) println("oxygen=$oxygen, co2scrubber=$co2scrubber, result=${oxygen * co2scrubber}") } private fun keepBits(data: List<List<Int>>, reductor: (List<List<Int>>, Int) -> Int): Long { val bits = (0..data[0].size - 1).map { reductor(data, it) } return toDecimal(bits) } private fun reduceList(data: List<List<Int>>, reductor: (List<List<Int>>, Int) -> Int): Long { var dataCopy = data for (i in data[0].indices) { val bitValue = reductor(dataCopy, i) dataCopy = dataCopy.filter { it[i] == bitValue } if (dataCopy.size == 1) break } return toDecimal(dataCopy[0]) } private fun mostCommonAt(data: List<List<Int>>, position: Int): Int = data.asSequence() .map { it[position] } .groupBy { it } .maxByOrNull { it.value.size * 2 + it.key }!! .key private fun leastCommonAt(data: List<List<Int>>, position: Int): Int = data.asSequence() .map { it[position] } .groupBy { it } .minByOrNull { it.value.size * 2 + it.key }!! .key private fun toDecimal(gammaBits: List<Int>) = gammaBits .fold(0L) { acc, value -> acc * 2 + value }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,611
advent-of-code
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-24.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import java.util.* fun main() { val input = readInputLines(2015, "24-input") val test1 = readInputLines(2015, "24-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Long { return solve(input, 3) } private fun part2(input: List<String>): Long { return solve(input, 4) } private fun solve(input: List<String>, groupCount: Int): Long { val packages = input.map { it.toLong() }.sortedDescending() val sum = packages.sum() require(sum % groupCount == 0L) val target = sum / groupCount val sequence = packages.groupsWithSum(target) val firstValid = sequence.first { it.isValid(packages, target) } val allCandidates = sequence.takeWhile { it.size <= firstValid.size }.dropWhile { it.size < firstValid.size } return allCandidates.minOf { it.product() } } private fun List<Long>.product(): Long = reduce { acc, l -> acc * l } private fun List<Long>.groupsWithSum(target: Long): Sequence<List<Long>> = sequence { val queue = LinkedList<Pair<List<Long>, List<Long>>>() queue.addLast(emptyList<Long>() to this@groupsWithSum) while (queue.isNotEmpty()) { val (next, remaining) = queue.removeFirst() val sum = next.sum() for (i in remaining.indices) { if (target < sum + remaining[i]) continue val new = next + remaining[i] if (target == sum + remaining[i]) { yield(new) continue } queue += new to remaining.subList(i + 1, remaining.size) } } } private fun List<Long>.isValid(all: List<Long>, target: Long): Boolean { val rest = all - this.toSet() return rest.groupsWithSum(target).any() }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,005
advent-of-code
MIT License
2023/src/main/kotlin/day3.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.Parser import utils.Solution import utils.Vec2i fun main() { Day3.run(skipTest = false) } object Day3 : Solution<Grid<Char>>() { override val name = "day3" override val parser = Parser.charGrid data class PartNum( val num: Int, val start: Vec2i, val end: Vec2i, ) { val points: List<Vec2i> get() { return (start.x..end.x).map { Vec2i(it, start.y) } } } private fun partNums(grid: Grid<Char>): Set<PartNum> { val nums = grid.cells.filter { (p, c) -> c.isDigit() && p.surrounding.any { it in grid.coords && grid[it].isSymbol() } }.map { (p, _) -> val start = (p.x downTo 0).takeWhile { x -> grid[x][p.y].isDigit() }.last() val end = (p.x until grid.width).takeWhile { x -> grid[x][p.y].isDigit() }.last() val chars = (start..end).map { x -> grid[x][p.y] } PartNum( chars.joinToString("").toInt(), Vec2i(start, p.y), Vec2i(end, p.y), ) }.toSet() return nums } override fun part1(grid: Grid<Char>): Int { return partNums(grid).sumOf { it.num } } override fun part2(grid: Grid<Char>): Int { val partNums = partNums(grid) val gearRatios = grid.cells.mapNotNull { (p, c) -> if (c != '*') return@mapNotNull null val adjacentParts = partNums.filter { partNum -> p.surrounding.any { it in partNum.points } } if (adjacentParts.size != 2) return@mapNotNull null return@mapNotNull adjacentParts[0].num * adjacentParts[1].num } return gearRatios.sum() } } private fun Char.isSymbol(): Boolean { return !isDigit() && this != '.' }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,652
aoc_kotlin
MIT License
src/com/kingsleyadio/adventofcode/y2021/day15/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day15 import com.kingsleyadio.adventofcode.util.readInput import com.kingsleyadio.adventofcode.y2021.day13.Point import java.util.* fun solution(input: List<IntArray>): Int { val plane = List(input.size) { IntArray(input.size) { Int.MAX_VALUE } } val queue = PriorityQueue<Path> { a, b -> a.cost - b.cost } queue.offer(Path(Point(0, 0), 0)) while (queue.isNotEmpty()) { val current = queue.poll() val (to, cost) = current if (plane[to.y][to.x] != Int.MAX_VALUE) continue plane[to.y][to.x] = cost sequence { for (y in -1..1) for (x in -1..1) { if (y != 0 && x != 0) continue val point = Point(to.x + x, to.y + y) val cell = plane.getOrNull(point.y)?.getOrNull(point.x) ?: continue if (cell == Int.MAX_VALUE) yield(point) } }.forEach { point -> queue.add(Path(point, cost + input[point.y][point.x])) } } return plane.last().last() } data class Point(val x: Int, val y: Int) data class Path(val to: Point, val cost: Int) fun main() { val input = buildList { readInput(2021, 15).forEachLine { line -> add(line.map { it.digitToInt() }.toIntArray()) } } println(solution(input)) val newInput = input.expand(5) println(solution(newInput)) } fun List<IntArray>.expand(times: Int): List<IntArray> { val self = this val newList = List(size * times) { IntArray(size * times) } for (i in 0..newList.lastIndex) { for (j in 0..newList.lastIndex) { val x = j % self.size val y = i % self.size val value = self[y][x] + j / self.size + i / self.size newList[i][j] = if (value > 9) (value % 10) + 1 else value } } return newList }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,855
adventofcode
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2018/Day15.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2018 import se.saidaspen.aoc.util.* fun main() = Day15.run() object Day15 : Day(2018, 15) { enum class Type { G, E } data class Combatant(val id: Char, val type: Type, var pos: Point, var hp: Int = 200) override fun part1(): Any { val (combatants, fullrounds) = simulateFight(3) return combatants.sumOf { it.hp } * fullrounds } override fun part2(): Any { var strenght = 4 val numElves = input.count { it == 'E' } while(true) { val (combatants, fullrounds) = simulateFight(strenght) val survivedElves = combatants.count { it.type == Type.E } if (survivedElves == numElves) { return combatants.sumOf { it.hp } * fullrounds } strenght++ } } private fun simulateFight(elfStrength: Int): P<MutableList<Combatant>, Int> { val map = toMap(input) var combatants = map.entries.filter { it.value == 'E' || it.value == 'G' }.withIndex().map { val id = if (it.index < 10) (it.index + 48).toChar() else (55 + it.index).toChar() Combatant(id, if (it.value.value == 'E') Type.E else Type.G, it.value.key) }.toMutableList() combatants.forEach { map[it.pos] = it.id } var fullRounds = 0 while (combatants.map { it.type }.histo().size == 2) { combatants = combatants.sortedWith(compareBy<Combatant> { it.pos.second }.thenBy { it.pos.first }).toMutableList() val killedThisRound = mutableListOf<Combatant>() for (c in combatants) { fun getNeighbourEnemies(pos: Point) = c.pos.neighborsSimple() .filter { map.containsKey(it) && map[it] != '.' && map[it] != '#' } .map { npos -> map[npos]!! } .map { combatants.first { e -> e.id == it } } .filter { it.type != c.type } .filter { !killedThisRound.contains(it) } if (killedThisRound.contains(c)) continue var neighborEnemies = getNeighbourEnemies(c.pos) if (neighborEnemies.isEmpty()) { val targets = combatants.filter { !killedThisRound.contains(it) }.filter { it.type != c.type } val inRange = targets.flatMap { neighborsSimple(it.pos) }.filter { map[it] == '.' }.toSet() val next: (Point) -> Iterable<Point> = { it.neighborsSimple().filter { n -> map.containsKey(n) && map[n] == '.' }.sortedWith(compareBy<Point> {p -> p.second }.thenBy {p-> p.first }) } val reachable = inRange.mapNotNull { destination -> bfsPath( c.pos, { it == destination }, next ) } if (reachable.isEmpty()) continue val minLength = reachable.minOf { it.length } val chosen = reachable.filter { it.length == minLength }.sortedWith(compareBy<BfsResult<Point>> { it.path.first().second }.thenBy { it.path.first().first }).first().path.dropLast(1).last() // Need to change map[c.pos] = '.' c.pos = chosen map[c.pos] = c.id neighborEnemies = getNeighbourEnemies(c.pos) } if (neighborEnemies.isNotEmpty()) { val attackable = neighborEnemies.sortedWith(compareBy<Combatant> { it.hp }.thenBy { it.pos.second }.thenBy { it.pos.first }) val enemyToAttack = attackable.first() val strength = if(c.type == Type.E) elfStrength else 3 enemyToAttack.hp = enemyToAttack.hp - strength if (enemyToAttack.hp <= 0 ) { killedThisRound.add(enemyToAttack) map[enemyToAttack.pos] = '.' } } } combatants.removeAll(killedThisRound) killedThisRound.clear() fullRounds += 1 } return P(combatants, fullRounds - 1) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
4,251
adventofkotlin
MIT License
src/Day04.kt
kenyee
573,186,108
false
{"Kotlin": 57550}
fun main() { // ktlint-disable filename fun containedRangesInPair(line: String): Int { val ranges = line.split(",") val range1 = ranges[0].split("-").let { it[0].toInt()..it[1].toInt() } val range2 = ranges[1].split("-").let { it[0].toInt()..it[1].toInt() } val range1inRange2 = range1.first in range2 && range1.last in range2 val range2inRange1 = range2.first in range1 && range2.last in range1 return if (range1inRange2 || range2inRange1) 1 else 0 } fun part1(input: List<String>): Int { val totalRanges = input.sumOf { line -> containedRangesInPair(line.trim()) } return totalRanges } fun overlappingRangesInPair(line: String): Int { val ranges = line.split(",") val range1 = ranges[0].split("-").let { it[0].toInt()..it[1].toInt() } val range2 = ranges[1].split("-").let { it[0].toInt()..it[1].toInt() } val range1inRange2 = range1.first in range2 || range1.last in range2 val range2inRange1 = range2.first in range1 || range2.last in range1 return if (range1inRange2 || range2inRange1) 1 else 0 } fun part2(input: List<String>): Int { val totalRanges = input.sumOf { line -> overlappingRangesInPair(line.trim()) } return totalRanges } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") println("test result contained pairs total: ${part1(testInput)}") check(part1(testInput) == 2) println("test result overlapping pairs total is: ${part2(testInput)}") check(part2(testInput) == 4) val input = readInput("Day04_input") println("Contained pairs total is: ${part1(input)}") println("Overlapping pairs total is: ${part2(input)}") }
0
Kotlin
0
0
814f08b314ae0cbf8e5ae842a8ba82ca2171809d
1,834
KotlinAdventOfCode2022
Apache License 2.0
src/Day11.kt
olezhabobrov
572,687,414
false
{"Kotlin": 27363}
class Monkeys(input: List<String>, val toDivide: Boolean = true) { val monkeys: MutableList<Monkey> = mutableListOf() init { input.chunked(7).forEach { monkeyString -> val items = monkeyString[1].split(" ", ",").map{ it.toLongOrNull() } .filter { it != null }.toMutableList() val opStr = monkeyString[2].removePrefix(" Operation: new = ") val (a, op, b) = opStr.split(" ") val operation: (Long) -> Long = { old: Long -> val a2 = if (a == "old") old else a.toLong() val b2 = if (b == "old") old else b.toLong() if (op == "*") a2 * b2 else if (op == "+") a2 + b2 else error("not valid operation") } val x = monkeyString[3].split(" ").map { it.toLongOrNull() } .filter { it != null }.first()!! val testItem: (Long) -> Boolean = { z -> z % x == 0L } val monkey1 = monkeyString[4].split(" ").map { it.toIntOrNull() } .filter { it != null }.first()!! val monkey2 = monkeyString[5].split(" ").map { it.toIntOrNull() } .filter { it != null }.first()!! val trueOp: (Long) -> Unit = { item -> monkeys[monkey1].items.add(item) } val falseOp: (Long) -> Unit = { item -> monkeys[monkey2].items.add(item) } monkeys.add(Monkey(items, operation, testItem, trueOp, falseOp)) } } fun process(index: Int) { val monkey = monkeys[index] while (monkey.items.isNotEmpty()) { val item = monkey.items.removeFirst()!! monkey.counter++ val newLevel = if (toDivide) monkey.operation(item) / 3L else monkey.operation(item) if (monkey.testItem(newLevel)) { monkey.trueOp(newLevel) } else { monkey.falseOp(newLevel) } } } class Monkey( val items: MutableList<Long?>, val operation: (Long) -> Long, val testItem: (Long) -> Boolean, val trueOp: (Long) -> Unit, val falseOp: (Long) -> Unit ) { var counter: Long = 0L } } fun main() { fun part1(input: List<String>): Long { val monkeys = Monkeys(input) repeat(20) { for (index in 0 until monkeys.monkeys.size) { monkeys.process(index) } } val sorted = monkeys.monkeys.sortedByDescending { monkey -> monkey.counter } return sorted[0].counter * sorted[1].counter } fun part2(input: List<String>): Long { val monkeys = Monkeys(input, false) repeat(10000) { for (index in 0 until monkeys.monkeys.size) { monkeys.process(index) } } val sorted = monkeys.monkeys.sortedByDescending { monkey -> monkey.counter } return sorted[0].counter * sorted[1].counter } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) println(part2(testInput)) // check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
31f2419230c42f72137c6cd2c9a627492313d8fb
3,350
AdventOfCode
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/Day14.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 14: Extended Polymerization */ package dev.paulshields.aoc import dev.paulshields.aoc.common.addToValue import dev.paulshields.aoc.common.incrementValue import dev.paulshields.aoc.common.readFileAsString import dev.paulshields.aoc.common.subtractFromValue fun main() { println(" ** Day 14: Extended Polymerization ** \n") val polymerInstructions = readFileAsString("/Day14PolymerInstructions.txt") val partOne = differenceInCountOfMostAndLeastElementsInPolymerAfterIteration(polymerInstructions, 10) println("The difference in quantity between the most and least used elements in the polymer for part 1 is $partOne.") val partTwo = differenceInCountOfMostAndLeastElementsInPolymerAfterIteration(polymerInstructions, 40) println("The difference in quantity between the most and least used elements in the polymer for part 2 is $partTwo.") } fun differenceInCountOfMostAndLeastElementsInPolymerAfterIteration(polymerInstructions: String, iterationCount: Int): Long { val pairsCount = countPolymerPairsInPolymerAfterIteration(polymerInstructions, iterationCount) val individualElementsCountInPolymer = countIndividualElementsInPolymer(pairsCount, polymerInstructions) val countOfMostElements = individualElementsCountInPolymer.maxByOrNull { it.value }?.value ?: 0 val countOfLeastElements = individualElementsCountInPolymer.minByOrNull { it.value }?.value ?: 0 return countOfMostElements - countOfLeastElements } private fun countIndividualElementsInPolymer(polymerPairsCount: Map<String, Long>, polymerTemplate: String): Map<Char, Long> { val individualElementsCountInPolymer = polymerPairsCount .map { it.key[1] to it.value } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .map { it.key to it.value.sum() } .toMap().toMutableMap() individualElementsCountInPolymer.incrementValue(polymerTemplate.first()) return individualElementsCountInPolymer.toMap() } private fun countPolymerPairsInPolymerAfterIteration(polymerInstructions: String, iterationCount: Int): Map<String, Long> { val (polymerTemplate, pairInsertionRules) = parsePolymerInstructions(polymerInstructions) var elementPairsCount = pairInsertionRules .map { it.key } .associateWith { pair -> polymerTemplate.windowed(2, 1).count { it == pair }.toLong() } (0 until iterationCount).forEach { _ -> val nextElementPairsCount = elementPairsCount.toMutableMap() elementPairsCount.forEach { (elementPair, count) -> if (count == 0L) return@forEach nextElementPairsCount.subtractFromValue(elementPair, count) pairInsertionRules[elementPair]?.forEach { nextElementPairsCount.addToValue(it, count) } } elementPairsCount = nextElementPairsCount.toMap() } return elementPairsCount } private fun parsePolymerInstructions(polymerInstructions: String): Pair<String, Map<String, List<String>>> { val (polymerTemplate, rawPairInsertionRules) = polymerInstructions.split("\n\n") val pairInsertionRules = rawPairInsertionRules .lines() .associate { val (pair, insertionElement) = it.split(" -> ") pair to calculateInsertionReplacementPairs(pair, insertionElement.first()) } return polymerTemplate to pairInsertionRules } private fun calculateInsertionReplacementPairs(pair: String, insertionElement: Char) = listOf("${pair[0]}$insertionElement", "$insertionElement${pair[1]}")
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
3,557
AdventOfCode2021
MIT License
src/Day09.kt
floblaf
572,892,347
false
{"Kotlin": 28107}
import kotlin.math.pow import kotlin.math.sign import kotlin.math.sqrt fun main() { val moves = readInput("Day09").map { val (direction, steps) = it.split(" ") Move( direction = when (direction) { "U" -> Direction.UP "D" -> Direction.DOWN "L" -> Direction.LEFT "R" -> Direction.RIGHT else -> throw IllegalStateException() }, steps = steps.toInt() ) } fun computePositions(ropeSize: Int, moves: List<Move>): List<Rope> { val positions = mutableListOf(Rope(List(ropeSize) { Knot(x = 0, y = 0) })) moves.forEach { move -> repeat(move.steps) { val lastPosition = positions.last() val knots = mutableListOf<Knot>() knots.add(lastPosition.knots[0].let { when (move.direction) { Direction.LEFT -> it.copy(x = it.x - 1) Direction.RIGHT -> it.copy(x = it.x + 1) Direction.UP -> it.copy(y = it.y + 1) Direction.DOWN -> it.copy(y = it.y - 1) } }) for (i in 1 until lastPosition.knots.size) { val previous = lastPosition.knots[i] knots.add(if (knots[i-1].distance(previous) >= 2.0) { previous.copy( x = previous.x + (knots[i-1].x - previous.x).sign, y = previous.y + (knots[i-1].y - previous.y).sign ) } else { previous }) } positions.add(Rope(knots.toList())) } } return positions.toList() } fun countDistinctPositionOfTail(input: List<Rope>): Int { return input.map { it.knots.last() }.distinct().count() } println(countDistinctPositionOfTail(computePositions(2, moves))) println(countDistinctPositionOfTail(computePositions(10, moves))) } enum class Direction { LEFT, RIGHT, UP, DOWN } data class Move(val direction: Direction, val steps: Int) data class Knot(val x: Int, val y: Int) { fun distance(other: Knot): Double { return sqrt((other.x - x).toDouble().pow(2) + (other.y - y).toDouble().pow(2)) } } data class Rope( val knots: List<Knot> )
0
Kotlin
0
0
a541b14e8cb401390ebdf575a057e19c6caa7c2a
2,459
advent-of-code-2022
Apache License 2.0
src/year2021/Day3.kt
drademacher
725,945,859
false
{"Kotlin": 76037}
package year2021 import readLines fun main() { val input = readLines("2021", "day3").map { it.split(("")).filter { bit -> bit == "0" || bit == "1" } } val testInput = readLines("2021", "day3_test").map { it.split(("")).filter { bit -> bit == "0" || bit == "1" } } check(part1(testInput) == 198) println("Part 1:" + part1(input)) check(part2(testInput) == 230) println("Part 2:" + part2(input)) } private fun part1(input: List<List<String>>): Int { val bitsSize = input[0].size val gamma = mutableListOf<String>() val epsilon = mutableListOf<String>() for (bit in 0 until bitsSize) { if (mostCommonIsOne(input, bit)) { gamma.add("1") epsilon.add("0") } else { gamma.add("0") epsilon.add("1") } } return gamma.toBinary() * epsilon.toBinary() } private fun part2(input: List<List<String>>): Int { val bitsSize = input[0].size var oxygenGeneratorRating = input.map { ArrayList(it) } for (bit in 0 until bitsSize) { oxygenGeneratorRating = oxygenGeneratorRating.filter { (it[bit] == "1") == mostCommonIsOne(oxygenGeneratorRating, bit) } if (oxygenGeneratorRating.size == 1) break } var co2ScrubberRating = input.map { ArrayList(it) } for (bit in 0 until bitsSize) { co2ScrubberRating = co2ScrubberRating.filter { (it[bit] == "1") != mostCommonIsOne(co2ScrubberRating, bit) } if (co2ScrubberRating.size == 1) break } return oxygenGeneratorRating[0].toBinary() * co2ScrubberRating[0].toBinary() } private fun mostCommonIsOne( input: List<List<String>>, i: Int, ) = input.filter { it[i] == "1" }.size * 2 >= input.size private fun List<String>.toBinary(): Int = this.joinToString("").toInt(2)
0
Kotlin
0
0
4c4cbf677d97cfe96264b922af6ae332b9044ba8
1,792
advent_of_code
MIT License