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/Day12.kt
jstapels
572,982,488
false
{"Kotlin": 74335}
fun main() { data class Coord(val row: Int, val col: Int) fun List<List<Char>>.get(pos: Coord) = this[pos.row][pos.col] fun List<List<Char>>.height(pos: Coord) = this[pos.row][pos.col] .let { when (it) { 'S' -> 'a' 'E' -> 'z' else -> it } } fun find(map: List<List<Char>>, ch: Char) = map.flatMapIndexed { row, line -> line.withIndex() .filter { it.value == ch } .map { (col, _) -> Coord(row, col) } }.first() fun parseInput(input: List<String>) = input.map { it.toList() } fun invertMap(map: List<List<Char>>) = map.map { line -> line.map { when (it) { 'E' -> 'S' 'S', 'a' -> 'E' else -> 'a' + ('z' - it) }} } fun adjacents(map: List<List<Char>>, pos: Coord): List<Coord> { val maxCol = map[0].size - 1 val maxRow = map.size - 1 val up = Coord(pos.row - 1, pos.col) val down = Coord(pos.row + 1, pos.col) val left = Coord(pos.row, pos.col - 1) val right = Coord(pos.row, pos.col + 1) val valid = map.height(pos) + 1 val isValid = { p: Coord -> p.row in (0.. maxRow) && p.col in (0..maxCol) && map.height(p) <= valid } return listOf(up, down, left, right) .filter { isValid(it) } } fun bfs(map: List<List<Char>>, start: Coord): List<Coord> { val parents = mutableMapOf<Coord, Coord>() val explored = mutableListOf(start) val search = mutableListOf(start) while (search.isNotEmpty()) { val node = search.removeFirst() if (map.get(node) == 'E') { val path = mutableListOf(node) var n = node while (n in parents) { n = parents[n]!! path.add(n) } return path } adjacents(map, node).forEach { if (it !in explored) { explored.add(it) parents[it] = node search.add(it) } } } throw IllegalStateException() } fun part1(input: List<String>): Int { val map = parseInput(input) val start = find(map, 'S') val path = bfs(map, start) return path.size - 1 } fun part2(input: List<String>): Int { val map = invertMap(parseInput(input)) val start = find(map, 'S') val path = bfs(map, start) return path.size - 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") checkTest(31) { part1(testInput) } checkTest(29) { part2(testInput) } val input = readInput("Day12") solution { part1(input) } solution { part2(input) } }
0
Kotlin
0
0
0d71521039231c996e2c4e2d410960d34270e876
2,969
aoc22
Apache License 2.0
src/Day02.kt
BenHopeITC
573,352,155
false
null
fun main() { fun part3(input: List<String>) = input .map { (it[0] - 'A') to (it[2] - 'X') } .sumOf { (a, b) -> 3 * (4 + b - a).rem(3) + b + 1 } fun part1(input: List<String>): Int { val games = input.map { val actions = it.split(" ") actions[0] to actions[1] } val pointsForShape = games.map { when (it.second.uppercase()) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } }.sum() val pointsForResult = games.map { when (it.first.uppercase() to it.second.uppercase()) { "A" to "Z", "B" to "X", "C" to "Y" -> 0 "A" to "X", "B" to "Y", "C" to "Z" -> 3 else -> 6 } }.sum() return pointsForShape + pointsForResult } fun part2(input: List<String>): Int { val games = input.map { val actions = it.split(" ") actions[0] to actions[1] }.map { it.first to when(it.second) { "X" -> if (it.first=="A") "C" else if (it.first=="B") "A" else "B" "Z" -> if (it.first=="A") "B" else if (it.first=="B") "C" else "A" else -> it.first } } val pointsForShape = games.map { when (it.second.uppercase()) { "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } }.sum() val pointsForResult = games.map { when (it.first.uppercase() to it.second.uppercase()) { "A" to "C", "B" to "A", "C" to "B" -> 0 "A" to "A", "B" to "B", "C" to "C" -> 3 else -> 6 } }.sum() return pointsForShape + pointsForResult } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // println(part1(testInput)) // check(part1(testInput) == 15) // val testInput2 = readInput("Day02_test2") // println(part2(testInput2)) // check(part2(testInput2) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) println(part3(input)) check(part1(input) == 11603) check(part2(input) == 12725) }
0
Kotlin
0
0
851b9522d3a64840494b21ff31d83bf8470c9a03
2,541
advent-of-code-2022-kotlin
Apache License 2.0
src/year2015/day18/Day18.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day18 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2015", "Day18_test") check(part1(testInput, 4), 4) check(part2(testInput, 5), 17) val input = readInput("2015", "Day18") println(part1(input)) println(part2(input)) // 865 is too low } private fun part1(input: List<String>, rounds: Int = 100) = activeLightsAfterAnimation(input, rounds) private fun part2(input: List<String>, rounds: Int = 100) = activeLightsAfterAnimation(input, rounds) { (y, x), grid -> (y to x) isCornerOf grid } private fun activeLightsAfterAnimation( input: List<String>, rounds: Int = 100, orCondition: (Pair<Int, Int>, Array<Array<Boolean>>) -> Boolean = { _, _ -> false }, ): Int { var grid = input.toGrid(orCondition) var next = Array(grid.size) { Array(grid.first().size) { false } } repeat(rounds) { for (y in grid.indices) { for (x in grid.first().indices) { val activeNeighbours = (y to x).neighbours().count { (ny, nx) -> grid.getOrNull(ny)?.getOrNull(nx) == true } val isActive = grid[y][x] next[y][x] = (isActive && activeNeighbours in 2..3) || (!isActive && activeNeighbours == 3) || orCondition(y to x, grid) } } val temp = grid grid = next next = temp } return grid.sumOf { row -> row.count { it } } } private fun List<String>.toGrid( orCondition: (Pair<Int, Int>, Array<Array<Boolean>>) -> Boolean ): Array<Array<Boolean>> { val grid = Array(size) { Array(first().length) { false } } forEachIndexed { y, row -> row.forEachIndexed { x, state -> grid[y][x] = state == '#' || orCondition(y to x, grid) } } return grid } private fun Pair<Int, Int>.neighbours(): List<Pair<Int, Int>> { val (y, x) = this return listOf( y - 1 to x - 1, y - 1 to x, y - 1 to x + 1, y to x + 1, y + 1 to x + 1, y + 1 to x, y + 1 to x - 1, y to x - 1, ) } private infix fun Pair<Int, Int>.isCornerOf(grid: Array<Array<Boolean>>): Boolean { val (y, x) = this return (y == 0 || y == grid.lastIndex) && (x == 0 || x == grid.first().lastIndex) }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
2,416
AdventOfCode
Apache License 2.0
src/Day12.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
import java.util.* private data class Day12Point(val coords: Pair<Int, Int>, val elevation: Int) fun main() { fun List<String>.find(c: Char): List<Pair<Int, Int>> { val points = mutableListOf<Pair<Int, Int>>() for (y in indices) { for(x in this[y].indices) { if (this[y][x] == c) points.add(y to x) } } return points } fun List<IntArray>.elevationOf(p: Pair<Int, Int>): Int { return this[p.first][p.second] } fun List<IntArray>.bfs(start: Pair<Int, Int>, end: Pair<Int, Int>): Int { val dirs = listOf(0, 1, 0, -1, 0) val queue: Queue<Day12Point> = LinkedList() queue.offer(Day12Point(start, this[start.first][start.second])) this[start.first][start.second] = Int.MAX_VALUE var steps = 0 while (queue.isNotEmpty()) { steps++ repeat(queue.size) { val (coords, elevation) = queue.poll() if (coords == end) { return steps - 1 } val next = dirs.windowed(2).map { coords.first + it[0] to coords.second + it[1] } .filter { it.first in 0..lastIndex && it.second in 0..this[0].lastIndex && elevationOf(it) <= elevation + 1 } for (p in next) { queue.offer(Day12Point(p, elevationOf(p))) this[p.first][p.second] = Int.MAX_VALUE } } } return Int.MAX_VALUE } fun List<String>.solve(end: Pair<Int, Int>, vararg starts: Pair<Int, Int>): Int { var minSteps = Int.MAX_VALUE for (start in starts) { val map = map { s -> s.map { it - 'a' }.toIntArray() }.apply { this[start.first][start.second] = 0 } .apply { this[end.first][end.second] = 25 } minSteps = minOf(minSteps, map.bfs(start, end)) } return minSteps } fun part1(input: List<String>): Int { val start = input.find('S').single() val end = input.find('E').single() return input.solve(end, start) } fun part2(input: List<String>): Int { val starts = input.find('a').toTypedArray() val end = input.find('E').single() return input.solve(end, *starts) } check(part1(readInput("Day12_test")) == 31) check(part2(readInput("Day12_test")) == 29) println(part1(readInput("Day12"))) println(part2(readInput("Day12"))) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
2,507
aoc-2022
Apache License 2.0
src/y2022/Day16.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput import java.lang.Integer.max object Day16 { class Valve( val id: String, val rate: Int, var neighbors: List<Valve>, private val neighborIds: List<String>, ) { companion object { fun of(line: String): Valve { val id = line.drop(6).take(2) val rate = line.substringAfter("rate=").substringBefore(";").toInt() val neighborIds = line.substringAfter("valves ").split(", ") return Valve(id, rate, listOf(), neighborIds) } } fun updateNeighbors(valves: Map<String, Valve>) { neighbors = neighborIds.map { valves[it] ?: error("neighbor not in map") } } override fun toString(): String { return "$id: $rate → $neighborIds" } fun distances(keys: Set<String>): Map<Pair<String, String>, Int> { val remaining = keys.toMutableSet() remaining.remove(id) val rtn = mutableMapOf((id to id) to 0) var dist = 1 var frontier = neighbors.toSet() do { rtn.putAll(frontier.associate { (id to it.id) to dist }) remaining.removeAll(frontier.map { it.id }.toSet()) frontier = frontier.map { it.neighbors }.flatten().filter { it.id in remaining }.toSet() dist++ } while (remaining.isNotEmpty()) return rtn } } class PressureSearch(valves: Map<String, Valve>) { private val distances: Map<Pair<String, String>, Int> = getAllDistances(valves) private fun getAllDistances(valves: Map<String, Valve>): Map<Pair<String, String>, Int> { val rtn = mutableMapOf<Pair<String, String>, Int>() valves.forEach { rtn.putAll(it.value.distances(valves.keys)) } return rtn } fun maxReleaseFrom( state: SearchState, bestSoFar: Int, ): Int { val optimistic = state.unOpened.map { it.rate }.sortedDescending() .mapIndexed { index, rate -> max(0, (state.remainingMinutes - (index + 1) * 2)) * rate } .sum() + state.releasedSoFar if (optimistic <= bestSoFar) { return 0 } val nextSteps = state.unOpened.map { val remaining = state.remainingMinutes - distances[state.position to it.id]!! - 1 SearchState(it.id, remaining, remaining * it.rate, state.unOpened - setOf(it), state.releasedSoFar + remaining * it.rate) }.sortedByDescending { it.releasedSoFar } val bestNext = nextSteps.maxOfOrNull { it.releasedHere } if (bestNext == null || bestNext <= 0) { println("released ${state.releasedSoFar} with remaining ${state.unOpened.map { it.id }}") return state.releasedSoFar } var currentBest = bestSoFar for (n in nextSteps) { currentBest = max(currentBest, maxReleaseFrom(n, currentBest)) } return currentBest } fun maxReleaseFrom(state: SearchStateDouble, bestSoFar: Int): Int { val bestUsedMinutesPossible = (state.remainingFast downTo 1 step 2).toList() + (state.remainingFast downTo 1 step 2).toList() val optimistic = state.unOpened.map { it.rate }.sortedDescending().zip(bestUsedMinutesPossible.sortedDescending()) .sumOf { (rate, minutes) -> rate * minutes } + state.releasedSoFar if (optimistic <= bestSoFar) { return 0 } val nextSteps = generateNextSteps(state) val bestNext = nextSteps.maxOfOrNull { it.releasedHere } if (bestNext == null || bestNext <= 0) { return state.releasedSoFar } var currentBest = bestSoFar for (n in nextSteps) { currentBest = max(currentBest, maxReleaseFrom(n, currentBest)) } return currentBest } private fun generateNextSteps(state: SearchStateDouble): List<SearchStateDouble> { return state.unOpened.flatMap { v1 -> state.unOpened.map { v1 to it } } .filter { it.first != it.second } .map { (v1, v2) -> val remaining1 = state.remainingFast - distances[state.positionFast to v1.id]!! - 1 val remaining2 = state.remainingSlow - distances[state.positionSlow to v2.id]!! - 1 if (remaining1 > state.remainingSlow) { SearchStateDouble( v1.id, state.positionSlow, remaining1, state.remainingSlow, remaining1 * v1.rate, state.unOpened - setOf(v1), state.releasedSoFar + remaining1 * v1.rate ) } else if (remaining1 >= remaining2) { SearchStateDouble( v1.id, v2.id, remaining1, remaining2, remaining1 * v1.rate + remaining2 * v2.rate, state.unOpened - setOf(v1, v2), state.releasedSoFar + remaining1 * v1.rate + remaining2 * v2.rate ) } else { SearchStateDouble( v2.id, v1.id, remaining2, remaining1, remaining1 * v1.rate + remaining2 * v2.rate, state.unOpened - setOf(v1, v2), state.releasedSoFar + remaining1 * v1.rate + remaining2 * v2.rate ) } } } } data class SearchState( val position: String, val remainingMinutes: Int, val releasedHere: Int, val unOpened: Set<Valve>, val releasedSoFar: Int, ) data class SearchStateDouble( val positionFast: String, val positionSlow: String, val remainingFast: Int, val remainingSlow: Int, val releasedHere: Int, val unOpened: Set<Valve>, val releasedSoFar: Int, ) private fun parse(input: List<String>): Map<String, Valve> { val valves = input.map { Valve.of(it) } val map = valves.associateBy { it.id } valves.forEach { it.updateNeighbors(map) } return map } fun part1(input: List<String>, time: Int = 30): Int { val valves = parse(input) println(valves) println("nonzero " + valves.filterValues { it.rate > 0 }) println("nonzero count " + valves.count { it.value.rate > 0 }) val s = PressureSearch(valves) return s.maxReleaseFrom(SearchState("AA", time, 0, valves.values.filter { it.rate != 0 }.toSet(), 0), 0) } fun part2(input: List<String>, time: Int = 26): Int { val valves = parse(input) val s = PressureSearch(valves) val beginning = SearchStateDouble("AA", "AA", time, time, 0, valves.values.filter { it.rate != 0 }.toSet(), 0) return s.maxReleaseFrom(beginning, 0) } fun part2Cheat(input: List<String>, unopened: List<String>, time: Int = 26): Int { val valves = parse(input) val s = PressureSearch(valves) val beginning = SearchState("AA", time, 0, valves.values.filter { it.rate != 0 }.toSet(), 0) val singlePressure = s.maxReleaseFrom(beginning, 0) val secondBeginning = SearchState("AA", time, 0, valves.filterKeys { it in unopened }.values.toSet(), 0) return singlePressure + s.maxReleaseFrom(secondBeginning, 0) } } fun main() { val testInput = """ Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valves GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valves II """.trimIndent().split("\n") val cheatBreak = """ Valve AA has flow rate=0; tunnels lead to valves BB, EE Valve BB has flow rate=100; tunnels lead to valves AA, CC Valve CC has flow rate=100; tunnels lead to valves BB, DD Valve DD has flow rate=1; tunnels lead to valves CC, EE Valve EE has flow rate=1; tunnels lead to valves DD, AA """.trimIndent().split("\n") println("------Tests------") println("part 1: " + Day16.part1(testInput)) println("part 2: " + Day16.part2(testInput)) println("part 2 for cheatBreaker normal solution: " + Day16.part2(cheatBreak, 6)) println("part 2 for cheatBreaker cheated solution: " + Day16.part2Cheat(cheatBreak, listOf("DD", "EE"), 6)) println("------Real------") val input = readInput("resources/2022/day16") println("part 1: " + Day16.part1(input)) println("part 2 cheat: " + Day16.part2Cheat(input, listOf("DM", "XS", "KI", "DU", "ZK", "LC", "IY", "VF", "BD"))) println("part 2: " + Day16.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
9,616
advent-of-code
Apache License 2.0
src/Day05.kt
djleeds
572,720,298
false
{"Kotlin": 43505}
import java.util.* typealias Stacks = List<Stack<Crate>> typealias CrateMover = (src: Stack<Crate>, dst: Stack<Crate>, count: Int) -> Unit private object Parser { private const val FIELD_SIZE = 4 private val newline = System.lineSeparator() private val movementRegex = Regex("move (\\d+) from (\\d+) to (\\d+)") fun parse(input: String): Pair<() -> Stacks, List<Movement>> { val (crane, movement) = input.split(newline.repeat(2)).map { it.split(newline) } return { parseStacks(crane) } to movement.filter { it.isNotEmpty() }.map(::parseMovement) } private fun parseMovement(input: String) = movementRegex.find(input)?.groupValues?.let { Movement(it[1].toInt(), it[2].toInt(), it[3].toInt()) } ?: throw IllegalArgumentException() private fun parseStacks(input: List<String>): List<Stack<Crate>> { val lines = input.reversed().drop(1) return (1..input.last().length step FIELD_SIZE).map { index -> lines.fold(Stack<Crate>()) { stack, item -> stack.apply { item.getOrNull(index)?.takeUnless { it == ' ' }?.let { push(Crate(it)) } } } } } } data class Movement(val count: Int, val sourceId: Int, val destinationId: Int) data class Crate(val id: Char) class Crane(private val stacks: Stacks, private val move: CrateMover) { val message: String get() = stacks.map { it.peek().id }.joinToString("") fun move(movements: List<Movement>) = movements.forEach(::move) private fun move(movement: Movement) = with(movement) { move(stacks[sourceId - 1], stacks[destinationId - 1], count) } } val crateMover9000: CrateMover = { source, destination, count -> repeat(count) { destination.push(source.pop()) } } val crateMover9001: CrateMover = { source, destination, count -> (0 until count).map { source.pop() }.reversed().forEach(destination::push) } fun main() { fun part1(stacks: Stacks, movements: List<Movement>): String = Crane(stacks, crateMover9000).apply { move(movements) }.message fun part2(stacks: Stacks, movements: List<Movement>): String = Crane(stacks, crateMover9001).apply { move(movements) }.message Parser.parse(readInputAsText("Day05_test")).let { (stacks, movements) -> check(part1(stacks(), movements) == "CMZ") check(part2(stacks(), movements) == "MCD") } Parser.parse(readInputAsText("Day05")).let { (stacks, movements) -> println(part1(stacks(), movements)) println(part2(stacks(), movements)) } }
0
Kotlin
0
4
98946a517c5ab8cbb337439565f9eb35e0ce1c72
2,509
advent-of-code-in-kotlin-2022
Apache License 2.0
src/Day9.kt
sitamshrijal
574,036,004
false
{"Kotlin": 34366}
import kotlin.math.abs import kotlin.math.sign fun main() { fun parse(input: List<String>): List<Pair<Direction, Int>> = input.map { val (direction, count) = it.split(" ") Direction.parse(direction) to count.toInt() } fun part1(input: List<String>): Int { val movements = parse(input) // Starting position val s = Position(0, 0) var head = s var tail = s val visited = mutableListOf(tail) movements.forEach { (direction, count) -> repeat(count) { head = head.move(direction) if (!tail.isNear(head)) { tail = tail.moveNear(head) visited += tail } } } return visited.distinct().size } fun part2(input: List<String>): Int { val movements = parse(input) // Starting position val s = Position(0, 0) val knots = MutableList(10) { s } val visited = mutableListOf(s) movements.forEach { (direction, count) -> repeat(count) { // Move the head knots[0] = knots[0].move(direction) (1..9).forEach { index -> val position = knots[index] val follow = knots[index - 1] if (!position.isNear(follow)) { knots[index] = position.moveNear(follow) if (index == 9) { visited += knots[9] } } } } } return visited.distinct().size } val input = readInput("input9") println(part1(input)) println(part2(input)) } enum class Direction(val dx: Int, val dy: Int) { LEFT(-1, 0), RIGHT(1, 0), UP(0, 1), DOWN(0, -1); companion object { fun parse(string: String): Direction = values().find { it.name.startsWith(string) }!! } } data class Position(val x: Int, val y: Int) { fun isNear(other: Position): Boolean = abs(x - other.x) <= 1 && abs(y - other.y) <= 1 fun move(direction: Direction): Position = Position(x + direction.dx, y + direction.dy) fun moveNear(other: Position): Position { val dx = x - other.x val dy = y - other.y return Position(x - dx.sign, y - dy.sign) } }
0
Kotlin
0
0
fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d
2,385
advent-of-code-2022
Apache License 2.0
src/day08/Day08.kt
robin-schoch
572,718,550
false
{"Kotlin": 26220}
package day08 import AdventOfCodeSolution fun main() { Day08.run() } class Forest(private val trees: Array<IntArray>) { operator fun Forest.get(coord: Pair<Int, Int>): Int = trees[coord.second][coord.first] fun searchFromLeft() = searchForVisibleTrees(trees.indices, trees[0].indices) { x, y -> x to y } fun searchFromRight() = searchForVisibleTrees(trees.indices, trees[0].lastIndex downTo 0) { x, y -> x to y } fun searchFromTop() = searchForVisibleTrees(trees[0].lastIndex downTo 0, trees.indices) { x, y -> y to x } fun searchFromBottom() = searchForVisibleTrees(trees[0].indices, trees.lastIndex downTo 0) { x, y -> y to x } private fun searchForVisibleTrees(rows: IntProgression, row: IntProgression, dir: (x: Int, y: Int) -> Pair<Int, Int>) = rows.fold(setOf<Pair<Int, Int>>()) { set, i -> row.fold(-1 to setOf<Pair<Int, Int>>()) { acc, j -> dir(i, j).let { when (get(it) > acc.first) { true -> get(it) to (acc.second + it) false -> acc } } }.second + set } fun calculateScenicScore() = trees.flatMapIndexed { index, treeRow -> treeRow.mapIndexed { jndex, _ -> (index to jndex).let { lookDown(it) * lookUp(it) * lookLeft(it) * lookRight(it) } } }.max() private fun look(coordinate: Pair<Int, Int>, bounded: (Pair<Int, Int>) -> Boolean, bounds: Int, generator: (Pair<Int, Int>) -> Pair<Int, Int>?): Int { return (generateSequence(coordinate, generator) .takeWhile(bounded) .map { get(it) } .zipWithNext() .takeWhile { it.second < get(coordinate) } .count() + 1).coerceAtMost(bounds) } private fun lookUp(coordinate: Pair<Int, Int>) = look(coordinate, { it.first >= 0 }, coordinate.first) { it.first - 1 to it.second } private fun lookDown(coordinate: Pair<Int, Int>) = look(coordinate, { it.first < trees.size }, trees.size - coordinate.first - 1) { it.first + 1 to it.second } private fun lookLeft(coordinate: Pair<Int, Int>) = look(coordinate, { it.second >= 0 }, coordinate.second) { it.first to it.second - 1 } private fun lookRight(coordinate: Pair<Int, Int>) = look(coordinate, { it.second < trees[0].size }, trees[0].size - coordinate.second - 1) { it.first to it.second + 1 } companion object { fun seed(matrix: List<String>): Forest { return matrix .map { it.map { char -> char.digitToInt() }.toIntArray() } .toTypedArray() .let { Forest(it) } } } } object Day08 : AdventOfCodeSolution<Int, Int> { override val testSolution1 = 21 override val testSolution2 = 8 override fun part1(input: List<String>) = with(Forest.seed(input)) { searchFromLeft() + searchFromRight() + searchFromTop() + searchFromBottom() }.size override fun part2(input: List<String>) = Forest.seed(input).calculateScenicScore() }
0
Kotlin
0
0
fa993787cbeee21ab103d2ce7a02033561e3fac3
3,124
aoc-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-12.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2023, "12-input") val test1 = readInputLines(2023, "12-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 = input.sumOf { line -> val (row, groups) = line.split(' ').let { (row, g) -> row to g.split(',').map(String::toInt) } possible(row, groups, mutableMapOf()) } private fun part2(input: List<String>): Long = input.sumOf { line -> val (row, groups) = line.split(' ').let { (row, g) -> row to g.split(',').map(String::toInt) } val newRows = List(5) { row }.joinToString(separator = "?") val newGroups = List(5) { groups }.flatten() possible(newRows, newGroups, mutableMapOf()) } private fun possible(row: String, groups: List<Int>, cache: MutableMap<Pair<String, List<Int>>, Long>): Long = when { row to groups in cache -> cache[row to groups]!! row.isEmpty() && groups.isEmpty() -> 1 row.isEmpty() && groups.isNotEmpty() -> 0 groups.isEmpty() -> if (row.any { it == '#' }) 0 else 1 else -> { val head = row.first() val tail = row.drop(1) when (head) { '.' -> possible(tail.dropWhile { it == '.' }, groups, cache) '#' -> starting(row, groups, cache) '?' -> possible(tail, groups, cache) + starting(row, groups, cache) else -> error("impossible") } } }.also { cache[row to groups] = it } private fun starting(row: String, groups: List<Int>, cache: MutableMap<Pair<String, List<Int>>, Long>): Long { val first = groups.first() val next = groups.drop(1) if (row.length < first) return 0 if (row.take(first).any { it == '.' }) return 0 val rest = row.drop(first) return when { rest.isEmpty() && next.isEmpty() -> 1 rest.isEmpty() && next.isNotEmpty() -> 0 rest.startsWith('#') -> 0 else -> possible(rest.drop(1), next, cache) } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
2,200
advent-of-code
MIT License
src/Day11.kt
oleksandrbalan
572,863,834
false
{"Kotlin": 27338}
import java.util.Deque import java.util.LinkedList fun main() { val part1Monkeys = parseMonkeys() part1Monkeys.playWithItems(PART1_ROUNDS) { this / 3 } val part1 = part1Monkeys.calculateMonkeyBusiness() println("Part2: $part1") val part2Monkeys = parseMonkeys() val commonTestBy = part2Monkeys.fold(1) { acc, monkey -> acc * monkey.testBy } part2Monkeys.playWithItems(PART2_ROUNDS) { this % commonTestBy } val part2 = part2Monkeys.calculateMonkeyBusiness() println("Part2: $part2") } private fun parseMonkeys(): List<Monkey> = readInput("Day11") .filterNot { it.isEmpty() } .chunked(6) { parseMonkey(it) } private fun List<Monkey>.playWithItems(rounds: Int, adjustWorryLevel: Long.() -> Long) = repeat(rounds) { forEach { monkey -> while (monkey.items.isNotEmpty()) { val oldWorryLevel = monkey.items.pop() val newWorryLevel = monkey.inspect(oldWorryLevel).adjustWorryLevel() val index = monkey.nextMonkey(newWorryLevel) this[index].items.push(newWorryLevel) } } } private fun List<Monkey>.calculateMonkeyBusiness(): Long = sortedByDescending { it.inspected } .take(2) .fold(1L) { acc, monkey -> acc * monkey.inspected } private fun parseMonkey(info: List<String>): Monkey { fun String.parseItems(): LinkedList<Long> = LinkedList<Long>().apply { addAll(split(":")[1].trim().split(",").map { it.trim().toLong() }) } fun String.parseOperation(): (Long) -> Long { val rightSide = split("=")[1].trim().split(" ") val operand1 = rightSide[0].toLongOrNull() val operand2 = rightSide[2].toLongOrNull() return when (rightSide[1]) { "+" -> { { (operand1 ?: it) + (operand2 ?: it) } } "*" -> { { (operand1 ?: it) * (operand2 ?: it) } } else -> error("Operation '${rightSide[1]}' is not supported") } } fun String.parseTestBy(): Int = split(" ").last().toInt() fun List<String>.parseTest(): (Boolean) -> Int { val monkeys = takeLast(2).map { it.split(" ").last().toInt() } return { if (it) monkeys[0] else monkeys[1] } } return Monkey( items = info[1].parseItems(), testBy = info[3].parseTestBy(), operation = info[2].parseOperation(), test = info.parseTest() ) } private class Monkey( val items: Deque<Long>, val testBy: Int, val operation: (Long) -> Long, val test: (Boolean) -> Int, ) { var inspected: Long = 0 fun inspect(item: Long): Long { inspected += 1 return operation(item) } fun nextMonkey(item: Long): Int = test(item % testBy == 0L) } private const val PART1_ROUNDS = 20 private const val PART2_ROUNDS = 10_000
0
Kotlin
0
2
1493b9752ea4e3db8164edc2dc899f73146eeb50
2,915
advent-of-code-2022
Apache License 2.0
y2018/src/main/kotlin/adventofcode/y2018/Day15.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2018 import adventofcode.io.AdventSolution import kotlin.math.abs object Day15 : AdventSolution(2018, 15, "Beverage Bandits") { override fun solvePartOne(input: String): Int { val map = parse(input) val combatants = mutableListOf<Combatant>() for (y in map.indices) { for (x in map[0].indices) { if (map[y][x] == Tile.Goblin) combatants.add(Combatant(Point(x, y), 200, 3, false)) if (map[y][x] == Tile.Elf) combatants.add(Combatant(Point(x, y), 200, 3, true)) } } val r = simulate(map, combatants) return r * combatants.sumOf { it.hp } } override fun solvePartTwo(input: String): Int { for (power in 4..30) { val map = parse(input) val combatants = mutableListOf<Combatant>() for (y in map.indices) { for (x in map[0].indices) { if (map[y][x] == Tile.Goblin) combatants.add(Combatant(Point(x, y), 200, 3, false)) if (map[y][x] == Tile.Elf) combatants.add(Combatant(Point(x, y), 200, power, true)) } } val elves = combatants.filter { it.isElf } val r = simulate(map, combatants) if (elves.any { !it.isAlive() }) continue return r * combatants.sumOf { it.hp } } return -1 } private fun simulate(map: MutableList<MutableList<Tile>>, combatants: MutableList<Combatant>): Int { var rounds = 0 while (true) { for (attacker in combatants.sortedBy { it.p.x }.sortedBy { it.p.y }) { if (!attacker.isAlive()) continue if (combatants.distinctBy { it.isElf }.size == 1) return rounds val target: Combatant? = findAdjacentTarget(attacker, combatants) if (target == null) moveTo(attacker, map, combatants) findAdjacentTarget(attacker, combatants) ?.let { it.hp -= attacker.power if (!it.isAlive()) { combatants.remove(it) map[it.p.y][it.p.x] = Tile.Open // if (!attacker.isElf) return -1 } } } rounds++ } } private fun findAdjacentTarget(attacker: Combatant, combatants: MutableList<Combatant>): Combatant? = combatants .asSequence() .filter { it.isValidTarget(attacker) } .sortedBy { it.p.x } .sortedBy { it.p.y } .sortedBy { it.hp } .firstOrNull() private fun moveTo(attacker: Combatant, map: MutableList<MutableList<Tile>>, combatants: MutableList<Combatant>) { val targetsByDistance = combatants .asSequence() .filter { it.isElf != attacker.isElf } .filter { it.hp > 0 } .flatMap { it.p.neighbors().asSequence() } .distinct() .filter { map.isOpen(it) } .associateWith { distanceTo(attacker.p, it, map) } val min = targetsByDistance.values.minOrNull() ?: return if (min == Int.MAX_VALUE) return val destination = targetsByDistance.keys.sortedBy { it.x }.sortedBy { it.y }.find { targetsByDistance[it] == min } ?: return val stepTo = attacker.p.neighbors() .filter { map.isOpen(it) } .minByOrNull { distanceTo(it, destination, map) } ?: return map[attacker.p.y][attacker.p.x] = Tile.Open attacker.p = stepTo map[attacker.p.y][attacker.p.x] = if (attacker.isElf) Tile.Elf else Tile.Goblin } private fun distanceTo(from: Point, to: Point, map: MutableList<MutableList<Tile>>): Int { var open = listOf(from) val closed = mutableSetOf<Point>() var steps = 0 while (open.isNotEmpty()) { if (open.any { it == to }) return steps steps++ closed += open open = open .flatMap { it.neighbors() } .distinct() .filter { it !in closed } .filter { map.isOpen(it) } } return Int.MAX_VALUE } private fun List<List<Tile>>.isOpen(it: Point) = getOrNull(it.y)?.getOrNull(it.x) == Tile.Open data class Point(val x: Int, val y: Int) { fun neighbors() = listOf(Point(x, y - 1), Point(x - 1, y), Point(x + 1, y), Point(x, y + 1)) } data class Combatant(var p: Point, var hp: Int, val power: Int, val isElf: Boolean) { fun isValidTarget(attacker: Combatant) = isAdjecentTo(attacker) && isElf != attacker.isElf && isAlive() private fun isAdjecentTo(attacker: Combatant) = abs(p.y - attacker.p.y) + abs(p.x - attacker.p.x) == 1 fun isAlive() = hp > 0 } private fun parse(input: String): MutableList<MutableList<Tile>> { return input.lines().map { it.map { tile -> when (tile) { '#' -> Tile.Closed '.' -> Tile.Open 'E' -> Tile.Elf 'G' -> Tile.Goblin else -> throw IllegalArgumentException("unknown") } }.toMutableList() }.toMutableList() } private enum class Tile { Open, Closed, Elf, Goblin } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
5,622
advent-of-code
MIT License
src/Day07.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
fun main() { data class File(val name: String, val size: Int) class Dir { var parentDirectory: Dir? = null val files: MutableList<File> = mutableListOf<File>() val subDirectories: MutableMap<String, Dir> = mutableMapOf<String, Dir>() fun traverseSize(recorder: (Int) -> Unit): Int = listOf( this.files.sumOf { f -> f.size }, this.subDirectories.values.sumOf { d -> d.traverseSize(recorder) } ).sum().apply { recorder(this) } fun goToParent(): Dir? = this.parentDirectory fun addFile(f: File) = this.files.add(f) fun addDirectory(name: String) = this.subDirectories?.put(name, Dir().apply { this.parentDirectory = this@Dir }) fun goToSubDirectory(name: String): Dir = this.subDirectories[name]!! } fun parseCommands(input: List<String>): List<List<String>> = input.fold(mutableListOf<MutableList<String>>()) { acc, ele -> if (ele.first() == '$') { acc.add(mutableListOf()) } acc.last().add(ele) acc } class Solution(input: List<String>) { var root: Dir? init { var cur: Dir? = null parseCommands(input).forEach { group -> when (group[0]) { "$ cd /" -> cur = Dir() "$ cd .." -> cur = cur?.goToParent() "$ ls" -> group.drop(1).forEach { line -> line.split(" ").run { if (this[0] == "dir") { cur?.addDirectory(this[1]) } else { cur?.addFile(File(this[1], this[0].toInt())) } } } else -> cur = cur?.goToSubDirectory(group[0].substring("$ cd ".length)) } }.run { while (cur?.parentDirectory != null) cur = cur?.goToParent() } this.root = cur } fun findSizes(): List<Int> = mutableListOf<Int>().apply { [email protected]?.traverseSize { this.add(it) } } fun findTotalSize(filter: (v: Int) -> Boolean): Int = this.findSizes().filter(filter).sum() } fun part1(input: List<String>) = Solution(input).findTotalSize { v -> v <= 100000 } fun part2(input: List<String>): Int = Solution(input).findSizes().run { this.filter { it >= this.max().minus(40000000) }.minOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
2,878
advent-of-code-kotlin-2022
Apache License 2.0
src/day13/Day13.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day13 import readText // Parsing like an animal 🤯 fun format(line: String): List<Any> = buildList { var index = 0 var number = "" while (true) { if (index > line.lastIndex) break var char = line[index++] when { char == ',' && number.isNotBlank() -> { add(number.toInt()) number = "" } char.isDigit() -> number += char char == '[' -> { val start = index var depth = 1 while (depth != 0) { char = line[index++] if (char == '[') depth++ if (char == ']') depth-- } val end = index - 1 add(format(line.substring(start until end)).toList()) } } } if (number.isNotBlank()) add(number.toInt()) } .also { check("[${line}]" == it.toString().replace(" ", "")) { "Failed to parse $line" } } // Why is this not in stdlib 🤯 fun <T, R> Iterable<T>.zipWithNull(other: Iterable<R>): List<Pair<T?, R?>> = buildList { val first = [email protected]() val second = other.iterator() while (first.hasNext() || second.hasNext()) { val left = if (first.hasNext()) first.next() else null val right = if (second.hasNext()) second.next() else null add(left to right) } } operator fun <T> List<T>.compareTo(other: List<T>): Int { val list = zipWithNull(other) var order: Int for ((left, right) in list) { order = when { left is Int && right is Int -> -left.compareTo(right) left is Int && right is List<*> -> listOf(left).compareTo(right) left is List<*> && right is Int -> left.compareTo(listOf(right)) left is List<*> && right is List<*> -> left.compareTo(right) left == null && (right is List<*> || right is Int) -> 1 // left ran out of numbers (left is List<*> || left is Int) && right == null -> -1 // right ran out of numbers else -> 0 } if (order != 0) return order } return 0 } val Dividers = listOf(listOf(listOf(2)), listOf(listOf(6))) fun main() { fun part1(input: String): Int = input.split("\n\n") .map { pair -> pair.split("\n") } .mapIndexed { index, (left, right) -> index to format(left).compareTo(format(right)) } .filter { (_, order) -> order > 0 } .sumOf { (index, _) -> index + 1 } fun part2(input: String): Int = input .split("\n").filter { it.isNotBlank() } .map { format(it) } .plus(Dividers) .sortedWith { first, second -> second.compareTo(first) } .let { sorted -> val (start, end) = Dividers val startIndex = sorted.indexOf(start) + 1 val endIndex = sorted.indexOf(end) + 1 startIndex * endIndex } val testInput = readText("day13/test.txt") val input = readText("day13/input.txt") check(part1(testInput) == 13) println(part1(input)) check(part2(testInput) == 140) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
2,894
advent-of-code-22
Apache License 2.0
src/main/kotlin/day15/Day15.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day15 import execute import parseRecords import readAllText import kotlin.math.absoluteValue private fun Pair<Long, Long>.rotate45ish() = let { (x0, y0) -> val x1 = x0 - y0 val y1 = x0 + y0 x1 to y1 } private fun Pair<Long, Long>.rotateBack45ish() = let { (x1, y1) -> val x0 = (x1 + y1) / 2 val y0 = x0 - x1 x0 to y0 } tailrec fun LongRange.splitRange( cuts: List<Long>, cutIndex: Int = 0, acc: List<LongRange> = emptyList() ): List<LongRange> = if (first > last) acc else if (cuts.lastIndex < cutIndex) acc + listOf(this) else { val c = cuts[cutIndex] if (c < first) splitRange(cuts, cutIndex + 1, acc) else (c + 1..last).splitRange( cuts, cutIndex + 1, acc + listOf(first until c, c..c).filter { it.first <= it.last } ) } fun <T> List<T>.merge(mergeOp: (T, T) -> List<T>): List<T> = fold<T, MutableList<T>>(mutableListOf()) { acc, t -> acc.apply { if (isEmpty()) add(t) else addAll(mergeOp(removeLast(), t)) } }.toList() fun part1(input: String): Long { val data = input.parseRecords(regex, ::parse).toList() val testLine = if (data.first().first.first == 2L) 10L else 2000000L val beaconsAlreadyOnTestLine = data .map { (_, beacon) -> beacon } .filter { (_, y) -> y == testLine } .toSet().size val ranges = data .map { (sensor, beacon) -> val (sx, sy) = sensor val (bx, by) = beacon val dist = (sx - bx).absoluteValue + (sy - by).absoluteValue val dist10 = dist - (sy - testLine).absoluteValue sx - dist10..sx + dist10 } .filter { it.first <= it.last } .sortedWith(compareBy<LongRange> { it.first }.thenBy { it.last }) val cuts = buildSet { ranges.forEach { add(it.first); add(it.last) } } .toList().sorted() return ranges.flatMap { it.splitRange(cuts) } .map { it.first to it.last } .filter { (s, e) -> s <= e } .toSet().sumOf { (s, e) -> e - s + 1 } - beaconsAlreadyOnTestLine } fun part2(input: String): Long { val sensors = input.parseRecords(regex, ::parse).map { (sensor, beacon) -> val (sx, sy) = sensor val (bx, by) = beacon val dist = (sx - bx).absoluteValue + (sy - by).absoluteValue sensor to dist }.toList() val sensors45 = sensors.map { (s, r) -> s.rotate45ish() to r } val ranges45 = sensors45.map { (s, d) -> val (x, y) = s (x - d..x + d) to (y - d..y + d) } val horizCuts45 = buildSet { ranges45.forEach { (h, v) -> add(h.first); add(h.last) } } .sorted() val vertCuts45 = buildSet { ranges45.forEach { (h, v) -> add(v.first); add(v.last) } } .sorted() val blocks45: List<Pair<LongRange, List<LongRange>>> = ranges45.flatMap { (h, v) -> v.splitRange(vertCuts45) // .filter { it.first == it.last } .flatMap { vv -> h.splitRange(horizCuts45).map { hh -> hh to vv } } } .sortedWith(compareBy<Pair<LongRange, LongRange>> { it.first.first }.thenBy { it.first.last } .thenBy { it.second.first }.thenBy { it.second.last }) .groupBy { it.first }.map { (h, l) -> h to l.map { it.second } } val mergedBlocks45 = blocks45.map { (h, vl) -> h to vl.merge { a, b -> if (a.last >= b.first - 1) listOf(a.first..b.last) else listOf(a, b) } } .merge { (a, al), (b, bl) -> if (a.last >= b.first - 1 && al == bl) listOf(a.first..b.last to al) else listOf(a to al, b to bl) } val broken45 = mergedBlocks45.first { it.second.size > 1 } .let { (h, vl) -> h.single() to vl.first().last + 1 } val broken = broken45.rotateBack45ish() return broken.let { (x, y) -> y + x * 4000000 } } private val regex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex() private fun parse(matchResult: MatchResult) = matchResult.destructured.let { (a, b, c, d) -> (a.toLong() to b.toLong()) to (c.toLong() to d.toLong()) } fun main() { val input = readAllText("local/day15_input.txt") val test = """ Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3 """.trimIndent() execute(::part1, test, 26) execute(::part1, input, 5525847) execute(::part2, test, 56000011) execute(::part2, input, 13340867187704) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
5,255
advent-of-code-2022
MIT License
src/Day02/Day02.kt
Nathan-Molby
572,771,729
false
{"Kotlin": 95872, "Python": 13537, "Java": 3671}
package Day02 import readInput enum class RPS { ROCK, PAPER, SCISSORS; fun kryptonite(inputRPS: RPS): RPS { return when(inputRPS) { RPS.ROCK -> RPS.PAPER RPS.PAPER -> RPS.SCISSORS RPS.SCISSORS -> RPS.ROCK } } fun archNemesis(inputRPS: RPS): RPS { return when(inputRPS) { RPS.ROCK -> RPS.SCISSORS RPS.PAPER -> RPS.ROCK RPS.SCISSORS -> RPS.PAPER } } } class RPSRound(playerInput: String, opponentInput: String) { var playerInput: RPS = rpsFromString(playerInput) val opponentInput: RPS = rpsFromString(opponentInput) fun calculatePlayerScore(): Int { var playerScore = 0 //calculate shape score playerScore += when(playerInput) { RPS.ROCK -> 1 RPS.PAPER -> 2 RPS.SCISSORS -> 3 } //calculate outcome score playerScore += when(opponentInput) { playerInput.archNemesis(playerInput) -> 6 playerInput.kryptonite(playerInput) -> 0 else -> 3 } return playerScore } } fun rpsFromString(inputString: String): RPS { return when(inputString) { "A", "X" -> RPS.ROCK "B", "Y" -> RPS.PAPER "C", "Z" -> RPS.SCISSORS else -> RPS.ROCK } } fun main() { fun part1(input: List<String>): Int { var rounds = mutableListOf<RPSRound>() for (row in input) { val rowValues = row.split(" ") rounds.add(RPSRound(rowValues[1], rowValues[0])) } return rounds.map { it.calculatePlayerScore() }.sum() } fun part2(input: List<String>): Int { var rounds = mutableListOf<RPSRound>() for(row in input) { val rowValues = row.split(" ") var currentRound = RPSRound(rowValues[0], rowValues[0]) currentRound.playerInput = when(rowValues[1]) { "X" -> currentRound.opponentInput.archNemesis(currentRound.opponentInput) "Y" -> currentRound.opponentInput "Z" -> currentRound.opponentInput.kryptonite(currentRound.opponentInput) else -> RPS.ROCK } rounds.add(currentRound) } return rounds.map { it.calculatePlayerScore() }.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02","Day02_test") check(part1(testInput) == 15) val input = readInput("Day02","Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
750bde9b51b425cda232d99d11ce3d6a9dd8f801
2,605
advent-of-code-2022
Apache License 2.0
src/year_2023/day_06/Day06.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_06 import readInput fun List<Long>.product(): Long { var product = 0L this.forEach { value -> if (product == 0L) { product = value } else { product *= value } } return product } object Day06 { /** * */ fun solutionOne(text: List<String>): Long { val times = text[0].split(" ").filter { it.isNotEmpty() }.drop(1).map { it.toLong() } val distances = text[1].split(" ").filter { it.isNotEmpty() }.drop(1).map { it.toLong() } return times.indices.map { round -> val totalTime = times[round] val currentDistanceRecord = distances[round] winCount(totalTime, currentDistanceRecord) }.product() } /** * */ fun solutionTwo(text: List<String>): Long { val times = text[0].filter { it != ' ' }.split(":").drop(1).map { it.toLong() } val distances = text[1].filter { it != ' ' }.split(":").drop(1).map { it.toLong() } return winCount(times[0], distances[0]) } private fun winCount(totalTime: Long, distance: Long): Long { var winCount = 0L for (windUpTime in 1 until totalTime) { if (windUpTime * (totalTime-windUpTime) > distance) { winCount += 1 } else if (winCount > 0) { break } } return winCount } } fun main() { val text = readInput("year_2023/day_06/Day06.txt") val solutionOne = Day06.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day06.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
1,675
advent_of_code
Apache License 2.0
src/day11/Day11.kt
martin3398
572,166,179
false
{"Kotlin": 76153}
package day11 import readInput class Monkey( private val items: MutableList<Long>, private val operation: String, private val testDivisor: Long, private val trueTargetMonkey: Int, private val falseTargetMonkey: Int, private val modulo: Int ) { private var inspectionCount = 0 fun inspectNext(divisor: Int = 3): Pair<Int, Long> { inspectionCount++ val worryLevel = performOperation(items.removeFirst()) / divisor % modulo val target = if (worryLevel % testDivisor == 0L) trueTargetMonkey else falseTargetMonkey return Pair(target, worryLevel) } private fun performOperation(item: Long): Long { val operator = operation[4] val operandRaw = operation.split(" ").last() val operand = if (operandRaw == "old") item else operandRaw.toLong() return if (operator == '*') item * operand else item + operand } fun hasNext() = items.isNotEmpty() fun addItem(item: Long) = items.add(item) fun getInspectionCount() = inspectionCount } fun main() { fun simulate(input: List<Monkey>, count: Int, divisor: Int) = repeat(count) { input.forEach { while (it.hasNext()) { val (next, item) = it.inspectNext(divisor) input[next].addItem(item) } } } fun getMax2Product(input: List<Monkey>): Long { val inspectionCounts = input.map { it.getInspectionCount() }.toMutableList() val max1 = inspectionCounts.max().also { inspectionCounts.remove(it) } val max2 = inspectionCounts.max() return max1.toLong() * max2.toLong() } fun part1(input: List<Monkey>) = simulate(input, 20, 3).run { getMax2Product(input) } fun part2(input: List<Monkey>) = simulate(input, 10000, 1).run { getMax2Product(input) } fun preprocess(input: List<String>): List<Monkey> { val modulo = input.indices.step(7).map { input[it + 3].split(" ").last().toInt() }.reduce { acc, e -> acc * e } return input.indices.step(7).map { i -> Monkey( input[i + 1] .split(" ") .filter { it.firstOrNull()?.isDigit() == true } .map { it.removeSuffix(",").toLong() } .toMutableList(), input[i + 2].substring(19), input[i + 3].split(" ").last().toLong(), input[i + 4].split(" ").last().toInt(), input[i + 5].split(" ").last().toInt(), modulo ) } } // test if implementation meets criteria from the description, like: val testInput = readInput(11, true) check(part1(preprocess(testInput)) == 10605L) val input = readInput(11) println(part1(preprocess(input))) check(part2(preprocess(testInput)) == 2713310158L) println(part2(preprocess(input))) }
0
Kotlin
0
0
4277dfc11212a997877329ac6df387c64be9529e
2,901
advent-of-code-2022
Apache License 2.0
src/Day09.kt
mandoway
573,027,658
false
{"Kotlin": 22353}
import kotlin.math.pow import kotlin.math.sqrt fun Pair<Int, Int>.distanceTo(other: Pair<Int, Int>) = sqrt( (first - other.first).toDouble().pow(2) + (second - other.second).toDouble().pow(2) ) operator fun Pair<Int, Int>.minus(other: Pair<Int, Int>) = first - other.first to second - other.second operator fun Pair<Int, Int>.plus(other: Pair<Int, Int>) = first + other.first to second + other.second fun Pair<Int, Int>.coerceIn(range: IntRange) = first.coerceIn(range) to second.coerceIn(range) fun Pair<Int, Int>.shouldMoveTo(other: Pair<Int, Int>) = distanceTo(other) > sqrt(2.0) fun getMoveVector(direction: String) = when (direction) { "R" -> 1 to 0 "L" -> -1 to 0 "U" -> 0 to 1 "D" -> 0 to -1 else -> error("invalid state") } fun Pair<Int, Int>.unitMoveTowards(head: Pair<Int, Int>) = (head - this).coerceIn(-1..1) fun getTotalTailPositions(input: List<String>, ropeLength: Int = 2): Int { val segments = MutableList(ropeLength) { 0 to 0 } val tailPositions = mutableSetOf(0 to 0) input.forEach { val (direction, moves) = it.split(" ") val moveVector = getMoveVector(direction) repeat(moves.toInt()) { segments[0] += moveVector segments .indices .zipWithNext() .forEach { (headIndex, tailIndex) -> val head = segments[headIndex] val tail = segments[tailIndex] if (tail.shouldMoveTo(head)) { segments[tailIndex] += tail.unitMoveTowards(head) } } tailPositions.add(segments.last()) } } return tailPositions.size } fun main() { fun part1(input: List<String>): Int { return getTotalTailPositions(input) } fun part2(input: List<String>): Int { return getTotalTailPositions(input, ropeLength = 10) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val testInput2 = readInput("Day09_test2") check(part1(testInput) == 13) check(part2(testInput) == 1) check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0393a4a25ae4bbdb3a2e968e2b1a13795a31bfe2
2,313
advent-of-code-22
Apache License 2.0
src/main/day06/Day06.kt
rolf-rosenbaum
543,501,223
false
{"Kotlin": 17211}
package day06 import readInput import second import kotlin.math.abs fun part1(input: List<String>): Int { val points = input.mapIndexed { index, line -> line.toPoint(index.toString()) } val map = mutableSetOf<Point>() (points.minOf { it.x }..points.maxOf { it.x }).forEach { x -> (points.minOf { it.y }..points.maxOf { it.y }).forEach { y -> val p = Point(x, y) val sortedBy = points.sortedBy { p.distanceTo(it) } val point = sortedBy.first() val areaId = if (point.distanceTo(p) == sortedBy.second().distanceTo(p)) "." else point.areaId map.add(Point(x, y, areaId)) } } return map.filter{it.areaId != "."}.groupingBy { it.areaId }.eachCount().maxByOrNull { it.value }?.value ?: -1 } fun part2(input: List<String>): Int { val points = input.mapIndexed { index, line -> line.toPoint(index.toString()) } val map = mutableSetOf<Point>() (points.minOf { it.x }..points.maxOf { it.x }).forEach { x -> (points.minOf { it.y }..points.maxOf { it.y }).forEach { y -> val p = Point(x, y) if (points.totalDistanceTo(p) < 10000) map.add(Point(x, y)) } } return map.size } fun main() { val input = readInput("main/day06/Day06") println(part1(input)) println(part2(input)) } data class Point(val x: Int, val y: Int, val areaId: String = "-1") { fun distanceTo(other: Point): Int = abs(x - other.x) + abs(y - other.y) } fun List<Point>.totalDistanceTo(p: Point): Int = sumOf { it.distanceTo(p) } fun String.toPoint(areaId: String): Point { val (x, y) = split(", ") return Point(x.toInt(), y.toInt(), areaId) }
0
Kotlin
0
0
dfd7c57afa91dac42362683291c20e0c2784e38e
1,722
aoc-2018
Apache License 2.0
src/day03.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
val line = readLine()!! val nBits = line.length val input = (sequenceOf(line) + generateSequence(::readLine)).map { it.toInt(2) }.toList() fun mostCommon(numbers: List<Int>, nthBit: Int): Int? = numbers.count { it and (1 shl nthBit) != 0 }.let { when { 2 * it > numbers.size -> 1 shl nthBit 2 * it < numbers.size -> 0 else -> null } } fun leastCommon(numbers: List<Int>, nthBit: Int): Int? = mostCommon(numbers, nthBit)?.inv()?.and(1 shl nthBit) fun part1(criteria: (Int) -> Int?): Int = (0 until nBits).fold(0) { acc, nthBit -> acc or (criteria(nthBit) ?: 0) } val gamma = part1 { mostCommon(input, it) } val epsilon = part1 { leastCommon(input, it) } println("part1: ${gamma * epsilon}") fun part2(criteria: (List<Int>, Int) -> Int): Int = ((nBits - 1) downTo 0).fold(input) { acc, nthBit -> if (acc.size > 1) { val mask = criteria(acc, nthBit) acc.filter { it and (1 shl nthBit) == mask } } else { acc } }.single() val oxygen = part2 { numbers, nthBit -> mostCommon(numbers, nthBit) ?: 1 shl nthBit } val co2 = part2 { numbers, nthBit -> leastCommon(numbers, nthBit) ?: 0 } println("part2: ${oxygen * co2}")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
1,255
aoc2021
The Unlicense
src/day09.kts
miedzinski
434,902,353
false
{"Kotlin": 22560, "Shell": 113}
val map = generateSequence(::readLine).map { it.map(Char::digitToInt) }.toList() typealias HeightMap = List<List<Int>> data class Point(val x: Int, val y: Int) operator fun HeightMap.get(point: Point): Int = this[point.x][point.y] fun HeightMap.points(): Sequence<Point> = (0 until size) .asSequence() .flatMap { x -> (0 until map[x].size).asSequence().map { y -> Point(x, y) } } fun Point.adjacent(): Sequence<Point> = sequenceOf( copy(x - 1, y), copy(x + 1, y), copy(x, y - 1), copy(x, y + 1), ).filter { (x, y) -> x in 0 until map.size && y in 0 until map[x].size } fun Point.isLow(): Boolean = adjacent().all { map[it] > map[this] } fun HeightMap.lowPoints(): Sequence<Point> = points().filter { it.isLow() } fun HeightMap.basins(): Sequence<Sequence<Point>> = lowPoints().map { start -> val visited = mutableSetOf(start) val queue = mutableListOf(start) generateSequence(queue::removeLastOrNull) .onEach { point -> point.adjacent() .filterNot(visited::contains) .filter { map[point] < map[it] && map[it] < 9 } .onEach { visited.add(it) } .toCollection(queue) } } val part1 = map.lowPoints().sumOf { map[it] + 1 } val part2 = map.basins() .map { it.count() } .sortedDescending() .take(3) .reduce(Int::times) println("part1: $part1") println("part2: $part2")
0
Kotlin
0
0
6f32adaba058460f1a9bb6a866ff424912aece2e
1,548
aoc2021
The Unlicense
y2019/src/main/kotlin/adventofcode/y2019/Day14.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2019 import adventofcode.io.AdventSolution import kotlin.math.ceil fun main() = Day14.solve() object Day14 : AdventSolution(2019, 14, "Space Stoichiometry") { override fun solvePartOne(input: String) = calculateOre(1L, parse(input)) override fun solvePartTwo(input: String): Long { val reactions = parse(input) val target = 1_000_000_000_000 val bounds = 1..10_000_000L return bounds.binarySearch { calculateOre(it, reactions) < target }.first } private inline fun LongRange.binarySearch(isBelowTarget: (Long) -> Boolean): LongRange { check(isBelowTarget(first)) check(!isBelowTarget(last)) var low = first var high: Long = last while (low + 1 < high) { val mid = (low + high) / 2 if (isBelowTarget(mid)) low = mid else high = mid } return low..high } private fun calculateOre(fuel: Long, reactions: Map<String, Pair<Int, List<Term>>>): Long { val requirements = mutableMapOf("FUEL" to fuel) var requiredOreCount = 0L while (requirements.any { it.value > 0L }) { val productToCreate = requirements.asIterable().first { it.value > 0L }.key val required = requirements.remove(productToCreate)!! val (amount, reagents) = reactions.getValue(productToCreate) val times = ceil(required / amount.toDouble()).toLong() requirements[productToCreate] = required - amount * times reagents.forEach { requirements.merge(it.unit, it.amount * times, Long::plus) } requiredOreCount += requirements.remove("ORE") ?: 0 } return requiredOreCount } private fun parse(input: String) = input .lineSequence() .map { it.split(" => ") } .associate { (reagents, result) -> val (amount, unit) = parseTerm(result) unit to Pair(amount, reagents.split(", ").map(this::parseTerm)) } private fun parseTerm(input: String) = input.split(" ").let { Term(it[0].toInt(), it[1]) } private data class Term(val amount: Int, val unit: String) }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,200
advent-of-code
MIT License
src/Day02.kt
VadimB95
574,449,732
false
{"Kotlin": 19743}
import java.lang.IllegalArgumentException fun main() { // 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)) println(part2(input)) } private fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { val roundInput = it.split(" ").map(String::mapToShape) val outcome = roundInput[1].round(roundInput[0]) totalScore += roundInput[1].score + outcome.score } return totalScore } private fun part2(input: List<String>): Int { var totalScore = 0 input.forEach { val roundInput = it.split(" ") val opponentShape = roundInput[0].mapToShape() val expectedOutcome = roundInput[1].mapToOutcome() val yourShape = when (expectedOutcome) { Outcome.LOSS -> opponentShape.wins Outcome.DRAW -> opponentShape Outcome.WIN -> opponentShape.loses } totalScore += yourShape.score + expectedOutcome.score } return totalScore } private enum class Shape(val representations: List<String>, val score: Int) { ROCK(listOf("A", "X"), 1), PAPER(listOf("B", "Y"), 2), SCISSORS(listOf("C", "Z"), 3) } private val Shape.wins: Shape get() = when (this) { Shape.ROCK -> Shape.SCISSORS Shape.PAPER -> Shape.ROCK Shape.SCISSORS -> Shape.PAPER } private val Shape.loses: Shape get() = when (this) { Shape.ROCK -> Shape.PAPER Shape.PAPER -> Shape.SCISSORS Shape.SCISSORS -> Shape.ROCK } private enum class Outcome(val representation: String, val score: Int) { LOSS("X", 0), DRAW("Y", 3), WIN("Z", 6) } private fun String.mapToShape(): Shape { return Shape.values().first { it.representations.contains(this) } } private fun String.mapToOutcome(): Outcome { return Outcome.values().first { it.representation == this } } private fun Shape.round(otherShape: Shape): Outcome { return when { this == otherShape -> Outcome.DRAW wins == otherShape -> Outcome.WIN loses == otherShape -> Outcome.LOSS else -> throw IllegalArgumentException() } }
0
Kotlin
0
0
3634d1d95acd62b8688b20a74d0b19d516336629
2,261
aoc-2022
Apache License 2.0
src/Day24.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import java.util.PriorityQueue data class BlizzardNode(val location: Point, val minutes: Int) fun Point.orthogonal() = listOf( Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1), ).map(::plus) class BlizzardBasin( val initialConditions: List<List<Char>>, val entrance: Point, val exit: Point, ) : Graph<BlizzardNode> { val width = initialConditions[0].size val height = initialConditions.size private val bounds = PointRegion(width, height) override fun neighbors(node: BlizzardNode): List<Pair<Int, BlizzardNode>> { val (location, minutes) = node return buildList { if (location == entrance || location == exit || !snowCovered(location, minutes + 1) ) { add(location) } location.orthogonal().forEach { neighbor -> if (neighbor == exit || neighbor == entrance || (neighbor in bounds && !snowCovered(neighbor, minutes + 1)) ) { add(neighbor) } } }.map { 1 to BlizzardNode(it, minutes + 1) } } private fun snowCovered(location: Point, minutes: Int): Boolean { val (x, y) = location return initialConditions[(y - minutes).mod(height)][x] == '^' || initialConditions[y][(x - minutes).mod(width)] == '>' || initialConditions[(y + minutes).mod(height)][x] == 'v' || initialConditions[y][(x + minutes).mod(width)] == '<' } } fun <T> `A*`( graph: Graph<T>, start: Collection<T>, goal: (T) -> Boolean, heuristic: (T) -> Int = { 0 }, ): Pair<Int, List<T>>? { val visited = mutableSetOf<T>() val frontier = PriorityQueue<Triple<Int, Int, List<T>>>(start.size) { a, b -> compareValuesBy(a, b) { it.first } } frontier.addAll(start.map { Triple(0, 0, listOf(it)) }) while(frontier.isNotEmpty()) { val (_, cost, path) = frontier.remove() val next = path.last() if (goal(next)) { return cost to path } if (!visited.add(next)) { continue } graph.neighbors(next).forEach { (edgeCost, neighbor) -> val newCost = cost + edgeCost val estimate = newCost + heuristic(neighbor) val newPath = path + neighbor frontier.add(Triple(estimate, newCost, newPath)) } } return null } fun main() { val valley = readInput("Day24").map(String::toList) val height = valley.size - 2 val entrance = Point( valley[0].indexOfFirst('.'::equals) - 1, height ) val exit = Point( valley.last().indexOfFirst('.'::equals) - 1, -1 ) val initialConditions = valley .drop(1) .dropLast(1) .reversed() .map { it.drop(1).dropLast(1) } val graph = BlizzardBasin(initialConditions, entrance, exit) val (firstTrip, _) = `A*`( graph, listOf(BlizzardNode(entrance, 0)), { it.location == exit}, { it.location.manhattanDistance(exit) } )!! println(firstTrip) val (secondTrip, _) = `A*`( graph, listOf(BlizzardNode(exit, firstTrip)), { it.location == entrance}, { it.location.manhattanDistance(entrance) } )!! val (thirdTrip, _) = `A*`( graph, listOf(BlizzardNode(entrance, firstTrip + secondTrip)), { it.location == exit}, { it.location.manhattanDistance(exit) } )!! println(firstTrip + secondTrip + thirdTrip) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
3,637
advent-of-code-2022
Apache License 2.0
13/kotlin/src/main/kotlin/se/nyquist/Main.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist import java.io.File fun main() { val lines = File("input.txt").readLines() val coordinates = lines.filter{ it.contains(',')}.map { getPair(it) }.toList() val instructionsLines = lines.filter{ it.contains('=')}.map { it.split(" ")[2].split("=") }.map { Pair(it[0], it[1]) } exercise1(coordinates, instructionsLines.toMutableList()) exercise2(coordinates, instructionsLines.toMutableList()) } fun getPair(it: String): Pair<Int, Int> { val c = it.split(",") return Pair(c[0].toInt(), c[1].toInt()) } private fun exercise1(values: List<Pair<Int, Int>>, commands: MutableList<Pair<String, String>>) { var currentValues : List<Pair<Int, Int>> = values.toList() val current = commands.removeAt(0) if (current.first == "y") { currentValues = foldVertical(currentValues, current.second.toInt()) } else if (current.first == "x") { currentValues = foldHorizontal(currentValues, current.second.toInt()) } println("Dots: ${currentValues.size}") } private fun getPrintChar ( currentValues: List<Pair<Int, Int>>, col: Int, row: Int ) : Char = if (currentValues.contains(Pair(col, row))) '*' else ' ' fun foldVertical(values: List<Pair<Int, Int>>, c: Int): List<Pair<Int, Int>> { return values.map { transformVertical(it, c) }.distinct().toList() } fun transformVertical(it: Pair<Int, Int>, c: Int) : Pair<Int, Int> { val vdiff = it.second - c if (vdiff > 0) { return Pair(it.first, c - vdiff) } return Pair(it.first, it.second) } fun foldHorizontal(values: List<Pair<Int, Int>>, c: Int): List<Pair<Int, Int>> { return values.map { transformHorizontal(it, c) }.distinct().toList() } fun transformHorizontal(it: Pair<Int, Int>, c: Int) : Pair<Int, Int> { val hdiff = it.first - c if (hdiff > 0) { return Pair(c - hdiff, it.second) } return Pair(it.first, it.second) } private fun exercise2(values: List<Pair<Int, Int>>, commands: MutableList<Pair<String, String>>) { var currentValues : List<Pair<Int, Int>> = values.toList() while (commands.isNotEmpty()) { val current = commands.removeAt(0) if (current.first == "y") { currentValues = foldVertical(currentValues, current.second.toInt()) } else if (current.first == "x") { currentValues = foldHorizontal(currentValues, current.second.toInt()) } val xmax = currentValues.maxOf { it.first } val ymax = currentValues.maxOf { it.second } println("X: $xmax Y; $ymax") } val xmax = currentValues.maxOf { it.first } val ymax = currentValues.maxOf { it.second } IntRange(0,ymax).forEach { row -> println(IntRange(0, xmax).map { col -> getPrintChar(currentValues, col, row) }.joinToString("")) } }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
2,818
adventofcode2021
Apache License 2.0
src/Day07.kt
davedupplaw
573,042,501
false
{"Kotlin": 29190}
interface Item { val name: String fun size(): Int } data class File(override val name: String, private val size: Int) : Item { override fun size() = size } class Directory( override val name: String, val parent: Directory? = null, private val files: MutableList<Item> = mutableListOf() ) : Item { override fun size() = files.sumOf { it.size() } fun addDir(name: String): Directory = files .filterIsInstance<Directory>() .find { it.name == name } ?: run { Directory(name, this).let { files.add(it); it } } fun addFile(name: String, size: Int) = files.add(File(name, size)) fun dirs() = files.filterIsInstance<Directory>() fun fullName(): String = (parent?.fullName() ?: "") + name + "/" override fun toString(): String { return """${fullName()}($files)""" } } fun main() { fun parseOutput(input: List<String>): Directory { val root = Directory("") var currentDir = root input.forEach { output -> val bits = output.split(" ") if (bits[0] == "$") { when (bits[1]) { "cd" -> currentDir = when (bits[2]) { ".." -> currentDir.parent!! "/" -> root else -> currentDir.addDir(bits[2]) } } } else { when (bits[0]) { "dir" -> currentDir.addDir(bits[1]) else -> currentDir.addFile(bits[1], bits[0].toInt()) } } } return root } fun dirSizes(root: Directory): List<Pair<String, Int>> { return root.dirs().map { dirSizes(it) }.flatten() + listOf(root.fullName() to root.size()) } fun part1(input: List<String>): Int { val root = parseOutput(input) val dirSizes = dirSizes(root) return dirSizes.filter { it.second <= 100000 }.sumOf { it.second } } fun part2(input: List<String>): Int { val root = parseOutput(input) val total = 70000000 val freeSpace = total - root.size() val dirSizes = dirSizes(root).sortedBy { it.second } val toRemove = dirSizes.find { freeSpace + it.second >= 30000000 } return toRemove!!.second } val test = readInput("Day07.test") val part1test = part1(test) println("part1 test: $part1test") check(part1test == 95437) val part2test = part2(test) println("part2 test: $part2test") check(part2test == 24933642) val input = readInput("Day07") val part1 = part1(input) println("Part1: $part1") val part2 = part2(input) println("Part2: $part2") }
0
Kotlin
0
0
3b3efb1fb45bd7311565bcb284614e2604b75794
2,733
advent-of-code-2022
Apache License 2.0
Advent-of-Code-2023/src/Day04.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
import kotlin.math.pow private const val AOC_DAY = "Day04" private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1" private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2" private const val INPUT_FILE = AOC_DAY private const val DOUBLE_POINTS = 2.0 /** * Finds and counts the points of the numbers that match the winning numbers. * The first match makes the card worth one point and each match after the first doubles the point value of that card. * @return the sum of points obtained in all the cards. */ private fun part1(input: List<String>): Int { return splitWinningNumbersFromMine(input).sumOf { card -> val matches = getMatchesCount(card) DOUBLE_POINTS.pow(matches.toDouble() - 1).toInt() } } typealias CardId = Int data class Card(val matches: Int, val instances: Int) /** * Accumulates scratchcards equal to the number of winning numbers that were a match. If card 10 were to have * 5 matching numbers, it would result in one copy each of cards 11, 12, 13, 14, and 15. * Basically, after knowing the matches with the winning numbers, the instances of the next cards are incremented based * on how many instances the current card had, i.e., if card 2 had 2 matches and 2 instances, it would increment the * instances of card 3 and card 4 twice, since card 2 has 2 instances, or more specifically, two copies of itself. * @return the sum of all instances of the cards. */ private fun part2(input: List<String>): Int { val gameMap = mutableMapOf<CardId, Card>() splitWinningNumbersFromMine(input).forEachIndexed { currentCardId, card -> val matches = getMatchesCount(card) val currentInstances = (gameMap[currentCardId]?.instances ?: 0) + 1 // Add instance of the original card gameMap[currentCardId] = Card(matches, currentInstances) // Add instances of the cards copies (0..<matches).forEach { j -> val nextCardId = currentCardId + j + 1 val nextCardInstances = gameMap[nextCardId]?.instances ?: 0 gameMap[nextCardId] = Card(0, nextCardInstances + currentInstances) } } return gameMap.values.sumOf { it.instances } } /** * Splits the input by list of winning numbers and list of numbers to be matched. * @return a list of cards with each of one those split in a list of winning numbers and numbers to be matched. */ private fun splitWinningNumbersFromMine(input: List<String>): List<List<String>> { return input .map { line -> line.split(": ", ": ")[1] } // ": " to avoid creating an unnecessary entry with "" .map { line -> line.split(" | ", " | ") } // " | 2" & " | 22" } /** * Based on the card provided, counts the matches between the numbers that one have and the winning numbers. * @return the number of matches found. */ private fun getMatchesCount(card: List<String>): Int { val winningNumbersSet = card[0].split(" ", " ").toSet() val matches = card[1] .split(" ", " ") .sumOf { if (winningNumbersSet.contains(it)) 1 else 0 as Int } return matches } fun main() { val part1ExpectedRes = 13 val part1TestInput = readInputToList(PART1_TEST_FILE) println("---| TEST INPUT |---") println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes") val part2ExpectedRes = 30 val part2TestInput = readInputToList(PART2_TEST_FILE) println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n") val input = readInputToList(INPUT_FILE) val improving = true println("---| FINAL INPUT |---") println("* PART 1: ${part1(input)}${if (improving) "\t\t== 15205" else ""}") println("* PART 2: ${part2(input)}${if (improving) "\t== 6189740" else ""}") }
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
3,751
Advent-of-Code-2023
Apache License 2.0
src/day7/Day7.kt
gautemo
317,316,447
false
null
package day7 import shared.getLines fun nrCanContainGoldBag(bagRules: List<String>): Int { val bags = mapToBags(bagRules) return bags.count { containGold(it, bags) } } fun containGold(bag: Bag, bags: List<Bag>): Boolean{ return bag.contain.any { inside -> inside.color == "shiny gold" || containGold(bags.find { it.color == inside.color }!!, bags) } } data class Bag(val color: String, val contain: List<BagInside>) data class BagInside(val color: String, val nr: Int) fun mapToBags(bagRules: List<String>): List<Bag>{ return bagRules.map { rule -> val (bag, containRule) = rule.split("bags contain").map { it.trim() } val contain = containRule.split(",").map { it.trim() }.filter { it != "no other bags." }.map { val nr = it[0].toString().toInt() val color = it.substring(1).replace(Regex("bag(s)?(.)?\$"), "").trim() BagInside(color, nr) } Bag(bag, contain) } } fun bagsInsideGold(bagRules: List<String>): Int{ val bags = mapToBags(bagRules) val gold = bags.find { it.color == "shiny gold" }!! return gold.contain.sumBy { countBag(it, bags) } } fun countBag(bag: BagInside, bags: List<Bag>): Int { return bags.find { it.color == bag.color }!!.contain.sumBy { countBag(it, bags) } * bag.nr + bag.nr } fun main(){ val rules = getLines("day7.txt") val containsGold = nrCanContainGoldBag(rules) println(containsGold) val insideGold = bagsInsideGold(rules) println(insideGold) }
0
Kotlin
0
0
ce25b091366574a130fa3d6abd3e538a414cdc3b
1,521
AdventOfCode2020
MIT License
src/twentytwo/Day02.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("Day02_test") println(part1(testInput)) check(part1(testInput) == 15) println(part2(testInput)) check(part2(testInput) == 12) println("---") val input = readInputLines("Day02_input") println(part1(input)) println(part2(input)) testAlternativeSolutions() } private enum class Move(val moveScore: Int) { ROCK(1), PAPER(2), SCISSORS(3); fun playAgainst(opponent: Move): Result { return when { this == opponent -> Result.DRAW this.losesTo() == opponent -> Result.LOSE this.winsAgainst() == opponent -> Result.WIN else -> error("$this + $opponent case not covered") } } fun winsAgainst(): Move { return when (this) { PAPER -> ROCK ROCK -> SCISSORS SCISSORS -> PAPER } } fun losesTo(): Move { return when (this) { PAPER -> SCISSORS ROCK -> PAPER SCISSORS -> ROCK } } companion object { fun fromInput(char: Char): Move { return when (char) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> error("unexpected input") } } } } private enum class Result(val score: Int) { WIN(6), DRAW(3), LOSE(0); companion object { fun fromInput(char: Char): Result { return when (char) { 'X' -> LOSE 'Y' -> DRAW 'Z' -> WIN else -> error("unexpected input") } } } } private fun part1(input: List<String>): Int { val games = input.map { val (opponentMove, myMove) = it.split(" ") Pair(Move.fromInput(opponentMove.first()), Move.fromInput(myMove.first())) } val scores = games.map { (opponentMove, myMove) -> val moveScore = myMove.moveScore val gameScore = myMove.playAgainst(opponentMove).score moveScore + gameScore } return scores.sum() } private fun part2(input: List<String>): Int { val games = input.map { val (opponentMove, desiredResult) = it.split(" ") Pair(Move.fromInput(opponentMove.first()), Result.fromInput(desiredResult.first())) } val scores = games.map { (opponentMove, desiredResult) -> val gameScore = desiredResult.score val myMove = when (desiredResult) { Result.DRAW -> opponentMove Result.WIN -> opponentMove.losesTo() Result.LOSE -> opponentMove.winsAgainst() } val moveScore = myMove.moveScore gameScore + moveScore } return scores.sum() } // ------------------------------------------------------------------------------------------------ private fun testAlternativeSolutions() { val testInput = readInputLines("Day02_test") check(part1AlternativeSolution(testInput) == 15) check(part2AlternativeSolution(testInput) == 12) println("Alternative Solutions:") val input = readInputLines("Day02_input") println(part1AlternativeSolution(input)) println(part2AlternativeSolution(input)) } private fun part1AlternativeSolution(input: List<String>): Int { val scores = mapOf( "A X" to 1 + 3, "A Y" to 2 + 6, "A Z" to 3 + 0, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 1 + 6, "C Y" to 2 + 0, "C Z" to 3 + 3, ) return input.sumOf { scores[it] ?: error("failed to find score for $it") } } private fun part2AlternativeSolution(input: List<String>): Int { val scores = mapOf( "A X" to 3 + 0, "A Y" to 1 + 3, "A Z" to 2 + 6, "B X" to 1 + 0, "B Y" to 2 + 3, "B Z" to 3 + 6, "C X" to 2 + 0, "C Y" to 3 + 3, "C Z" to 1 + 6, ) return input.sumOf { scores[it] ?: error("failed to find score") } }
1
Kotlin
0
0
600237b66b8cd3145f103b5fab1978e407b19e4c
4,093
advent-of-code-solutions
Apache License 2.0
src/year_2023/day_08/Day08.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2023.day_08 import readInput import util.lcm data class Node( val name: String, val left: String, val right: String ) object Day08 { /** * */ fun solutionOne(text: List<String>): Long { val pattern = text[0] val nodes = text.drop(2).map { parseNode(it) } val theMap = mutableMapOf<String, Node>() nodes.forEach { theMap[it.name] = it } val startingNode: Node = theMap["AAA"]!! return calculateMoves(pattern, startingNode, theMap) { it.name == "ZZZ"} } /** * */ fun solutionTwo(text: List<String>): Long { val pattern = text[0] val nodes = text.drop(2).map { parseNode(it) } val theMap = mutableMapOf<String, Node>() nodes.forEach { theMap[it.name] = it } val startingNodes = nodes.filter { it.name.endsWith('A') }.toMutableList() val cycleLengths = startingNodes.map { node -> calculateMoves(pattern, node, theMap) { it.name.endsWith('Z') } } return cycleLengths.lcm() } private fun parseNode(line: String): Node { // AAA = (BBB, CCC) val split = line.split(" = ") val node = split[0] val connections = split[1].filterNot { it == '(' || it == ')' }.split(", ") val left = connections[0] val right = connections[1] return Node(node, left, right) } private fun calculateMoves(pattern: String, startingNode: Node, theMap: Map<String, Node>, destinationCheck: (Node) -> Boolean): Long { var count = 0L var currentNode = startingNode while (true) { for(i in pattern.indices) { val direction = pattern[i] currentNode = when (direction) { 'L' -> theMap[currentNode.left]!! 'R' -> theMap[currentNode.right]!! else -> throw IllegalArgumentException("Unknown direction.") } count += 1 if (destinationCheck(currentNode)) { return count } } } } } fun main() { val text = readInput("year_2023/day_08/Day08.txt") val solutionOne = Day08.solutionOne(text) println("Solution 1: $solutionOne") val solutionTwo = Day08.solutionTwo(text) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
2,393
advent_of_code
Apache License 2.0
src/main/kotlin/day22.kt
tobiasae
434,034,540
false
{"Kotlin": 72901}
class Day22 : Solvable("22") { override fun solveA(input: List<String>): String { val cuboids = input.map { Cuboid.getFromString(it) } val grid = Array(101) { Array(101) { Array(101) { false } } } cuboids.forEach { for (x in it.xMin..it.xMax) { if (x < -50) continue if (x > 50) break for (y in it.yMin..it.yMax) { if (y < -50) continue if (y > 50) break for (z in it.zMin..it.zMax) { if (z < -50) continue if (z > 50) break grid[x + 50][y + 50][z + 50] = it.on } } } } return grid.map { it.map { it.count { it } }.sum() }.sum().toString() } override fun solveB(input: List<String>): String { val cuboids = input.map { Cuboid.getFromString(it) } val xInter = cuboids.map { setOf(it.xMin, it.xMax + 1) }.reduce { l, r -> l + r }.sorted() val yInter = cuboids.map { setOf(it.yMin, it.yMax + 1) }.reduce { l, r -> l + r }.sorted() val zInter = cuboids.map { setOf(it.zMin, it.zMax + 1) }.reduce { l, r -> l + r }.sorted() val grid = Array(xInter.size) { Array(yInter.size) { Array(zInter.size) { false } } } cuboids.forEach { for (x in xInter.indexOf(it.xMin) until xInter.indexOf(it.xMax + 1)) { for (y in yInter.indexOf(it.yMin) until yInter.indexOf(it.yMax + 1)) { for (z in zInter.indexOf(it.zMin) until zInter.indexOf(it.zMax + 1)) { grid[x][y][z] = it.on } } } } var sum = 0L for (i in 0 until xInter.size - 1) { for (j in 0 until yInter.size - 1) { for (k in 0 until zInter.size - 1) { if (grid[i][j][k]) sum += (xInter[i + 1].toLong() - xInter[i].toLong()) * (yInter[j + 1].toLong() - yInter[j].toLong()) * (zInter[k + 1].toLong() - zInter[k].toLong()) } } } return sum.toString() } } data class Cuboid( val xMin: Int, val xMax: Int, val yMin: Int, val yMax: Int, val zMin: Int, val zMax: Int, val on: Boolean = true ) { companion object { fun getFromString(input: String): Cuboid { val (on, dim) = input.split(" ") val (x, y, z) = dim.split(",").map { it.drop(2) } val (x1, x2) = x.split("..").map(String::toInt) val (y1, y2) = y.split("..").map(String::toInt) val (z1, z2) = z.split("..").map(String::toInt) return Cuboid(x1, x2, y1, y2, z1, z2, on == "on") } } }
0
Kotlin
0
0
16233aa7c4820db072f35e7b08213d0bd3a5be69
2,967
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/oocode/EngineSchematic.kt
ivanmoore
725,978,325
false
{"Kotlin": 42155}
package com.oocode fun engineSchematicFrom(input: String): EngineSchematic { val lines = input.split("\n") val numbers = lines.flatMapIndexed { index, line -> numbersFrom(line, index) }.toSet() val symbols = lines.flatMapIndexed { index, line -> symbolsFrom(line, index) }.toSet() val gearIndicators = lines.flatMapIndexed { index, line -> gearIndicatorsFrom(line, index) }.toSet() return EngineSchematic(numbers, symbols, gearIndicators) } private fun Number.isNextToASymbol(symbols: Set<Symbol>) = symbols.any { symbol -> isNextTo(symbol.position) } private fun Pair<Int, Int>.isNextTo(position: Pair<Int, Int>) = Math.abs(first - position.first) <= 1 && Math.abs(second - position.second) <= 1 private fun numbersFrom(line: String, y: Int) = Regex("(\\d+)") .findAll(line) .map { Number(Pair(it.range.first, y), it.value) } .toSet() private fun symbolsFrom(line: String, y: Int): Set<Symbol> = line.mapIndexedNotNull { x, c -> if (c.isSymbol()) Symbol(Pair(x, y)) else null }.toSet() private fun gearIndicatorsFrom(line: String, y: Int): Set<GearIndicator> = line.mapIndexedNotNull { x, c -> if (c.isGearIndicator()) GearIndicator(Pair(x, y)) else null }.toSet() private fun Char.isSymbol() = !isDigit() && this != '.' private fun Char.isGearIndicator() = this == '*' data class Number(val startPosition: Pair<Int, Int>, val value: String) { fun positions(): Set<Pair<Int, Int>> = value.mapIndexed { index, _ -> startPosition.copy(startPosition.first + index) }.toSet() fun isNextTo(position: Pair<Int, Int>) = positions().any { it.isNextTo(position) } } data class Symbol(val position: Pair<Int, Int>) data class GearIndicator(val position: Pair<Int, Int>) class EngineSchematic( private val numbers: Set<Number>, private val symbols: Set<Symbol>, private val gearIndicators: Set<GearIndicator> ) { fun total() = partNumbers().sumOf { it.value.toInt() } private fun partNumbers() = numbers.filter { number -> number.isNextToASymbol(symbols) }.toSet() fun gearRatiosTotal() = gearIndicators .map { gearIndicator -> numbers .filter { number -> number.isNextTo(gearIndicator.position) } .map { it.value.toInt() } } .filter { it.size == 2 } .sumOf { it[0] * it[1] } }
0
Kotlin
0
0
36ab66daf1241a607682e7f7a736411d7faa6277
2,397
advent-of-code-2023
MIT License
src/Day18.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import kotlin.math.abs import kotlin.math.max fun main() { open class Lava(val x: Int, val y: Int, val z: Int): Comparable<Lava> { override fun toString(): String { return "Lava($x, $y, $z)" } fun touches(other: Lava): Boolean { val dx = abs(x - other.x) val dy = abs(y - other.y) val dz = abs(z - other.z) return dx + dy + dz == 1 } override fun compareTo(other: Lava): Int { val dx = x - other.x val dy = y - other.y val dz = z - other.z return 4 * dx / max(1, abs(dx)) + 2 * dy / max(1, abs(dy)) + dz / max(1, abs(dz)) } } class Air(x: Int, y: Int, z: Int): Lava(x, y, z) { fun adjacent(): List<Air> { return listOf( Air(x - 1, y, z), Air(x + 1, y, z), Air(x, y - 1, z), Air(x, y + 1, z), Air(x, y, z - 1), Air(x, y, z + 1), ) } override fun toString(): String { return "Air($x, $y, $z)" } } fun part1(lava: List<Lava>): Int { return 6 * lava.count() - lava.sumOf { cube1 -> lava.count { cube2 -> cube1.touches(cube2) } } } fun part2(lava: List<Lava>): Int { // x range: 0 - 21, y range: 0 - 21, z range : 0 - 20 // Start from (-1, -1, -1); expand as much as possible; count surface val toExplore = sortedSetOf(Air(-1, -1, -1)) val explored = lava.toSortedSet() while (toExplore.isNotEmpty()) { val air = toExplore.pollFirst()!! explored.add(air) val next = air.adjacent().filter { it.x >= -1 && it.x <= 22 && it.y >= -1 && it.y <= 22 && it.z >= -1 && it.z <= 21 && it !in toExplore && it !in explored } toExplore.addAll(next) } return explored.filterIsInstance<Air>().sumOf { air -> lava.count { cube -> air.touches(cube) } } } val input = readInput("Day18").map { line -> val (x, y, z) = line.split(",") Lava(x.toInt(), y.toInt(), z.toInt()) } println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
2,240
aoc2022-kotlin
Apache License 2.0
src/y2021/Day05.kt
Yg0R2
433,731,745
false
null
package y2021 import kotlin.math.abs import kotlin.math.max fun main() { fun part1(input: List<String>): Int { return input .toOceanFloor { x1, y1, x2, y2, oceanFloor -> if (x1 == x2) { val yDelta = y2.compareTo(y1) for (y in 0..abs(y1 - y2)) { oceanFloor[y1 + y * yDelta][x1] += 1 } } if (y1 == y2) { val xDelta = x2.compareTo(x1) for (x in 0..abs(x1 - x2)) { oceanFloor[y1][x1 + x * xDelta] += 1 } } } .countOverlaps() } fun part2(input: List<String>): Int { return input .toOceanFloor { x1, y1, x2, y2, oceanFloor -> val xDelta = x2.compareTo(x1) val yDelta = y2.compareTo(y1) for (index in 0..max(abs(x1 - x2), abs(y1 - y2))) { oceanFloor[y1 + index * yDelta][x1 + index * xDelta] += 1 } } .countOverlaps() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == 5) check(part2(testInput) == 12) val input = readInput("Day05") println(part1(input)) println(part2(input)) } private fun Array<Array<Int>>.countOverlaps() = this.flatten() .filter { it >= 2 } .size private fun List<String>.toOceanFloor(block: (x1: Int, y1: Int, x2: Int, y2: Int, oceanFloor: Array<Array<Int>>) -> Unit): Array<Array<Int>> { val oceanFloor = Array(1000) { Array(1000) { 0 } } this.map { coordinatePairs -> coordinatePairs.split("->") .map { it.trim() } } .map { coordinatePair -> coordinatePair.map { it.split(",").toIntList() } } .forEach { block(it[0][0], it[0][1], it[1][0], it[1][1], oceanFloor) } return oceanFloor }
0
Kotlin
0
0
d88df7529665b65617334d84b87762bd3ead1323
2,084
advent-of-code
Apache License 2.0
src/Day07.kt
khongi
572,983,386
false
{"Kotlin": 24901}
sealed class Node( val name: String, val parent: Dir?, val level: Int, ) { abstract fun calculateSize(): Int abstract fun print() } class File( name: String, parent: Dir, level: Int, val size: Int, ) : Node(name, parent, level) { override fun calculateSize() = size override fun print() = println("- $name (file, size=$size)".prependIndent(" ".repeat(level))) } class Dir( name: String, parent: Dir?, level: Int, val nodes: MutableList<Node> = mutableListOf(), ) : Node(name, parent, level) { override fun calculateSize() = nodes.sumOf { it.calculateSize() } override fun print() { println("- $name (dir, size=${calculateSize()})".prependIndent(" ".repeat(level))) nodes.forEach { it.print() } } } fun main() { fun buildTree(input: List<String>): Dir { val root = Dir("/", parent = null, level = 0) var currentNode = root input.drop(1).forEach { line -> val elements = line.split(' ') when (elements[0]) { "$" -> { when (elements[1]) { "cd" -> { val destination = elements[2] currentNode = if (destination == "..") { currentNode.parent ?: error("no parent to cd to") } else { currentNode.nodes.first { it.name == destination } as? Dir ?: error("no such dir") } } "ls" -> { // no-op } } } "dir" -> { if (currentNode.nodes.firstOrNull { it.name == elements[1] } == null) { currentNode.nodes.add( Dir( name = elements[1], parent = currentNode, level = currentNode.level + 1, ) ) } } else -> { if (currentNode.nodes.firstOrNull { it.name == elements[1] } == null) { currentNode.nodes.add( File( name = elements[1], parent = currentNode, level = currentNode.level + 1, size = elements[0].toInt(), ) ) } } } } return root } fun Dir.findDirectories(compare: (Int) -> Boolean): List<Dir> { val children = nodes.filterIsInstance<Dir>().flatMap { it.findDirectories(compare) } return if (compare(calculateSize())) { children + this } else { children } } fun part1(input: List<String>): Int { val root = buildTree(input) return root.findDirectories { it <= 100_000 }.sumOf { it.calculateSize() } } fun part2(input: List<String>): Int { val total = 70_000_000 val unusedNeeded = 30_000_000 val root = buildTree(input) val unusedSpace = total - root.calculateSize() val spaceNeeded = unusedNeeded - unusedSpace return root.findDirectories { it >= spaceNeeded }.minOf { it.calculateSize() } } val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9cc11bac157959f7934b031a941566d0daccdfbf
3,769
adventofcode2022
Apache License 2.0
src/Day04.kt
icoffiel
572,651,851
false
{"Kotlin": 29350}
fun main() { fun part1(input: List<String>): Int { return input .map { it.toRangeList() } .count { (first, second) -> first.toSet() fullyContains second.toSet() } } fun part2(input: List<String>): Int { return input .map { it.toRangeList() } .count { (it[0] intersect it[1]).isNotEmpty() } } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println("Part 1: ${part1(input)}") check(part1(input) == 453) println("Part 2: ${part2(input)}") check(part2(input) == 919) } /** * Checks if a Set of Int values is fully contained in another. * For instance: * [1, 2, 3] is fully within [1, 2, 3, 4] (true) * [1, 2] is fully within [2, 3] (false) */ private infix fun Set<Int>.fullyContains(second: Set<Int>): Boolean { val intersect = this intersect second return intersect.toSet() == this || intersect.toSet() == second } /** * Converts a String in the forms 1-2,3-4 into a list of IntRange. * Note that the String function substringBefore is also a good suggestion for this function instead of the split by , */ private fun String.toRangeList(): List<IntRange> { val split = this.split(",", "-") val firstElf = split[0].toInt()..split[1].toInt() val secondElf = split[2].toInt() .. split[3].toInt() return listOf(firstElf, secondElf) }
0
Kotlin
0
0
515f5681c385f22efab5c711dc983e24157fc84f
1,460
advent-of-code-2022
Apache License 2.0
src/Day16.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
import java.util.PriorityQueue import kotlin.math.max class Valve(val name: String, val flowRate: Int, val index: Int) { val next = MutableList(0) { "" to 1 } } const val startValve = "AA" class DFSState(val last: Valve, val time: Int, val open: Set<String>): Comparable<DFSState> { override fun compareTo(other: DFSState): Int { return if (time == other.time) -(open.size.compareTo(other.open.size)) else (time.compareTo(other.time)) } override fun toString(): String { return "{At ${last.name}, time=$time, open=[${open.toList()}]}" } } fun main() { val indicesByName = HashMap<String, Int>() val valves = MutableList<Valve>(0) { Valve("", 0, 0) } val nonNullValves = HashSet<String>() fun flatten() { for (valve in valves) { if (valve.next.size == 2 && valve.flowRate == 0) { val left = indicesByName[valve.next[0].first]!! val right = indicesByName[valve.next[1].first]!! val dist = valve.next.sumOf { it.second } valves[left].next.add(valve.next[1].first to dist) valves[right].next.add(valve.next[0].first to dist) valves[left].next.removeIf { it.first == valve.name } valves[right].next.removeIf { it.first == valve.name } } } for (valve in valves) valve.next.sortByDescending { valves[indicesByName[it.first]!!].flowRate } } fun <T: Comparable<T>> Set<T>.joinAll(): String { return toList().sorted().joinToString("") } fun parseInput(input: List<String>): Valve { input.map { it .replace("Valve ", "") .replace(" has flow rate=", ", ") .replace("; tunnels lead to valves", ",") .replace("; tunnel leads to valve", ",") .split(", ") }.forEachIndexed { index, line -> valves.add(Valve(line[0], line[1].toInt(), index)) valves[index].next.addAll(line.subList(2, line.size).map { it to 1 }) indicesByName[line[0]] = index } flatten() for (valve in valves) { if (valve.flowRate != 0) nonNullValves.add(valve.name) } return valves[indicesByName[startValve]!!] } fun <T> Set<T>.addAndClone(element: T?): Set<T> { val result = HashSet<T>(this) if (element != null) result.add(element) return result } val distances = Array(70) { IntArray(70) { 31 } } val visited = HashMap<Pair<Int, Pair<String, String>>, Int>() fun dfs(state: DFSState, allowedValves: Set<String>, maxTime: Int = 30): Int { if (state.time >= maxTime || state.open.size == allowedValves.size) { return 0 } val stateDfs = state.time to (state.last.name to state.open.joinAll()) if (visited.contains(stateDfs)) return visited[stateDfs]!! var result = 0 for (valve in allowedValves.subtract(state.open)) { val newTime = state.time + distances[state.last.index][valves[indicesByName[valve]!!].index] + 1 val newNode = valves[indicesByName[valve]!!] result = max(result, dfs(DFSState(newNode, newTime, state.open.addAndClone(newNode.name)), allowedValves, maxTime) + newNode.flowRate * (maxTime - newTime)) } visited[stateDfs] = result return result } fun calculateDistances() { for (i in valves.indices) { val queue = PriorityQueue<Pair<Int, Int>>(valves.size, compareBy { it.first }) queue.add(i to 0) while (queue.isNotEmpty()) { val current = queue.poll() if (current.second >= distances[i][current.first]) continue distances[i][current.first] = current.second for (nextValve in valves[current.first].next) { queue.add(indicesByName[nextValve.first]!! to current.second + nextValve.second) } } } } fun generateSubsets(from: List<String>): List<Set<String>> { val subsets = MutableList(0) { HashSet<String>() } for (b in 0 until (1 shl from.size)) { val subset = HashSet<String>() for (i in from.indices) { if ((b and (1 shl i)) != 0) { subset.add(from[i]) } } if (subset.size in (from.size / 2 - 5) .. (from.size / 2 + 5)) subsets.add(subset) } return subsets } fun part1(input: List<String>): Int { visited.clear() val graph = parseInput(input) calculateDistances() val result = dfs(DFSState(graph, 0, HashSet()), nonNullValves, 30) return result } fun part2(input: List<String>): Int { val graph = parseInput(input) calculateDistances() var result = 0 for (split in generateSubsets(nonNullValves.toList())) { visited.clear() val result1 = dfs(DFSState(graph, 0, HashSet()), split, 26) visited.clear() val result2 = dfs(DFSState(graph, 0, HashSet()), nonNullValves.subtract(split), 26) if (result1 + result2 > result) { result = result1 + result2 println(result) } } return result } val testInput = readInputLines("Day16_test") check(part1(testInput) == 1651) check(part2(testInput) == 1707) val input = readInputLines(16) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
5,036
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day03.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution03(input: List<String>) { private val rucksacks = input.map { Rucksack(it) } private fun getGroupItem(chunk: List<Rucksack>): Set<Char> { return chunk[0].items.toSet().intersect( chunk[1].items.toSet().intersect( chunk[2].items.toSet() ) ) } private fun getScore(charSet: Set<Char>): Int { val c = charSet.first() return if (c.isUpperCase()) c - 'A' + 27 else c - 'a' + 1 } private fun getDuplicateItem(rucksack: Rucksack) = rucksack.comp2.toSet().intersect(rucksack.comp1.toSet()) private data class Rucksack(val items: String) { val comp1 = items.subSequence(0, items.length / 2) val comp2 = items.subSequence(items.length / 2, items.length) } fun part1() = rucksacks.map { getDuplicateItem(it) }.sumOf { getScore(it) } fun part2() = rucksacks.chunked(3).map { getGroupItem(it) }.sumOf { getScore(it) } } fun main() { val testSolution = Solution03(readInput("Day03_test")) check(testSolution.part1() == 157) check(testSolution.part2() == 70) val solution = Solution03(readInput("Day03")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
1,228
aoc-2022
Apache License 2.0
src/Day08.kt
cisimon7
573,872,773
false
{"Kotlin": 41406}
fun main() { fun part1(trees: List<List<Int>>): Int { val treesVisibility = with(trees) { mapIndexed { rIdx, row -> row.mapIndexed { cIdx, height -> when { rIdx == 0 || cIdx == size - 1 -> true rIdx == row.size - 1 || cIdx == 0 -> true else -> { (0 until cIdx).all { i -> row[i] < height } || (cIdx + 1 until row.size).all { i -> row[i] < height } || (0 until rIdx).all { i -> this[i][cIdx] < height } || (rIdx + 1 until size).all { i -> this[i][cIdx] < height } } } } } } return treesVisibility.flatten().count { it } } fun part2(trees: List<List<Int>>): Int { val scenicScores = with(trees) { mapIndexed { rIdx, row -> row.mapIndexed { cIdx, height -> val left = (0 until cIdx).reversed().takeUntil { i -> height > row[i] }.count() val right = (cIdx + 1 until row.size).takeUntil { i -> height > row[i] }.count() val top = (0 until rIdx).reversed().takeUntil { i -> height > this[i][cIdx] }.count() val bottom = (rIdx + 1 until size).takeUntil { i -> height > this[i][cIdx] }.count() left * right * top * bottom } } } return scenicScores.flatten().maxOf { it } } fun parse(stringList: List<String>): List<List<Int>> { return stringList.map { line -> line.split("").drop(1).dropLast(1).map { it.toInt() } } } val testInput = readInput("Day08_test") check(part1(parse(testInput)) == 21) check(part2(parse(testInput)) == 8) val input = readInput("Day08_input") println(part1(parse(input))) println(part2(parse(input))) }
0
Kotlin
0
0
29f9cb46955c0f371908996cc729742dc0387017
2,011
aoc-2022
Apache License 2.0
src/main/kotlin/day14/Day14.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day14 import kotlin.math.max import kotlin.math.min fun solveA(input: List<String>): Int { val occupiedPositions = input.parseToCave().toMutableSet() val lowestRockHeight = occupiedPositions.maxBy { it.y }.y return occupiedPositions.pourSandWithoutFloor(lowestRockHeight) } fun solveB(input: List<String>): Int { val occupiedPositions = input.parseToCave().toMutableSet() val floor = occupiedPositions.maxBy { it.y }.y (-1000..1000).map { Position(it, floor + 2) }.also { occupiedPositions.addAll(it) } return occupiedPositions.pourSandWithFloor(floor + 2) } fun MutableSet<Position>.pourSandWithoutFloor(lowestRock: Int): Int { var restingSand = 0 while (true) { val sandUnit = Sand(this, lowestRock) val cameToRest = sandUnit.move() if (!cameToRest) return restingSand this.add(sandUnit.position).also { restingSand++ } } } fun MutableSet<Position>.pourSandWithFloor(floor: Int): Int { var restingSand = 0 while (true) { val sandUnit = Sand(this, floor + 2) sandUnit.move() this.add(sandUnit.position).also { restingSand++ } if (sandUnit.position == sandUnit.startingPosition) return restingSand } } fun List<String>.parseToCave(): Set<Position> = this.flatMap { it.scan().combinePaths() }.toSet() fun String.scan() = this.split(" -> ").map(String::toPosition) fun String.toPosition() = this.split(",").let { Position(it.first().toInt(), it.last().toInt()) } fun List<Position>.combinePaths() = this.windowed(2).flatMap { it.first().to(it.last()) } data class Sand(val occupiedPositions: Set<Position>, val floor: Int = 0) { val startingPosition = Position(500, 0) var position: Position = startingPosition fun move(): Boolean { while (position.y <= floor) { position = if (!occupiedPositions.contains(position.down())) position.down() else if (!occupiedPositions.contains(position.downLeft())) position.downLeft() else if (!occupiedPositions.contains(position.downRight())) position.downRight() else return true } return false } } data class Position(val x: Int, val y: Int) { fun down() = Position(x, y + 1) fun downLeft() = Position(x - 1, y + 1) fun downRight() = Position(x + 1, y + 1) private fun toHorizontally(other: Position) = (min(x, other.x)..max(x, other.x)).map { Position(it, y) } private fun toVertically(other: Position) = (min(y, other.y)..max(y, other.y)).map { Position(x, it) } fun to(other: Position): Set<Position> = (toHorizontally(other) + toVertically(other)).toSet() }
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
2,661
advent-of-code-2022
Apache License 2.0
src/main/aoc2023/Day7.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 class Day7(val input: List<String>) { private data class Hand2(val cards: String, val bid: Int, private val useJokers: Boolean) { // The type of the hand, higher number means better hand val type: Int // The strength of the hand, used for comparisons when the type of two hands are the same. // The larger the string the stronger the hand. val strength = cards.map { it.cardStrength() }.joinToString("") init { val groups = cards.groupingBy { it }.eachCount() val jokers = if (useJokers) groups['J'] ?: 0 else 0 val nonJokers = groups.filterKeys { !useJokers || it != 'J' } type = when { jokers == 5 -> 6 // All jokers, nonJokers is empty and max() would throw an exception. nonJokers.values.max() + jokers == 5 -> 6 // 5 of a kind nonJokers.values.max() + jokers == 4 -> 5 // 4 of a kind nonJokers.size == 2 && jokers in 0..1 -> 4 // full house (more than one joker would make a better hand) nonJokers.values.max() + jokers == 3 -> 3 // 3 of a kind nonJokers.size == 3 && jokers == 0 -> 2 // two pairs (jokers would make a better hand) nonJokers.values.max() + jokers == 2 -> 1 // one pair else -> 0 // high card } } private fun Char.cardStrength(): Char { val x = when (this) { 'A' -> 14 'K' -> 13 'Q' -> 12 'J' -> if (useJokers) 1 else 11 'T' -> 10 else -> digitToInt() } return 'a' + x } companion object { fun parse(rawHand: String, useJokers: Boolean): Hand2 { return rawHand.split(" ").let { Hand2(it.first(), it.last().toInt(), useJokers) } } } } private fun totalWinnings(useJokers: Boolean): Int { return input.map { Hand2.parse(it, useJokers) } .sortedWith(compareBy({ it.type }, { it.strength })) .withIndex() .sumOf { (index, hand) -> (index + 1) * hand.bid } } fun solvePart1(): Int { return totalWinnings(false) } fun solvePart2(): Int { return totalWinnings(true) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,350
aoc
MIT License
src/Day07.kt
emersonf
572,870,317
false
{"Kotlin": 17689}
fun main() { data class PathSizeEntry(val path: String, val size: Int) fun List<String>.parseInput(): List<PathSizeEntry> { val path = ArrayDeque<String>(50) path.add("root") return flatMap { line -> if (line.first() !in '0'..'9') { when { line == "$ cd /" -> { path.clear(); path.add("root") } line == "$ cd .." -> path.removeLast() line.startsWith("$ cd ") -> path.addLast(line.substringAfterLast(" ")) } emptyList() } else { val (size, filename) = line.split(" ") path.indices .map { index -> val pathPrefix = path.subList(0, index + 1).joinToString(separator = "/", prefix = "/") PathSizeEntry(pathPrefix, size.toInt()) } } } } fun getDirectorySizes(input: List<String>) = input.parseInput() .groupingBy { it.path } .aggregate { _, accumulator: Int?, element, _ -> if (accumulator == null) { element.size } else accumulator + element.size } .entries .map { entry -> PathSizeEntry(entry.key, entry.value ) } fun part1(input: List<String>): Int { return getDirectorySizes(input) .filter { it.size < 100000 } .sumOf { it.size } } fun part2(input: List<String>): Int { val directorySizes = getDirectorySizes(input) val totalSize = directorySizes.first { it.path == "/root" }.size val unusedSize = 70000000 - totalSize val requiredUnusedSize = 30000000 - unusedSize return directorySizes .map { it.size } .filter { size -> size > requiredUnusedSize } .minOf { it } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0e97351ec1954364648ec74c557e18ccce058ae6
2,173
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/github/lernejo/korekto/toolkit/misc/Distances.kt
lernejo
315,255,600
false
{"Kotlin": 83210, "HTML": 3592, "Java": 220}
package com.github.lernejo.korekto.toolkit.misc import java.util.* import java.util.stream.Collectors import java.util.stream.Stream import kotlin.math.min object Distances { private fun minimum(a: Int, b: Int, c: Int): Int { return min(min(a, b), c) } fun levenshteinDistance(lhs: CharSequence?, rhs: CharSequence?): Int { val distance = Array(lhs!!.length + 1) { IntArray( rhs!!.length + 1 ) } for (i in 0..lhs.length) distance[i][0] = i for (j in 1..rhs!!.length) distance[0][j] = j for (i in 1..lhs.length) for (j in 1..rhs.length) distance[i][j] = minimum( distance[i - 1][j] + 1, distance[i][j - 1] + 1, distance[i - 1][j - 1] + if (lhs[i - 1] == rhs[j - 1]) 0 else 1 ) return distance[lhs.length][rhs.length] } fun isWordsIncludedApprox(left: String, right: String, wordLevenshteinDistance: Int): Boolean { val leftWords = words(left).collect(Collectors.toList()) val rightWords = words(right).collect(Collectors.toList()) val shorterList = if (rightWords.size > leftWords.size) leftWords else rightWords val longerList: MutableList<String?> = if (rightWords.size > leftWords.size) rightWords else leftWords for (shortListWord in shorterList) { if (!contains(longerList, shortListWord, wordLevenshteinDistance)) { return false } } return true } private fun contains(words: MutableList<String?>, match: String?, maxLevenshteinDistance: Int): Boolean { var contained = false var matched: String? = null for (word in words) { if (levenshteinDistance(word, match) <= maxLevenshteinDistance) { contained = true matched = word break } } if (contained) { words.remove(matched) } return contained } fun countWords(text: String): Int { return words(text).count().toInt() } private fun words(sentence: String): Stream<String?> { return Arrays.stream(sentence.split("\\s+".toRegex()).toTypedArray()) .filter { s: String? -> s!!.trim { it <= ' ' }.isNotEmpty() } } fun longestCommonSubSequence(a: String, b: String): Int { return lCSubStr(a.toCharArray(), b.toCharArray(), a.length, b.length) } private fun lCSubStr(X: CharArray, Y: CharArray, m: Int, n: Int): Int { // Create a table to store lengths of longest common suffixes of // substrings. Note that LCSuff[i][j] contains length of longest // common suffix of X[0..i-1] and Y[0..j-1]. The first row and // first column entries have no logical meaning, they are used only // for simplicity of program val lCStuff = Array(m + 1) { IntArray(n + 1) } var result = 0 // To store length of the longest common substring // Following steps build LCSuff[m+1][n+1] in bottom up fashion for (i in 0..m) { for (j in 0..n) { if (i == 0 || j == 0) lCStuff[i][j] = 0 else if (X[i - 1] == Y[j - 1]) { lCStuff[i][j] = lCStuff[i - 1][j - 1] + 1 result = Integer.max(result, lCStuff[i][j]) } else lCStuff[i][j] = 0 } } return result } }
4
Kotlin
0
0
df998e7098b20454f35cdc05ab3b7b3632fc3ac1
3,447
korekto-toolkit
Apache License 2.0
2021/src/main/kotlin/day14_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.mapItems import utils.mergeToMap import utils.withLCounts fun main() { Day14Func.run() } object Day14Func : Solution<Pair<Day14Func.Polymer, List<Pair<String, String>>>>() { override val name = "day14" override val parser = Parser { input -> val (polymer, ruleLines) = input.split("\n\n") return@Parser Polymer(polymer) to Parser.lines.mapItems { val (from, replacement) = it.split(" -> ") from to replacement }(ruleLines) } data class Polymer(val pairs: Map<String, Long>, val chars: Map<String, Long>) { constructor(input: String) : this( input.windowed(2).withLCounts(), input.windowed(1).withLCounts() ) } /** * doesn't really return a Polymer but more of a delta instead */ private fun deltaByRule(input: Polymer, rule: Pair<String, String>): Polymer { val pair = rule.first val char = rule.second val count = input.pairs[pair] ?: 0L if (count == 0L) { return Polymer(emptyMap(), emptyMap()) } val ret = Polymer( // need to merge because resulting rules can overwrite the original decrement listOf( pair to 0 - count, pair.first() + char to count, char + pair.last() to count ).mergeToMap { _, c1, c2 -> c1 + c2 }, mapOf(char to count) ) return ret } private fun polymerize(input: Polymer, rules: List<Pair<String, String>>): Polymer { val deltas = rules.map { deltaByRule(input, it) } return (deltas + input).reduce { acc, polymer -> val reduced = Polymer( (acc.pairs.toList() + polymer.pairs.toList()).mergeToMap { _, c1, c2 -> c1 + c2 }, (acc.chars.toList() + polymer.chars.toList()).mergeToMap { _, c1, c2 -> c1 + c2 } ) return@reduce reduced } } private fun solve(steps: Int, input: Pair<Polymer, List<Pair<String, String>>>): Long { val answ = (0 until steps).fold(input.first) { acc, _ -> polymerize(acc, input.second) } .chars.entries.sortedBy { it.value } return answ.last().value - answ.first().value } override fun part1(input: Pair<Polymer, List<Pair<String, String>>>): Long { return solve(10, input) } override fun part2(input: Pair<Polymer, List<Pair<String, String>>>): Long { return solve(40, input) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,329
aoc_kotlin
MIT License
src/Day15.kt
inssein
573,116,957
false
{"Kotlin": 47333}
import kotlin.math.abs fun main() { data class Sensor(val position: Pair<Int, Int>, val distance: Int) data class Beacon(val position: Pair<Int, Int>, val sensors: MutableList<Sensor> = mutableListOf()) fun List<String>.toBeaconMap() = this.fold(mutableMapOf<Pair<Int, Int>, Beacon>()) { map, it -> val parts = it.split("=") val sX = parts[1].substringBefore(",").toInt() val sY = parts[2].substringBefore(":").toInt() val bX = parts[3].substringBefore(",").toInt() val bY = parts[4].toInt() val beacon = bX to bY val sensor = Sensor(sX to sY, abs(sX - bX) + abs(sY - bY)) map.getOrDefault(beacon, Beacon(beacon)) .also { it.sensors.add(sensor) } .let { map[beacon] = it } .let { map } } fun List<Sensor>.toCoverage(row: Int) = this.mapNotNull { val (sX, sY) = it.position // is in range? if (abs(row - sY) <= it.distance) { val distance = (it.distance - abs(row - sY)) (sX - distance)..(sX + distance) } else { null } } fun List<IntRange>.collapse() = this .sortedBy { it.first } .fold(listOf<IntRange>()) { acc, it -> val last = acc.lastOrNull() ?: return@fold acc.plusElement(it) when { last.last < it.first -> acc.plusElement(it) last.last < it.last -> acc.dropLast(1).plusElement(last.first..it.last) else -> acc } } fun part1(input: List<String>, row: Int): Int { val beaconMap = input.toBeaconMap() val sensors = beaconMap.values.flatMap { it.sensors } // @note: this only works because there is no gap val firstRange = sensors .toCoverage(row) .collapse() .first() // @note: this is intentionally off by one to account for the beacon return firstRange.last - firstRange.first } fun part2(input: List<String>, max: Int): Long { val beaconMap = input.toBeaconMap() val beacons = beaconMap.values val sensors = beacons.flatMap { it.sensors } for (y in 0..max) { var minX = 0 val coverage = sensors.toCoverage(y).collapse() if (coverage.size == 1) { continue } // find a gap in the range for (r in coverage) { if (minX - r.first < 0) { val result = minX + (r.first - minX) / 2 return result * 4_000_000L + y } minX = minX.coerceAtLeast(r.last) } } return 0 } val testInput = readInput("Day15_test") println(part1(testInput, 10)) // 26 println(part2(testInput, 20)) // 56000011 val input = readInput("Day15") println(part1(input, 2_000_000)) // 5073496 println(part2(input, 4_000_000)) // 13081194638237 }
0
Kotlin
0
0
095d8f8e06230ab713d9ffba4cd13b87469f5cd5
3,001
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day25.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.* fun main() { val input = Input.day(25) println(day25A(input)) } fun day25A(input: Input): Int { val pairs = sortedBasedOnConnections(toPairs(input.lines)) for (cut1 in 0..10) { for (cut2 in cut1..<10) { for (cut3 in cut2..<10) { if (cut1 == cut3 || cut2 == cut3) continue getGroups(pairs.filterIndexed { index, _ -> !listOf(cut1, cut2, cut3).contains(index) }).let { if (it.size == 2) { return it[0].size * it[1].size } } } } } throw Exception() } private fun toPairs(lines: List<String>): List<Pair<String, String>> { val pairs = mutableListOf<Pair<String, String>>() lines.forEach { line -> val left = line.split(':')[0] val rights = line.split(':')[1].trim().split(' ') rights.forEach { right -> if (pairs.none { it == left to right || it == right to left }) { pairs.add(left to right) } } } return pairs } private fun getGroups(pairs: List<Pair<String, String>>): List<Set<String>> { val groups = mutableListOf<MutableSet<String>>() pairs.forEach { pair -> val existingGroups = groups.filter { it.contains(pair.first) || it.contains(pair.second) } if (existingGroups.isEmpty()) { groups.add(mutableSetOf(pair.first, pair.second)) } else if (existingGroups.size == 1) { existingGroups[0].add(pair.first) existingGroups[0].add(pair.second) } else { existingGroups.drop(1).forEach { existingGroups[0].addAll(it) groups.remove(it) } } } return groups } private fun sortedBasedOnConnections(pairs: List<Pair<String, String>>): List<Pair<String, String>> { val popular = pairs.associateWith { 0 }.toMutableMap() val nodes = pairs.flatMap { listOf(it.first, it.second) }.toSet().toMutableList() nodes.forEachIndexed { index, a -> println("$index of ${nodes.size}") val prev = dijkstra(pairs, a) nodes.drop(index + 1).forEach { b -> pathBetweenNodes(pairs, prev, b).forEach { popular[it] = popular[it]!! + 1 } } } return pairs.sortedByDescending { pair -> popular[pair] } } private fun dijkstra(pairs: List<Pair<String, String>>, source: String): Map<String, String?> { val queue = pairs.flatMap { listOf(it.first, it.second) }.toSet().toMutableList() val dist = queue.associateWith { Int.MAX_VALUE }.toMutableMap() val prev = mutableMapOf<String, String?>() dist[source] = 0 while (queue.isNotEmpty()) { val u = queue.minBy { dist[it] ?: 0 }.also { queue.remove(it) } pairs .filter { it.first == u || it.second == u } .forEach { val v = if (it.first == u) it.second else it.first val alt = dist[u]!! + 1 if (alt < dist[v]!!) { dist[v] = alt prev[v] = u } } } return prev } private fun pathBetweenNodes( pairs: List<Pair<String, String>>, prev: Map<String, String?>, target: String ): List<Pair<String, String>> { val path = mutableListOf<Pair<String, String>>() var last = target while (prev[last] != null) { path.add(pairs.first { (it.first == last && it.second == prev[last]) || (it.second == last && it.first == prev[last]) }) last = prev[last]!! } return path }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
3,653
AdventOfCode2023
MIT License
src/Day03.kt
vladislav-og
573,326,483
false
{"Kotlin": 27072}
fun main() { fun calculatePriority(elementInBothRucksacks: Char) = if (elementInBothRucksacks.code > 96) elementInBothRucksacks.code - 96 else elementInBothRucksacks.code - 64 + 26 fun part1(input: List<String>): Int { val items = arrayListOf<Int>() for (row in input) { val firsRucksack = row.substring(0, row.length / 2).asSequence() val secondRucksack = row.substring(row.length / 2, row.length).asSequence() val elementInBothRucksacks = firsRucksack.filter { c -> secondRucksack.contains(c) }.first() val priority = calculatePriority(elementInBothRucksacks) items.add(priority) } return items.sum() } fun part2(input: List<String>): Int { val items = arrayListOf<Int>() var rucksacks = arrayListOf<String>() for (row in input) { rucksacks.add(row) if (rucksacks.size == 3) { val rucksack1 = rucksacks[0] val rucksack2 = rucksacks[1] val rucksack3 = rucksacks[2] val elementInBothRucksacks = rucksack1.asSequence().filter { c -> rucksack2.asSequence().contains(c) }.filter { c -> rucksack3.asSequence().contains(c) }.first() val priority = calculatePriority(elementInBothRucksacks) items.add(priority) rucksacks = arrayListOf() } } return items.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println(part1(testInput)) check(part1(testInput) == 157) println(part2(testInput)) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b230ebcb5705786af4c7867ef5f09ab2262297b6
1,875
advent-of-code-2022
Apache License 2.0
src/Day02.kt
hubikz
573,170,763
false
{"Kotlin": 8506}
enum class Shape { ROCK, PAPER, SCISSORS } enum class Result { LOSE, DRAW, WIN } const val LOST_POINTS = 0 const val DRAW_POINTS = 3 const val WON_POINTS = 6 fun main() { // A for Rock, B for Paper, and C for Scissors // X for Rock, Y for Paper, and Z for Scissors // 1 for Rock, 2 for Paper, and 3 for Scissors // 0 lose 3 draw 6 win val elfShapes = mapOf<String, Shape>("A" to Shape.ROCK, "B" to Shape.PAPER, "C" to Shape.SCISSORS) val myShapes = mapOf<String, Shape>("X" to Shape.ROCK, "Y" to Shape.PAPER, "Z" to Shape.SCISSORS) val expectedResult = mapOf("X" to Result.LOSE, "Y" to Result.DRAW, "Z" to Result.WIN) val defeats = mapOf(Shape.ROCK to Shape.SCISSORS, Shape.SCISSORS to Shape.PAPER, Shape.PAPER to Shape.ROCK) val shapePoints = mapOf(Shape.ROCK to 1, Shape.PAPER to 2, Shape.SCISSORS to 3) fun part1(input: List<String>): Int { return input.sumOf { val (left, right) = it.split(" ") val elfShape = elfShapes.getValue(left) val myShape: Shape = myShapes.getValue(right) val gamePoints = when (elfShape) { myShape -> { DRAW_POINTS } defeats.getValue(myShape) -> { WON_POINTS } else -> { LOST_POINTS } } gamePoints + shapePoints.getValue(myShape) } } fun part2(input: List<String>): Int { return input.sumOf { val (left, right) = it.split(" ") val elfShape = elfShapes.getValue(left) when (expectedResult.getValue(right)) { Result.DRAW -> { DRAW_POINTS + shapePoints.getValue(elfShape) } Result.LOSE -> { LOST_POINTS + shapePoints.getValue(defeats.getValue(elfShape)) } else -> { WON_POINTS + shapePoints.getValue(defeats.entries.associate{ e -> e.value to e.key}.getValue(elfShape)) } } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println("Part 1: ${part1(input)}") check(part2(testInput) == 12) println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
902c6c3e664ad947c38c8edcb7ffd612b10e58fe
2,438
AoC2022
Apache License 2.0
2022/src/day07/day07.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day07 import GREEN import RESET import printTimeMillis import readInput data class File( val name: String, val isDir: Boolean = false, val size: Long = 0 ) fun List<String>.toPath() = "/" + drop(1).joinToString("/") // construct a map of "/some/file" -> List<File> fun parseFileSystem(input: List<String>): MutableMap<String, MutableList<File>> { val fs = mutableMapOf<String, MutableList<File>>() val nav = mutableListOf<String>() input.forEach { if (it.startsWith("$")) { if (it.startsWith("$ cd ")) { when(val nextDir = it.split(" ").last()) { ".." -> nav.removeLast() else -> nav.add(nextDir) } } } else { // result of "ls" val currPath = nav.toPath() if (!fs.containsKey(currPath)) { fs[currPath] = mutableListOf() } if (it.startsWith("dir")) { fs[currPath]?.add(File(it.split(" ")[1], isDir = true)) } else { fs[currPath]?.add(it.split(" ").let { File(it.last(), size = it.first().toLong()) }) } } } return fs } // fills the "sums" with their sizes by traversing the graph // sums: map of "/some/dir/on/the/filesystem" -> sumOfContained fun traverseAndCount( fs: Map<String, MutableList<File>>, sums: MutableMap<String, Long>, nav: List<String> ): Long { val files = fs[nav.toPath()] ?: return 0 val sum = files.map { if (it.isDir) { traverseAndCount(fs, sums, nav + it.name) } else { it.size } }.sum() sums[nav.toPath()] = sum return sum } fun part1(input: List<String>): Long { val fs = parseFileSystem(input) val sums = mutableMapOf<String, Long>() traverseAndCount(fs, sums, listOf("/")) return sums.filter { it.value <= 100000 }.map { it.value }.sum() } fun part2(input: List<String>): Long { val fs = parseFileSystem(input) val sums = mutableMapOf<String, Long>() traverseAndCount(fs, sums, listOf("/")) val neededSpace = 30000000 - (70000000 - sums["/"]!!) return sums.filter { it.value >= neededSpace }.map { it.value }.sorted().first() } fun main() { val testInput = readInput("day07_example.txt") printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) } printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) } val input = readInput("day07.txt") printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) } printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) } }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
2,698
advent-of-code
Apache License 2.0
src/Day02.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
enum class Result(val score: Int) { WIN(6), Draw(3), Lose(0) } enum class Choice(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3); companion object { val winsAgainstMap = mapOf( ROCK to PAPER, PAPER to SCISSORS, SCISSORS to ROCK ) } private val losesTo: Choice get() { return winsAgainstMap[this]!! } fun scoreAgainst(other: Choice): Int { if (this == other) return Result.Draw.score return when (this) { ROCK -> if (other == SCISSORS) Result.WIN.score else Result.Lose.score PAPER -> if (other == ROCK) Result.WIN.score else Result.Lose.score SCISSORS -> if (other == PAPER) Result.WIN.score else Result.Lose.score } } fun getChoiceForDesiredResult(desiredResult: Result): Choice { return when (desiredResult) { Result.WIN -> this.losesTo Result.Draw -> this Result.Lose -> this.losesTo.losesTo } } } val charChoiceMap = mapOf( 'A' to Choice.ROCK, 'X' to Choice.ROCK, 'B' to Choice.PAPER, 'Y' to Choice.PAPER, 'Z' to Choice.SCISSORS, 'C' to Choice.SCISSORS ) val requiredResult = mapOf( 'Y' to Result.Draw, 'X' to Result.Lose, 'Z' to Result.WIN ) // For fun: task 1 in one line :D (still using maps / enum classes though :o ) // fun getTotalScoresInOneLine(choices: List<String>) = choices.map { Pair(charChoiceMap[it[2]], charChoiceMap[it[0]]) }.sumOf { it.first!!.score + if (it.first == it.second) Result.Draw.score else { if (it.first == Choice.ROCK) { if (it.second == Choice.SCISSORS) Result.WIN.score else Result.Lose.score } else if (it.first == Choice.PAPER) { if (it.second == Choice.ROCK) Result.WIN.score else Result.Lose.score } else { if (it.second == Choice.PAPER) Result.WIN.score else Result.Lose.score } } } fun getChoices(input: String): Pair<Choice, Choice>? { val playerChoice: Choice = charChoiceMap[input[2]] ?: return null val opponentChoice: Choice = charChoiceMap[input[0]] ?: return null return Pair(playerChoice, opponentChoice) } @JvmName("getTotalScores1") fun getTotalScores(choices: List<String>) = getTotalScores(choices.map { getChoices(it) }) fun getTotalScores(choices: List<Pair<Choice, Choice>?>) = choices.sumOf { if (it != null) getScore(it.first, it.second) else 0 } fun getScore(playerChoice: Choice, opponentChoice: Choice): Int = playerChoice.score + playerChoice.scoreAgainst(opponentChoice) fun makeDecision(character: Char, opponentChoice: Char): Pair<Choice, Choice>? { val oppChoice: Choice = charChoiceMap[opponentChoice] ?: return null val requiredResult = requiredResult[character] ?: return null val playerChoice = oppChoice.getChoiceForDesiredResult(requiredResult) return Pair(playerChoice, oppChoice) } fun playWithElfInstruction(choices: List<String>): Int { val choicesWithDecisions: List<Pair<Choice, Choice>?> = choices.map { makeDecision(it[2], it[0]) } return choicesWithDecisions.sumOf { if (it != null) getScore(it.first, it.second) else 0 } } fun main() { val testInput = readInput("Day02_test") val result = getTotalScores(testInput) println(result) check(result == 14531) val result2 = playWithElfInstruction(testInput) println(result2) check(result2 == 11258) }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
3,381
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/day12.kt
gautemo
725,273,259
false
{"Kotlin": 79259}
import shared.Input import shared.toInts fun main() { val input = Input.day(12) println(day12A(input)) println(day12B(input)) } fun day12A(input: Input): Long { return input.lines.sumOf { countPermutes(it) } } fun day12B(input: Input): Long { return input.lines.sumOf { val (first, second) = it.split(' ') countPermutes("${List(5) { first }.joinToString("?")} ${List(5) { second }.joinToString(",")}") } } private val cache = mutableMapOf<SpringsState, Long>() fun countPermutes(springs: String): Long { cache.clear() val (values, pattern) = springs.split(' ') return validPermutes(SpringsState(emptyList(), values), pattern.toInts()) } private fun validPermutes(springsState: SpringsState, pattern: List<Int>): Long { cache[springsState]?.let { return it } if(!pattern.joinToString(",").startsWith(springsState.groups.joinToString(","))) { return 0 } if(springsState.rest.isEmpty()) { if(springsState.groups == pattern) return 1 return 0 } if(!springsState.rest.contains('?')){ val answer = springsState.groups + getGroups(springsState.rest) if(answer == pattern) return 1 return 0 } val permutes1 = validPermutes(springsState.toNext('.'), pattern) val permutes2 = validPermutes(springsState.toNext('#'), pattern) cache[springsState] = permutes1 + permutes2 return permutes1 + permutes2 } private data class SpringsState(val groups: List<Int>, val rest: String) { fun toNext(to: Char): SpringsState { val changed = rest.replaceFirst('?', to) if(!changed.contains('?')) { return SpringsState(groups, changed) } var knownSection = changed.substringBefore("?") while (knownSection.endsWith('#')) { knownSection = knownSection.removeSuffix("#") } val toRest = changed.removePrefix(knownSection) val groupList = getGroups(knownSection) return SpringsState(groups + groupList, toRest) } } private fun getGroups(values: String): List<Int> { return Regex("""#+""") .findAll(values) .map { it.value.length }.toList() }
0
Kotlin
0
0
6862b6d7429b09f2a1d29aaf3c0cd544b779ed25
2,200
AdventOfCode2023
MIT License
src/day08/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day08 import Coord import day06.main import readInput typealias IntGrid = Array<Array<Int>> class Forest(private val trees: IntGrid) : Iterable<Coord> { val maxX = trees[0].size val maxY = trees.size fun isVisible(x: Int, y: Int) = (0 until x).all { trees[it][y] < trees[x][y] } || (0 until y).all { trees[x][it] < trees[x][y] } || ((x + 1) until maxX).all { trees[it][y] < trees[x][y] } || ((y + 1) until maxY).all { trees[x][it] < trees[x][y] } fun scenicScore(x: Int, y: Int): Int { val left = ((x - 1) downTo 1).takeWhile { trees[it][y] < trees[x][y] }.size val top = ((y - 1) downTo 1).takeWhile { trees[x][it] < trees[x][y] }.size val right = ((x + 1) until (maxX - 1)).takeWhile { trees[it][y] < trees[x][y] }.size val down = ((y + 1) until (maxY - 1)).takeWhile { trees[x][it] < trees[x][y] }.size return (left + 1) * (top + 1) * (right + 1) * (down + 1) } override fun iterator() = iterator { (1 until (maxX - 1)).forEach { x -> (1 until (maxY - 1)).forEach { y -> yield(Coord(x, y)) } } } } fun main() { fun parse(input: List<String>) = Forest(Array(input.first().length) { x -> Array(input.size) { y -> input[x][y].digitToInt() } }) fun part1(input: Forest) = input.count { (x, y) -> input.isVisible(x, y) } + (input.maxX - 1 + input.maxY - 1) * 2 //edges fun part2(input: Forest) = input.maxOf { (x, y) -> input.scenicScore(x, y) } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
1,732
AOC2022
Apache License 2.0
app/src/main/kotlin/day04/Day04.kt
KingOfDog
433,706,881
false
{"Kotlin": 76907}
package day04 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 4 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay04Part1, ::solveDay04Part2) } fun solveDay04Part1(input: List<String>): Int { val numbers = parseNumbers(input) val boards = parseBoards(input) var number: Int = 0 var hasWon = false while (!hasWon && numbers.isNotEmpty()) { number = numbers.removeFirst() boards.forEach { it.applyNumber(number) } hasWon = boards.any { it.hasWon() } } val winningBoard = boards.first { it.hasWon() } return winningBoard.sumOfRemainingNumbers() * number } fun solveDay04Part2(input: List<String>): Int { val numbers = parseNumbers(input) val boards = parseBoards(input) var number: Int = 0 val boardsWon = boards.map { false }.toTypedArray() var lastWinningBoardIndex = -1 while (numbers.isNotEmpty() && boardsWon.any { !it }) { number = numbers.removeFirst() boards.forEachIndexed { index, board -> board.applyNumber(number) if (board.hasWon() && !boardsWon[index]) { boardsWon[index] = true lastWinningBoardIndex = index } } } val lastWinningBoard = boards[lastWinningBoardIndex] return lastWinningBoard.sumOfRemainingNumbers() * number } private fun parseBoards(input: List<String>) = input.subList(2, input.size).filterNot { it == "" }.windowed(5, 5, false) .map { it.map { row -> row.split(Regex("\\s+")).map { cell -> cell.toInt() } } } .map { BingoBoard(it) } private fun parseNumbers(input: List<String>) = input[0].split(",").map { it.toInt() }.toMutableList() class BingoBoard(input: List<List<Int>>) { private val width = input[0].size private val height = input.size private val numbers: Array<Array<Cell>> = input.map { it.map { number -> Cell(number, false) }.toTypedArray() }.toTypedArray() init { input.forEach { assert(it.size == width) } } fun applyNumber(number: Int) { numbers.forEach { row -> row.forEach { if (it.number == number) it.checked = true } } } fun hasWon(): Boolean { val options = getOptions() return options.any { it.areAllChecked() } } fun sumOfRemainingNumbers(): Int = numbers.flatten().filterNot { it.checked }.sumOf { it.number } private fun getOptions(): Array<Array<Cell>> = arrayOf( *getRows(), *getColumns(), ) private fun getRows(): Array<Array<Cell>> = numbers private fun getColumns(): Array<Array<Cell>> = numbers.transpose() } data class Cell(val number: Int, var checked: Boolean) fun Array<Cell>.areAllChecked(): Boolean = all { it.checked } fun Array<Array<Cell>>.transpose(): Array<Array<Cell>> { val output = Array(this[0].size) { Array(size) { Cell(0, false) } } forEachIndexed { index, row -> row.forEachIndexed { index2, c -> output[index2][index] = c } } return output }
0
Kotlin
0
0
576e5599ada224e5cf21ccf20757673ca6f8310a
3,277
advent-of-code-kt
Apache License 2.0
leetcode/src/daily/hard/Q940.kt
zhangweizhe
387,808,774
false
null
package daily.hard fun main() { // 940. 不同的子序列 II // https://leetcode.cn/problems/distinct-subsequences-ii/ println(distinctSubseqII("blljuffdyfrkqtwfyfztpdiyktrhftgtabxxoibcclbjvirnqyynkyaqlxgyybkgyzvcahmytjdqqtctirnxfjpktxmjkojlvvrr")) } fun distinctSubseqII(s: String): Int { val mod = (Math.pow(10.0, 9.0) + 7).toInt() val dp = IntArray(s.length) val repeatArray = IntArray(26) dp[0] = 1 // 以 s[0] 结尾的字符串的子序列数量,只有1个 repeatArray[s[0] - 'a'] = 1 // s[0] 对应的字符的重复次数,是1 for (i in 1 until s.length) { val newCount = ((dp[i-1] + 1).rem(mod) + mod - repeatArray[s[i] - 'a']).rem(mod) dp[i] = (dp[i-1] + newCount).rem(mod) repeatArray[s[i] - 'a'] += newCount } return dp[s.length - 1] } /** * 不考虑大数的版本,没有取余操作 * 参考题解 * https://leetcode.cn/problems/distinct-subsequences-ii/solution/zhua-wa-mou-si-tu-jie-leetcode-by-muse-7-j2sy/ */ fun distinctSubseqII1(s: String): Int { val dp = IntArray(s.length) val repeatArray = IntArray(26) dp[0] = 1 // 以 s[0] 结尾的字符串的子序列数量,只有1个 repeatArray[s[0] - 'a'] = 1 // s[0] 对应的字符的重复次数,是1 for (i in 1 until s.length) { val newCount = dp[i-1] + 1 - repeatArray[s[i] - 'a'] dp[i] = dp[i-1] + newCount // 注意这里是 +=,不能直接赋值 repeatArray[s[i] - 'a'] = newCount,因为这里 newCount 是减去了上一次重复的次数的- repeatArray[s[i] - 'a'] repeatArray[s[i] - 'a'] += newCount } return dp[s.length - 1] }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,694
kotlin-study
MIT License
src/Day18.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { data class Cube(val x: Int, val y: Int, val z: Int) fun String.toCube() = split(",").map { it.toInt() }.let { (x, y, z) -> Cube(x, y, z) } fun Cube.neighbors() = listOf(copy(x = x + 1), copy(y = y + 1), copy(z = z + 1), copy(x = x - 1), copy(y = y - 1), copy(z = z - 1)) fun part1(input: List<String>): Int { val lavaCubes = input.mapTo(HashSet()) { it.toCube() } val possibleAirCubes = lavaCubes.flatMap { it.neighbors() } val airCubes = possibleAirCubes - lavaCubes return airCubes.size } fun part2(input: List<String>): Int { val lavaCubes = input.mapTo(HashSet()) { it.toCube() } val possibleAirCubes = lavaCubes.flatMap { it.neighbors() } val airCubes = possibleAirCubes - lavaCubes val xRange = airCubes.minOf { it.x }..airCubes.maxOf { it.x } val yRange = airCubes.minOf { it.y }..airCubes.maxOf { it.y } val zRange = airCubes.minOf { it.z }..airCubes.maxOf { it.z } val reachableByWater = mutableSetOf<Cube>() fun recurseOutside(cube: Cube) { for (neighbor in cube.neighbors()) { if (neighbor.x !in xRange || neighbor.y !in yRange || neighbor.z !in zRange || neighbor in reachableByWater || neighbor in lavaCubes) { continue } reachableByWater += neighbor recurseOutside(neighbor) } } recurseOutside(Cube(xRange.first, yRange.first, zRange.first)) val airCubesReachableByWater = airCubes.filter { it in reachableByWater } return airCubesReachableByWater.size } val testInput = readInput("Day18_test") check(part1(testInput) == 64) check(part2(testInput) == 58) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
1,864
advent-of-code-2022
Apache License 2.0
src/day2/Day02.kt
mrm1st3r
573,163,888
false
{"Kotlin": 12713}
package day2 import Puzzle enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3) } val elfCodes = mapOf( Pair('A', Shape.ROCK), Pair('B', Shape.PAPER), Pair('C', Shape.SCISSORS) ) val humanCodes = mapOf( Pair('X', Shape.ROCK), Pair('Y', Shape.PAPER), Pair('Z', Shape.SCISSORS) ) // second wins against first val winningCombinations = listOf( Pair(Shape.ROCK, Shape.PAPER), Pair(Shape.SCISSORS, Shape.ROCK), Pair(Shape.PAPER, Shape.SCISSORS), ) fun winAgainst(v: Shape): Shape { return winningCombinations.find { it.first == v }!!.second } fun loseAgainst(v: Shape): Shape { return winningCombinations.find { it.second == v }!!.first } fun parseShapes(line: String): Pair<Shape, Shape> { return Pair(elfCodes[line[0]]!!, humanCodes[line[2]]!!) } fun parseShapesPart2(line: String): Pair<Shape, Shape> { val elf = elfCodes[line[0]]!! val human = when (line[2]) { 'X' -> loseAgainst(elf) 'Z' -> winAgainst(elf) else -> elf } return Pair(elf, human) } fun score(shapes: Pair<Shape, Shape>): Int { return when { shapes.first == shapes.second -> 3 winningCombinations.contains(shapes) -> 6 else -> 0 } + shapes.second.score } fun main() { fun part1(input: List<String>): Int { return input .map(::parseShapes) .sumOf(::score) } fun part2(input: List<String>): Int { return input .map(::parseShapesPart2) .sumOf(::score) } Puzzle( "day2", ::part1, 15, ::part2, 12 ).test() }
0
Kotlin
0
0
d8eb5bb8a4ba4223331766530099cc35f6b34e5a
1,706
advent-of-code-22
Apache License 2.0
src/Day07.kt
mvanderblom
573,009,984
false
{"Kotlin": 25405}
import java.util.* data class File(val name: String, val size: Int) data class Dir(val name: String, val subDirs: MutableList<Dir>, val files: MutableList<File>) { fun size(): Int { return files.sumOf { it.size } + subDirs.sumOf { it.size() } } companion object { fun withName(name: String): Dir { return Dir(name, mutableListOf(), mutableListOf()) } } } data class FileSystem (val rootDir: Dir, val allDirs: List<Dir>) fun main() { val dayName = 7.toDayName() fun parseInput(input: List<String>): FileSystem { var cd = Stack<Dir>() var root: Dir? = null val allDirs = mutableListOf<Dir>(); input .filter { it != "$ ls" } .forEach { it -> when { it == "$ cd .." -> { cd.pop() } it.startsWith("$ cd ") -> { val dirName = it.substring(5) val dir = if (cd.size == 0) { val dir = Dir.withName(dirName) root = dir allDirs.add(dir); dir } else cd.peek().subDirs.single { it.name == dirName } cd.push(dir) } it.startsWith("dir ") -> { val dir = Dir.withName(it.substring(4)) allDirs.add(dir) cd.peek().subDirs.add(dir) } else -> { val (size, name) = it.split(" ") cd.peek().files.add(File(name, size.toInt())) } } } return FileSystem(root!!, allDirs) } fun part1(input: List<String>): Int { return parseInput(input).allDirs .map { it.size() } .filter { it < 100000 } .sortedDescending() .sum() } fun part2(input: List<String>): Int { val fileSystem = parseInput(input) val usedSpace = fileSystem.rootDir.size() val availableSpace = 70000000 - usedSpace val neededSpace = 30000000 - availableSpace return fileSystem.allDirs .map { it.size() } .sorted() .showMe() .first { it > neededSpace } } val testInput = readInput("${dayName}_test") val input = readInput(dayName) // Part 1 val testOutputPart1 = part1(testInput) testOutputPart1 isEqualTo 95437 val outputPart1 = part1(input) outputPart1 isEqualTo 1453349 // Part 2 val testOutputPart2 = part2(testInput) testOutputPart2 isEqualTo 24933642 val outputPart2 = part2(input) outputPart2 isEqualTo 2948823 }
0
Kotlin
0
0
ba36f31112ba3b49a45e080dfd6d1d0a2e2cd690
2,997
advent-of-code-kotlin-2022
Apache License 2.0
src/day02/Day02.kt
marcBrochu
573,884,748
false
{"Kotlin": 12896}
package day02 import readInput enum class Shape(val score: Int) { ROCK(1), PAPER(2), SCISSORS(3), DEFAULT(0); fun getOutcome(opponentShape: Shape) = when { opponentShape == ROCK && this == PAPER -> RoundOutcome.WIN opponentShape == PAPER && this == SCISSORS -> RoundOutcome.WIN opponentShape == SCISSORS && this == ROCK -> RoundOutcome.WIN opponentShape == this -> RoundOutcome.DRAW else -> RoundOutcome.LOST } companion object { fun create(letter: Char) = when(letter) { 'A', 'X' -> ROCK 'B', 'Y' -> PAPER 'C', 'Z' -> SCISSORS else -> DEFAULT } fun forOutcome(opponentShape: Shape, outcome: RoundOutcome): Shape = when { outcome == RoundOutcome.WIN && opponentShape == ROCK -> PAPER outcome == RoundOutcome.WIN && opponentShape == PAPER -> SCISSORS outcome == RoundOutcome.WIN && opponentShape == SCISSORS -> ROCK outcome == RoundOutcome.LOST && opponentShape == ROCK -> SCISSORS outcome == RoundOutcome.LOST && opponentShape == PAPER -> ROCK outcome == RoundOutcome.LOST && opponentShape == SCISSORS -> PAPER outcome == RoundOutcome.DRAW -> opponentShape else -> opponentShape } } } enum class RoundOutcome(val score: Int) { LOST(0), DRAW(3), WIN(6) } class Game( val opponentShape: Shape, val playerShape: Shape ) { fun getPlayerScore() = playerShape.getOutcome(opponentShape).score + playerShape.score override fun toString(): String = "$opponentShape x $playerShape" } fun main() { fun parseGuide(guide: List<String>): List<Game> = guide.map { Game( opponentShape = Shape.create(it[0]), playerShape = Shape.create(it[2]) ) } fun parseGuideForOutcome(guide: List<String>): List<Game> = guide.map { val opponentShape = Shape.create(it[0]) Game( opponentShape = opponentShape, playerShape = Shape.forOutcome( opponentShape = opponentShape, outcome = when (it[2]) { 'Y' -> RoundOutcome.DRAW 'Z' -> RoundOutcome.WIN else -> RoundOutcome.LOST }) ) } fun part1(games: List<Game>): Int = games.sumOf { it.getPlayerScore() } fun part2(games: List<Game>): Int = games.sumOf { it.getPlayerScore() } val input = readInput("day02/Day02") println(part1(parseGuide(input))) println(part2(parseGuideForOutcome(input))) }
0
Kotlin
0
2
8d4796227dace8b012622c071a25385a9c7909d2
2,847
advent-of-code-kotlin
Apache License 2.0
src/day13/Day13.kt
PoisonedYouth
571,927,632
false
{"Kotlin": 27144}
package day13 import readInput sealed interface Element : Comparable<Element> class ElementList(val elements: List<Element>) : Element { constructor(element: Element) : this(listOf(element)) override fun compareTo(other: Element): Int = when (other) { is ValueElement -> compareTo(ElementList(other)) is ElementList -> { elements.zip(other.elements).map { it.first.compareTo(it.second) }.firstOrNull { it != 0 } ?: this.elements.size.compareTo(other.elements.size) } } } class ValueElement(val value: Int) : Element { override fun compareTo(other: Element): Int = when (other) { is ValueElement -> value.compareTo(other.value) is ElementList -> ElementList(this).compareTo(other) } } private val regex = """(,)|(?=\[)|(?=])|(?<=\[)|(?<=])""".toRegex() private fun mapToElement(line: String): Element { val result = buildList<MutableList<Element>> { add(mutableListOf()) line.split(regex).filter(String::isNotBlank).forEach { t -> when (t) { "[" -> add(mutableListOf()) "]" -> removeLast().also { last().add(ElementList(it)) } else -> last().add(ValueElement(t.toInt())) } } } return result[0][0] } fun main() { fun part1(input: List<String>): Int { return input.asSequence().filter(String::isNotBlank).map(::mapToElement) .chunked(2) .mapIndexed { index, (a, b) -> if (a < b) index + 1 else 0 } .sum() } fun part2(input: List<String>): Int { val parsed = input.filter(String::isNotBlank).map(::mapToElement) val packet1 = ElementList(ElementList(ValueElement(2))) val packet2 = ElementList(ElementList(ValueElement(6))) val list = (parsed + packet1 + packet2).sorted() return (1 + list.indexOf(packet1)) * (1 + list.indexOf(packet2)) } val input = readInput("day13/Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
dbcb627e693339170ba344847b610f32429f93d1
2,053
advent-of-code-kotlin-2022
Apache License 2.0
src/Day08.kt
Totwart123
573,119,178
false
null
import kotlin.math.sign fun main() { fun part1(input: List<String>): Int { var treeCount = input.size * 2 + 2 * (input.first().length - 2) (1 until input.size - 1).forEach { i -> (1 until input[i].length - 1).forEach { j -> val currentTree = input[i][j].toString().toInt() //check left if (input[i].take(j).map { it.toString().toInt() }.max() < currentTree) treeCount++ //check right else if(input[i].takeLast(input[i].length - j - 1).map { it.toString().toInt() }.max() < currentTree) treeCount++ //check top else if(input.take(i).maxOf { it[j].toString().toInt() } < currentTree) treeCount ++ else if(input.takeLast(input.size - i - 1).maxOf { it[j].toString().toInt() } < currentTree) treeCount ++ } } return treeCount } fun calcScienceMulti(treesToCheck: List<Int>, currentTree: Int): Int{ val visibleTrees = treesToCheck.takeWhile { it < currentTree } val scienceMultiplicator = if (visibleTrees.size == treesToCheck.size){ visibleTrees.size } else{ visibleTrees.size + 1 } return scienceMultiplicator } fun part2(input: List<String>): Int { var highestScienceScore = -1 (input.indices).forEach { i -> (0 until input[i].length).forEach { j -> var scienceScore = 1 val currentTree = input[i][j].toString().toInt() //left val treesLeft = input[i].take(j).map { it.toString().toInt() }.reversed() scienceScore *= calcScienceMulti(treesLeft, currentTree) val treesRight = input[i].takeLast(input[i].length - j - 1).map { it.toString().toInt() } scienceScore *= calcScienceMulti(treesRight, currentTree) val treesTop = input.take(i).map { it[j].toString().toInt() }.reversed() scienceScore *= calcScienceMulti(treesTop, currentTree) val treesBottom = input.takeLast(input.size - i - 1).map { it[j].toString().toInt() } scienceScore *= calcScienceMulti(treesBottom, currentTree) if(scienceScore > highestScienceScore){ highestScienceScore = scienceScore } } } return highestScienceScore } 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
33e912156d3dd4244c0a3dc9c328c26f1455b6fb
2,742
AoC
Apache License 2.0
src/main/kotlin/days/Day16.kt
nuudles
316,314,995
false
null
package days class Day16 : Day(16) { private data class Field( val name: String, val ranges: Set<IntRange> ) private fun parseInput(): Triple<Set<Field>, List<Int>, List<List<Int>>> { val components = inputString.split("\n\n") val fields = components[0] .split("\n") .fold(setOf<Field>()) { set, line -> set + line.split(":").let { fieldComponents -> Field( name = fieldComponents.first(), ranges = fieldComponents .last() .split("or") .fold(setOf()) { rangeSet, ranges -> val test = ranges.trim().split("-").let { IntRange(it.first().toInt(), it.last().toInt()) } rangeSet.plus(element = test) } ) } } val myTicket = components[1] .split("\n") .last() .split(",") .map { it.toInt() } val nearbyTickets = components[2] .split("\n") .drop(1) .map { line -> line.split(",").map { it.toInt() } } return Triple(fields, myTicket, nearbyTickets) } override fun partOne(): Any { val (fields, _, nearbyTickets) = parseInput() var sum = 0 nearbyTickets.forEach { ticket -> ticket.forEach { number -> if ( fields.firstOrNull { field -> field.ranges.firstOrNull { range -> range.contains(number) } != null } == null ) { sum += number } } } return sum } override fun partTwo(): Any { val (fields, myTicket, nearbyTickets) = parseInput() val possibleFields = List(fields.count()) { fields.toMutableSet() } nearbyTickets .filter { ticket -> ticket.firstOrNull { number -> fields.firstOrNull { field -> field.ranges.firstOrNull { range -> range.contains(number) } != null } == null } == null } .forEach { ticket -> ticket.forEachIndexed { index, number -> if (possibleFields[index].count() == 1) { return@forEachIndexed } possibleFields[index].removeIf { field -> field.ranges.count { it.contains(number) } == 0 } } } while (possibleFields.sumBy { it.count() } != possibleFields.count()) { val known = possibleFields.filter { it.count() == 1 }.map { it.first() } possibleFields .filter { it.count() > 1 } .forEach { set -> set.removeIf { known.contains(it) } } } return possibleFields .map { it.first() } .withIndex() .filter { it.value.name.startsWith("departure") } .fold(1L) { product, field -> product * myTicket[field.index] } } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
3,533
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/com/kingsleyadio/adventofcode/y2021/day11/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day11 import com.kingsleyadio.adventofcode.util.readInput fun solution(steps: Int, isPart2: Boolean): Int { // NOTE: isPart2=false returns number of glows and isPart2=true returns number of steps val input = readInput(2021, 11).useLines { lines -> lines.map { line -> line.toCharArray().map { it.digitToInt() }.toIntArray() }.toList() } fun glow(y: Int, x: Int, glowing: MutableSet<String>) { if (input[y][x] > 9 && "$y#$x" !in glowing) { glowing.add("$y#$x") input[y][x] = 0 adjacentPoints(y, x, input).forEach { (newY, newX) -> if ("$newY#$newX" !in glowing) input[newY][newX]++ glow(newY, newX, glowing) } } } var totalGlows = 0 val octopusCount = input.size * input.first().size repeat(steps) { step -> val glowingPerStep = hashSetOf<String>() input.forEachIndexed { _, inner -> for (j in inner.indices) inner[j]++ } input.forEachIndexed { i, inner -> for (j in inner.indices) glow(i, j, glowingPerStep) } totalGlows += glowingPerStep.size if (isPart2 && glowingPerStep.size == octopusCount) return step + 1 } return totalGlows } fun adjacentPoints(y: Int, x: Int, input: List<IntArray>): List<IntArray> { return listOf( intArrayOf(y - 1, x), intArrayOf(y - 1, x + 1), intArrayOf(y, x + 1), intArrayOf(y + 1, x + 1), intArrayOf(y + 1, x), intArrayOf(y + 1, x - 1), intArrayOf(y, x - 1), intArrayOf(y - 1, x - 1) ).filter { (y, x) -> input.getOrNull(y)?.getOrNull(x) != null } } fun main() { println(solution(100, isPart2 = false)) println(solution(Int.MAX_VALUE, isPart2 = true)) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,799
adventofcode
Apache License 2.0
src/adventofcode/day04/Day04.kt
bstoney
574,187,310
false
{"Kotlin": 27851}
package adventofcode.day04 import adventofcode.AdventOfCodeSolution fun main() { Solution.solve() } typealias Section = Int object Solution : AdventOfCodeSolution<Int>() { override fun solve() { solve(4, 2, 4) } override fun part1(input: List<String>): Int { return getCleanUpPairs(input) .filter { it.assignment1.sections.size == it.sections.size || it.assignment2.sections.size == it.sections.size } .size } override fun part2(input: List<String>): Int { return getCleanUpPairs(input) .filter { it.assignment1.sections.size + it.assignment2.sections.size > it.sections.size } .size } private fun getCleanUpPairs(input: List<String>): List<CleanUpPair> = input .map { CleanUpPair(it) } .mapIndexed { index, cleanUpPair -> debug("Pair $index -> (${cleanUpPair.sections.size}) {${cleanUpPair.assignment1}(${cleanUpPair.assignment1.sections.size}),${cleanUpPair.assignment2}(${cleanUpPair.assignment2.sections.size})") cleanUpPair } class CleanUpPair(private val input: String) { private val assignments: List<Assignment> by lazy { input.split(",") .map { range -> val (start, end) = range.split("-") .map { it.toInt() } Assignment(start, end) } } val assignment1: Assignment by lazy { assignments[0] } val assignment2: Assignment by lazy { assignments[1] } val sections: Set<Section> by lazy { assignment1 union assignment2 } } data class Assignment(val start: Int, val end: Int) { val sections: Set<Section> by lazy { (start..end).toSet() } } } private infix fun Solution.Assignment.union(assignment: Solution.Assignment): Set<Section> = sections union assignment.sections
0
Kotlin
0
0
81ac98b533f5057fdf59f08940add73c8d5df190
1,913
fantastic-chainsaw
Apache License 2.0
src/main/kotlin/Day12.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { fun Char.getHeight(): Int = when (this) { 'S' -> 'a'.code 'E' -> 'z'.code else -> this.code } fun Point.toValid(input: Map<Point, Char>): List<Point> { val data = arrayOf((-1 to 0), (1 to 0), (0 to -1), (0 to 1)) .map { (dx, dy) -> Point(x + dx, y + dy) } return data.filter { it in input && input[it]!!.getHeight() - input[this]!!.getHeight() >= -1 } } fun move(input: Map<Point, Char>, currentPosition: Char): Int { val start = input.entries.first { it.value == 'E' }.key val distances = input.keys.associateWith { Int.MAX_VALUE }.toMutableMap() distances[start] = 0 val toVisit = mutableListOf(start) while (toVisit.isNotEmpty()) { val current = toVisit.removeFirst() current.toValid(input) .forEach { neighbour -> val newDistance = distances[current]!! + 1 if (input[neighbour] == currentPosition) return newDistance if (newDistance < distances[neighbour]!!) { distances[neighbour] = newDistance toVisit.add(neighbour) } } } return -1 } fun part1(input: Map<Point, Char>): Int = move(input, 'S') fun part2(input: Map<Point, Char>): Int = move(input, 'a') // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test").toPoints() check(part1(testInput) == 31) println(part2(testInput)) val input = readInput("Day12").toPoints() println(part1(input)) println(part2(input)) } fun List<String>.toPoints(): Map<Point, Char> = this .flatMapIndexed { y: Int, row: String -> row.mapIndexed { x, c -> Point(x, y) to c } } .toMap()
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
1,917
KotlinAdventOfCode2022
Apache License 2.0
src/main/kotlin/day12/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day12 import util.readTestInput enum class Direction(val dx: Int, val dy: Int) { LEFT(-1, 0), RIGHT(1, 0), UP(0, -1), DOWN(0, 1) } data class Position(val x: Int, val y: Int) { fun move(direction: Direction, amount: Int = 1) = Position(x + amount * direction.dx, y + amount * direction.dy) override fun toString(): String = "($x, $y)" } typealias Path = List<Position> class HeighMap(private val rows: List<String>) { private val width = rows[0].length private val height = rows.size private val startPos = findPositionOfChar('S') private val endPos = findPositionOfChar('E') private fun findPositionOfChar(searchedChar: Char): Position = findPositionsOfChar(searchedChar).first() fun findPositionsOfChar(searchedChar: Char): List<Position> { val positions = mutableListOf<Position>() for (y in 0 until height) { for (x in 0 until width) { if (rows[y][x] == searchedChar) positions.add(Position(x, y)) } } return positions } private fun heightAt(pos: Position): Char = when (rows[pos.y][pos.x]) { 'S' -> 'a' 'E' -> 'z' else -> rows[pos.y][pos.x] } private fun isValidPos(position: Position): Boolean = position.y in 0 until height && position.x in 0 until width private fun availablePositions(fromPos: Position): List<Position> { return Direction.values().map { fromPos.move(it) } .filter { position -> isValidPos(position) } .filter { position -> heightAt(position) - heightAt(fromPos) <= 1 } } // For visualization: fun draw(positions: Collection<Position>) { for (y in 0 until height) { for (x in 0 until width) { when { positions.contains(Position(x, y)) -> print('X') else -> print(heightAt(Position(x, y))) } } println("n") } } private fun nextPaths(currentPaths: List<Path>, visited: MutableSet<Position>): List<Path> { val newPaths = currentPaths.map { path -> val nextAvailable = availablePositions(path.last()).filter { !visited.contains(it) } if (nextAvailable.isEmpty()) emptyList<Path>() visited.addAll(nextAvailable) nextAvailable.map { path + it } }.filter { it.isNotEmpty() }.flatten() return newPaths; } fun findStepsToEnd(fromPos: Position = startPos): Int? { var currentPaths = listOf(listOf(fromPos)) val visited = mutableSetOf(fromPos) for (steps in 1 until 1000) { val nextPaths = nextPaths(currentPaths, visited) val newPositions = nextPaths.map { it.last() } if (newPositions.contains(endPos)) { return steps } visited.addAll(newPositions) currentPaths = nextPaths } return null } } fun part1(inputLines: List<String>): Int? { val heighMap = HeighMap(inputLines) return heighMap.findStepsToEnd() } fun part2(inputLines: List<String>): Int? { val heighMap = HeighMap(inputLines) val startingPoints = heighMap.findPositionsOfChar('a') return startingPoints .map { startPos -> heighMap.findStepsToEnd(startPos) } .filterNotNull() .min() } fun main() { val inputLines = readTestInput("day12") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
3,517
advent-of-code-2022
MIT License
src/aoc2022/Day12.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2022 import println import readInput import java.util.* fun main() { data class Position(val x: Int, val y: Int) : Comparable<Position> { public var distance: Int = Int.MAX_VALUE override fun compareTo(other: Position): Int { return distance - other.distance } fun neighbours(): List<Position> { return listOf(Position(x + 1, y), Position(x - 1, y), Position(x, y + 1), Position(x, y - 1)) } } class Terrain(val input: List<String>) { fun contains(position: Position): Boolean { return position.x >= 0 && position.x < input.size && position.y >= 0 && position.y < input[0].length } fun value(position: Position): Char { if (input[position.x][position.y] == 'S') return 'a' if (input[position.x][position.y] == 'E') return 'z' return input[position.x][position.y] } } fun minDistance(input: List<String>, start: Position): Int { val terrain = Terrain(input) val queue = PriorityQueue<Position>() val visited = mutableSetOf<Position>() start.distance = 0 queue.add(start) while (queue.isNotEmpty()) { val elem = queue.poll() visited.add(elem) for (n in elem.neighbours()) { if (terrain.contains(n) && !visited.contains(n) && terrain.value(elem) - terrain.value(n) >= -1) { if (input[n.x][n.y] == 'E') return elem.distance + 1 if (queue.contains(n)) { val inQueue = queue.find { it.equals(n) } queue.remove(inQueue) inQueue!!.distance = Math.min(inQueue!!.distance, elem.distance + 1) queue.add(inQueue) } else { n.distance = elem.distance + 1 queue.add(n) } } } } return Int.MAX_VALUE } fun part1(input: List<String>): Int { var start = Position(0, 0) for (i in input.indices) { for (j in input.indices) { if (input[i][j] == 'S') { start = Position(i, j) } } } return minDistance(input, start) } fun part2(input: List<String>): Int { val starts = mutableListOf<Position>() for (i in input.indices) { for (j in input[0].indices) { if (input[i][j] == 'S' || input[i][j] == 'a') { starts.add(Position(i, j)) } } } var min = Int.MAX_VALUE for (start in starts) { val dist = minDistance(input, start) min = Math.min(min, dist) } return min } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") part1(input).println() part2(input).println() }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
3,176
advent-of-code-kotlin
Apache License 2.0
src/Day09.kt
tsschmidt
572,649,729
false
{"Kotlin": 24089}
import kotlin.math.abs fun main() { fun moveTail(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int>? { if (head.first == tail.first) { if (abs((head.second) - (tail.second)) > 1) { return if (head.second < tail.second) { tail.first to tail.second - 1 } else { tail.first to tail.second + 1 } } } if (head.second == tail.second) { if (abs((head.first) - (tail.first)) > 1) { return if (head.first > tail.first) { tail.first + 1 to tail.second } else { tail.first - 1 to tail.second } } } if (abs((head.first) - (tail.first)) > 1 || abs((head.second) - (tail.second)) > 1) { return if (head.first > tail.first) { tail.first + 1 to if (head.second > tail.second) tail.second + 1 else tail.second - 1 } else { tail.first - 1 to if (head.second > tail.second) tail.second + 1 else tail.second - 1 } } return null } fun part1(input: List<String>): Int { val tail = mutableListOf<Pair<Int, Int>>(0 to 0) var head = 0 to 0 input.forEach { val move = it.split(" ") repeat(move[1].toInt()) { if (move[0] == "R") { head = head.first to head.second + 1 } if (move[0] == "D") { head = head.first + 1 to head.second } if (move[0] == "L") { head = head.first to head.second - 1 } if (move[0] == "U") { head = head.first - 1 to head.second } moveTail(head, tail.last())?.let { t -> tail.add(t) } } } return tail.distinct().size } fun part2(input: List<String>): Int { val tail = mutableListOf(0 to 0) val knots = mutableListOf<Pair<Int, Int>>().also { k -> repeat(9) { k.add(0 to 0)} } input.forEach { val move = it.split(" ") repeat(move[1].toInt()) { if (move[0] == "R") { knots[0] = knots[0].first to knots[0].second + 1 } if (move[0] == "D") { knots[0] = knots[0].first + 1 to knots[0].second } if (move[0] == "L") { knots[0] = knots[0].first to knots[0].second - 1 } if (move[0] == "U") { knots[0] = knots[0].first - 1 to knots[0].second } for (j in 0 until 8) { moveTail(knots[j], knots[j + 1])?.let { t -> knots[j + 1] = t } } moveTail(knots[8], tail.last())?.let { t -> tail.add(t) } } } return tail.distinct().size } //val input = readInput("Day09_part2") //check(part2(input) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
7bb637364667d075509c1759858a4611c6fbb0c2
3,231
aoc-2022
Apache License 2.0
src/Day14.kt
chbirmes
572,675,727
false
{"Kotlin": 32114}
import kotlin.math.max import kotlin.math.min fun main() { fun part1(input: List<String>): Int { val cave = Cave.parse(input, withFloor = false) return generateSequence { Sand() } .map { it.restPosition(cave) } .indexOfFirst { it == null } } fun part2(input: List<String>): Int { val cave = Cave.parse(input, withFloor = true) return generateSequence { Sand() } .map { it.restPosition(cave) } .indexOfFirst { it == sandSource } + 1 } val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") println(part1(input)) println(part2(input)) } val sandSource = Cave.Position(500, 0) class Sand(var position: Cave.Position = sandSource) { tailrec fun restPosition(cave: Cave): Cave.Position? = if (!cave.isAnythingBelow(position.y)) { null } else { val nextFree = sequenceOf( Cave.Position(position.x, position.y + 1), Cave.Position(position.x - 1, position.y + 1), Cave.Position(position.x + 1, position.y + 1), ) .firstOrNull { !cave.isBlocked(it) } if (nextFree == null) { position.also { cave.blockedPositions.add(it) } } else { position = nextFree restPosition(cave) } } } class Cave(val blockedPositions: MutableSet<Position>, private val withFloor: Boolean) { private val lowestBlocked = blockedPositions.maxOf { it.y } fun isAnythingBelow(y: Int) = withFloor || y < lowestBlocked fun isBlocked(position: Position) = (withFloor && position.y >= lowestBlocked + 2) || blockedPositions.contains(position) data class Position(val x: Int, val y: Int) { fun positionsTo(other: Position): Set<Position> = if (x == other.x) { ((min(y, other.y))..(max(y, other.y))) .map { Position(x, it) } .toSet() } else { ((min(x, other.x))..(max(x, other.x))) .map { Position(it, y) } .toSet() } } companion object { fun parse(input: List<String>, withFloor: Boolean): Cave { val positions = input.asSequence() .flatMap { line -> line.split(" -> ") .map { Position(it.substringBefore(',').toInt(), it.substringAfter(',').toInt()) } .windowed(2) .flatMap { it[0].positionsTo(it[1]) } } .toMutableSet() return Cave(positions, withFloor) } } }
0
Kotlin
0
0
db82954ee965238e19c9c917d5c278a274975f26
2,814
aoc-2022
Apache License 2.0
src/Day15.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
import kotlin.math.abs fun main() { class Sensor(val x: Int, val y: Int, val closestX: Int, val closestY: Int) { fun radius(): Int = abs(x - closestX) + abs(y - closestY) fun frontier(): Sequence<Pair<Int, Int>> { return sequence { for (a in 0..radius()) { yield(Pair(x - radius() - 1 + a, y - a)) yield(Pair(x + a, y - radius() - 1 + a)) yield(Pair(x + radius() + 1 - a, y + a)) yield(Pair(x - a, y + radius() + 1 - a)) } } } fun detects(px: Int, py: Int): Boolean { return abs(x - px) + abs(y - py) <= radius() } override fun toString(): String { return "($x, $y) [$closestX, $closestY]; radius=${radius()}" } } fun parseData(input: List<String>): Sequence<Sensor> { return sequence { input.forEach { line -> val regex = Regex("^Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)$") val match = regex.matchEntire(line)!! val values = match.groupValues.drop(1).toTypedArray() yield(Sensor(values[0].toInt(), values[1].toInt(), values[2].toInt(), values[3].toInt())) } } } fun part1(input: List<String>): Int { val targetY = 2_000_000 parseData(input) .map { val overlap = it.radius() - abs(it.y - targetY) if (overlap < 1) { return@map null } val range = IntRange(it.x - overlap, it.x + overlap) println("$it; overlap=$overlap; range=$range") range } .filterNotNull() .sortedBy { it.first } .forEach { println(it) } // Eye analysis :-] We are lucky that there are no holes in the sequence, so the final math is very easy :-) // The -1 is because there is one beacon in the range (appearing twice) that needs to be deduced. return 4651089 - -432198 + 1 - 1 } fun part2(input: List<String>): Long { // Idea : The beacon must be next to a sensor's border. // So let's check for all points on sensor's borders if they are detected by at least one sensor. // We start with sensors with a small radius because we feel like it :-) val sensors = parseData(input) parseData(input) .sortedBy { it.radius() } .forEach { println("Checking sensor $it.") val toCheck = it.frontier() val p = toCheck.find { (x, y) -> val inBounds = x in 0..4_000_000 && y in 0..4_000_000 val undetected = sensors.none { sensor -> sensor.detects(x, y) } inBounds && undetected } if (p != null) { println(p) return 4_000_000 * p.first.toLong() + p.second.toLong() } } return 42 } val input = readInput("Day15") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
3,224
aoc2022-kotlin
Apache License 2.0
src/year2023/06/Day06.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`06` import readInput import utils.printlnDebug private const val CURRENT_DAY = "06" data class Race( val time: Long, val distance: Long, ) data class Combination( val initTime: Long, val leftTime: Long, val travelDistance: Long, ) private fun parseInputIntoRaces(input: List<String>): List<Race> { val times = input.first().split(" ").mapNotNull { it.toLongOrNull() } val distances = input[1].split(" ").mapNotNull { it.toLongOrNull() } return times.mapIndexed { index, time -> Race(time, distances[index]) } } private fun findAllCombinations(race: Race): List<Combination> { val result = mutableListOf<Combination>() var currentTime = 0L while (currentTime != race.time) { val initSpeed = calculateSpeedForNumber(currentTime) val remainingTime = race.time - currentTime val travelDistance = calculateDistanceFor(initSpeed, remainingTime) result += Combination( initSpeed, remainingTime, travelDistance ) currentTime++ } return result } private fun calculateSpeedForNumber(num: Long): Long = num private fun calculateDistanceFor( initTime: Long, leftTime: Long, ): Long = initTime * leftTime fun main() { fun part1(input: List<String>): Int { val races = parseInputIntoRaces(input) .map { race -> findAllCombinations(race).count { it.travelDistance > race.distance } } return races.fold(1) { acc, raceCount -> acc * raceCount } } fun part2(input: List<String>): Int { val racesTime = parseInputIntoRaces(input).joinToString("") { it.time.toString() } val racesDistance = parseInputIntoRaces(input).joinToString("") { it.distance.toString() } printlnDebug { "TIME: $racesTime" } printlnDebug { "DISTANCE: $racesDistance" } val race = Race( time = racesTime.toLong(), distance = racesDistance.toLong(), ) return findAllCombinations(race).count { it.travelDistance > race.distance } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 288) val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 3316275) // Part 2 val part2 = part2(input) println(part2) check(part2 == 27102791) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
2,547
KotlinAdventOfCode
Apache License 2.0
src/day03/Day03.kt
banshay
572,450,866
false
{"Kotlin": 33644}
package day03 import readInput fun main() { fun part1(input: List<String>): Int { return input.sumOf { rucksackInput -> val priority = priorityMap[rucksackInput.toRucksack().getMisplacedType()] priority ?: 0 } } fun part2(input: List<String>): Int { return input.chunked(3) .sumOf { group -> val sharedType = group.map { rucksackInput -> rucksackInput.toRucksack().toSet() } .fold(mutableSetOf<Char>()) { acc, rucksack -> if (acc.isEmpty()) { acc.addAll(rucksack) } acc.apply { retainAll(rucksack) } } priorityMap[sharedType.first()] ?: 0 } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") println("test part1: ${part1(testInput)}") println("test part2: ${part2(testInput)}") val input = readInput("Day03") println("result part1: ${part1(input)}") println("result part2: ${part2(input)}") } fun String.toRucksack() = Rucksack(substring(0, length / 2).toCharArray().toList(), substring(length / 2).toCharArray().toList()) typealias Compartment = List<Char> data class Rucksack(val leftCompartment: Compartment, val rightCompartment: Compartment) { fun getMisplacedType(): Char { return leftCompartment.intersect(rightCompartment).first() } fun toSet(): Set<Char> = (leftCompartment + rightCompartment).toMutableSet() } private val alphabet = listOf( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ) private val upperAlphabet = alphabet.map { it.uppercase().toCharArray().first() } private val priorityMap = (alphabet + upperAlphabet).mapIndexed { index, char -> char to index + 1 }.toMap()
0
Kotlin
0
0
c3de3641c20c8c2598359e7aae3051d6d7582e7e
2,063
advent-of-code-22
Apache License 2.0
src/Day18.kt
Riari
574,587,661
false
{"Kotlin": 83546, "Python": 1054}
import kotlin.math.abs fun main() { data class MinMax(var min: Int = Int.MAX_VALUE, var max: Int = Int.MIN_VALUE): Iterable<Int> { fun update(value: Int) { min = minOf(min, value) max = maxOf(max, value) } override fun iterator(): Iterator<Int> { return (min..max).iterator() } } data class Vector(val x: Int, val y: Int, val z: Int) { fun isAdjacentTo(other: Vector): Boolean { if (y == other.y && z == other.z && abs(x - other.x) == 1) return true if (x == other.x && z == other.z && abs(y - other.y) == 1) return true if (x == other.x && y == other.y && abs(z - other.z) == 1) return true return false } } fun List<Vector>.has(x: Int, y: Int, z: Int): Boolean { return this.any { it.x == x && it.y == y && it.z == z } } fun processInput(input: List<String>): List<Vector> { return input.map { it.split(',').map { c -> c.toInt() } } .map { Vector(it[0], it[1], it[2]) } } fun solve(grid: List<Vector>, withoutInterior: Boolean = false): Int { var totalFaces = grid.size * 6 val xRange = MinMax(); val yRange = MinMax(); val zRange = MinMax() for (position in grid) { for (other in grid) { if (position == other) continue if (position.isAdjacentTo(other)) totalFaces-- } if (withoutInterior) { xRange.update(position.x) yRange.update(position.y) zRange.update(position.z) } } if (!withoutInterior) return totalFaces for (x in xRange) { for (y in yRange) { for (z in zRange) { if (grid.has(x, y, z)) continue val blocked = listOf( (x .. xRange.max).any { grid.has(it, y, z) }, // Right (x downTo xRange.min).any { grid.has(it, y, z) }, // Left (y .. yRange.max).any { grid.has(x, it, z) }, // Forward (y downTo yRange.min).any { grid.has(x, it, z) }, // Backward (z .. zRange.max).any { grid.has(x, y, it) }, // Above (z downTo zRange.min).any { grid.has(x, y, it) } // Below ) // TODO: update this to measure distances so that the additional adjacency checks aren't needed if (blocked.all { it }) { for (block in grid) { if (Vector(x, y, z).isAdjacentTo(block)) totalFaces-- } } } } } return totalFaces } fun part1(grid: List<Vector>): Int { return solve(grid) } fun part2(grid: List<Vector>): Int { return solve(grid, true) } val testInput = processInput(readInput("Day18_test")) check(part1(testInput) == 64) check(part2(testInput) == 58) val input = processInput(readInput("Day18")) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d
3,207
aoc-2022
Apache License 2.0
src/Day08.kt
arhor
572,349,244
false
{"Kotlin": 36845}
fun main() { val input = readInput {} val (visibleTrees, bestScenicScore) = solvePuzzle(input) println("Part 1: $visibleTrees") println("Part 2: $bestScenicScore") } private fun solvePuzzle(input: List<String>): Pair<Int, Int> { val data = input.map { it.map(Char::digitToInt) } val rows = data.size val cols = data.first().size var visibleTrees = (rows + cols) * 2 - 4 var bestScenicScore = 0 for (y in 1 until rows - 1) { for (x in 1 until cols - 1) { val value = data[y][x] val lines = data.iterateToEdges(x, y) val lessThanCurrentValue = { other: Int -> other < value } if (lines.any { it.all(lessThanCurrentValue) }) { visibleTrees++ lines.map { line -> line.countUntil(lessThanCurrentValue) }.reduce { a, b -> a * b }.also { if (it > bestScenicScore) { bestScenicScore = it } } } } } return visibleTrees to bestScenicScore } private fun <T> List<List<T>>.iterateToEdges(x: Int, y: Int): Sequence<List<T>> { val data = this return sequence { yield(value = data[y].slice(0 until x).reversed()) yield(value = data[y].slice((x + 1) until data[y].size)) yield(value = (0 until y).map { data[it][x] }.reversed()) yield(value = ((y + 1) until data.size).map { data[it][x] }) } }
0
Kotlin
0
0
047d4bdac687fd6719796eb69eab2dd8ebb5ba2f
1,465
aoc-2022-in-kotlin
Apache License 2.0
src/App.kt
tonicsoft
230,460,897
false
null
import java.nio.file.Files import java.nio.file.Paths import java.util.* import kotlin.streams.toList val words = Files.readAllLines(Paths.get("words.txt")).asSequence().map { it.toLowerCase() } .filter { !it.contains("-") } .filter { !it.contains("'") } .filter { !it.equals("hutukhtu") } .filter { !it.equals("kavakava") } .filter { !it.equals("kawakawa") } .filter { !it.equals("kivikivi") } .filter { !it.equals("kiwikiwi") } .filter { !it.equals("kolokolo") } .filter { !it.equals("malikala") } .filter { !it.equals("wanakena") } .filter { !it.equals("thisll") } .filter { !it.equals("tavell") } .filter { !it.equals("tewell") } .filter { !it.equals("thatll") } .filter { !it.equals("towill") } .filter { !it.equals("ploss") } .filter { !it.equals("theall") } .toList() //var solution = mapOf( // 6 to "h", // 8 to "f" //) //var clues = listOf( // listOf(10, 2, 18, 23, 6, 17 ,5, 19) //) class TreeNode(val solutionSoFar: Map<Int, String>, val clue: Int) { val children = mutableListOf<TreeNode>() } fun solve(clues: List<List<Int>>, solution: Map<Int, String>): List<Map<Int, String>> { val possibleSolutions = mutableListOf<Map<Int, String>>() val nodeQueue = ArrayDeque<TreeNode>() nodeQueue.add(TreeNode(solution, 0)) while (nodeQueue.isNotEmpty()) { val current = nodeQueue.pop() val seenNumbers = mutableMapOf<Int, Int>() val distinctLetters = clues[current.clue].distinct().size var filtered = words.asSequence() .filter { it.length == clues[current.clue].size } for (i in clues[current.clue].indices) { val number = clues[current.clue][i] if (current.solutionSoFar.containsKey(number)) { filtered = filtered.filter { it[i].toString() == current.solutionSoFar[number] } } else { if (seenNumbers.containsKey(number)) { filtered = filtered.filter { it[i] == it[seenNumbers.getValue(number)] } } else { seenNumbers[number] = i } } } val possibleWords = filtered .filter { it.chars().distinct().toList().size == distinctLetters } .toList() possibleWords.forEach { word -> val nextSolution = mutableMapOf<Int, String>() nextSolution.putAll(current.solutionSoFar) word.forEachIndexed { index, char -> nextSolution.put(clues[current.clue][index], char.toString()) } if (current.clue == clues.size - 1) { possibleSolutions.add(nextSolution) } else { val newNode = TreeNode(nextSolution, current.clue + 1) current.children.add(newNode) nodeQueue.add(newNode) } } } possibleSolutions.forEach { solution -> println("---- ") println("solution: ") clues.forEach { clue -> clue.forEach { character -> print(solution[character]) } print("\n") } } println("${possibleSolutions.size} solutions") val numSolutions = possibleSolutions.size for (i in 1..26) { val answers = mutableSetOf<String>() var count = 0; possibleSolutions.forEach { possibleSolution -> if (possibleSolution.containsKey(i)) { answers.add(possibleSolution.getValue(i)) count++ } } if (answers.size == 1 && count == numSolutions) { println("solved $i=${answers.iterator().next()}") } } return possibleSolutions } fun main() { val solution = solve( listOf ( listOf(6,15,16,23,17,15,24,23), listOf(4,23,5,15,12,23), listOf(23,13,13,23,7,23), listOf(13,1,23,17,5), listOf(21,4,26,21,6,14) ), mapOf( // 1 to "o", // 2 to "t", // 3 to "g", 4 to "b", 5 to "h", 6 to "n", 7 to "t", // 8 to "v", // 9 to "i", // 10 to "-", // 11 to "c", 12 to "v", 13 to "f", // 14 to "d", 15 to "a", // 16 to "-", // 17 to "a", // 18 to "m", 20 to "i", 21 to "o", // 22 to "-", 23 to "e", 24 to "k" // 25 to "-", // 26 to "n" // 27 to "w", // 28 to "p", // 31 to "-", // 35 to "-", // 38 to "-" ) ) val i = 0 }
0
Kotlin
0
0
47e62249cf73c8489be0d777782d36324f67d97c
4,670
alphapuzzle-solver
Apache License 2.0
src/Day11.kt
davedupplaw
573,042,501
false
{"Kotlin": 29190}
import java.math.BigInteger fun main() { var lowestCommonModulus: Long data class Item(var worryLevel: Long) data class Monkey( val number: Int, val items: MutableList<Item> = mutableListOf(), val operation: String, val operationOperand: String, val testDivisibleBy: Long, val trueThrow: Int, val falseThrow: Int ) { var itemsInspected = BigInteger.ZERO fun test(item: Item) = (item.worryLevel % testDivisibleBy) == 0L fun updateWorryLevel(item: Item) { val operand = if (operationOperand == "old") item.worryLevel else operationOperand.toLong() return when (operation) { "*" -> item.worryLevel *= operand "+" -> item.worryLevel += operand else -> error("Not allowed") } } fun throwTo(item: Item, reduceWorry: Boolean, lowestCommonModulus: Long): Int { itemsInspected++ updateWorryLevel(item) if (reduceWorry) item.worryLevel /= 3 else item.worryLevel %= lowestCommonModulus val result = test(item) return if (result) trueThrow else falseThrow } } fun parseInput(input: String): List<Monkey> { val monkeys = input.split("\n\n").map { monkeyInput -> val lines = monkeyInput.lines() val monkeyN = lines[0].split(" ", ":")[1].toInt() val splitItems = lines[1].split(" ", ":", ",").filter { it.isNotBlank() } val items = (2 until splitItems.size).map { Item(splitItems[it].toLong()) } val operationSplit = lines[2].split(" ").filter { it.isNotBlank() } val operation = operationSplit[4] val operationOperand = operationSplit[5] val divBy = lines[3].split(" ").filter { it.isNotBlank() }[3].toLong() val onTrue = lines[4].split(" ").filter { it.isNotBlank() }[5].toInt() val onFalse = lines[5].split(" ").filter { it.isNotBlank() }[5].toInt() Monkey(monkeyN, items.toMutableList(), operation, operationOperand, divBy, onTrue, onFalse) } return monkeys } fun getThoseMonkeysTyping(input: String, nTimes: Int, reduceWorry: Boolean): BigInteger { val monkeys = parseInput(input) lowestCommonModulus = monkeys.map { it.testDivisibleBy }.reduce { a, b -> a * b } repeat(nTimes) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkeys[monkey.throwTo(item, reduceWorry, lowestCommonModulus)].items += item } monkey.items.clear() } } return monkeys .map { it.itemsInspected } .sortedByDescending { it } .take(2).reduce { a, b -> a * b } } fun part1(input: String): BigInteger { return getThoseMonkeysTyping(input, 20, true) } fun part2(input: String): BigInteger { return getThoseMonkeysTyping(input, 10_000, false) } val test = readInputToString("Day11.test") val part1test = part1(test) println("part1 test: $part1test") check(part1test == BigInteger.valueOf(10605)) val part2test = part2(test) println("part2 test: $part2test") check(part2test == BigInteger.valueOf(2_713_310_158L)) val input = readInputToString("Day11") val part1 = part1(input) println("Part1: $part1") val part2 = part2(input) println("Part2: $part2") }
0
Kotlin
0
0
3b3efb1fb45bd7311565bcb284614e2604b75794
3,545
advent-of-code-2022
Apache License 2.0
src/day03/day03.kt
tmikulsk1
573,165,106
false
{"Kotlin": 25281}
package day03 import readInput /** * Advent of Code 2022 - Day 3 * @author tmikulsk1 */ fun main() { val inputRucksacks = readInput("day03/input.txt").readLines() getPuzzle1PriorityRucksacks(inputRucksacks) getPuzzle2PriorityRucksacks(inputRucksacks) } /** * Puzzle 1: show priority from half grouped rucksacks */ fun getPuzzle1PriorityRucksacks(inputRucksacks: List<String>) { val alphabetList = getAlphabetLowerAndUpperCaseList() val prioritySum = getRucksackSplitInInHalfPrioritySum(inputRucksacks, alphabetList) println(prioritySum) } /** * Puzzle 2: show priority third grouped rucksacks */ fun getPuzzle2PriorityRucksacks(inputRucksacks: List<String>) { val alphabetList = getAlphabetLowerAndUpperCaseList() val rucksacks = separateRucksackByThree(inputRucksacks) val prioritySum = getRucksackSplitInThirdPrioritySum(rucksacks, alphabetList) println(prioritySum) } fun getRucksackSplitInThirdPrioritySum( inputRucksacks: List<List<String>>, alphabetList: List<Char> ): Int { var prioritySum = 0 inputRucksacks.forEach { threeRuckSacks -> val firstRucksackPart = threeRuckSacks[0].toHashSet() val secondRucksackPart = threeRuckSacks[1].toHashSet() val thirdRucksackPart = threeRuckSacks[2].toHashSet() val commonLetter = firstRucksackPart intersect secondRucksackPart intersect thirdRucksackPart val index = alphabetList.indexOf(commonLetter.first()) prioritySum += index + 1 } return prioritySum } fun separateRucksackByThree(inputRucksacks: List<String>): List<List<String>> = inputRucksacks.chunked(3) fun getRucksackSplitInInHalfPrioritySum( inputRucksacks: List<String>, alphabetList: List<Char> ): Int { var prioritySum = 0 inputRucksacks.splitRucksacksInHalf().forEach { sack -> val rucksackKeySet = sack.keys.first().toSet() val rucksackValueSet = sack.values.first().toSet() val commonLetter = rucksackKeySet.intersect(rucksackValueSet) val index = alphabetList.indexOf(commonLetter.first()) prioritySum += index + 1 } return prioritySum } fun List<String>.splitRucksacksInHalf(): List<HashMap<String, String>> = map { rucksack -> val halfRucksack = rucksack.length / 2 val firstHalfPart = rucksack.substring(0, halfRucksack) val secondHalfPart = rucksack.substring(halfRucksack) return@map hashMapOf(firstHalfPart to secondHalfPart) } fun getAlphabetLowerAndUpperCaseList(): List<Char> = listOf('a'..'z', 'A'..'Z').flatten().toList()
0
Kotlin
0
1
f5ad4e601776de24f9a118a0549ac38c63876dbe
2,576
AoC-22
Apache License 2.0
src/main/kotlin/de/nilsdruyen/aoc/Day07.kt
nilsjr
571,758,796
false
{"Kotlin": 15971}
package de.nilsdruyen.aoc fun main() { fun part1(input: List<String>): Int { val tree: MutableList<Entry.Directory> = mutableListOf() val currentDir = mutableSetOf<String>() val dirTree = mutableListOf<String>() input.forEachIndexed { index, line -> if (line.startsWith('$')) { val (_, command) = line.split(" ") when (command) { "cd" -> { val (_, _, dir) = line.split(" ") if (dir == "..") { if (currentDir.size > 1) { currentDir.remove(currentDir.last()) } } else { currentDir.add(dir) } } "ls" -> { val cDir = currentDir.format() if (tree.none { it.name == cDir }) { tree.add(Entry.Directory(cDir)) } } } } else { println("$index - $currentDir") dirTree.add(currentDir.format()) when { line.startsWith("dir") -> { val (_, name) = line.split(" ") val cDir = currentDir.format() if (cDir == "/") { tree.add(Entry.Directory("$cDir$name")) } else { tree.add(Entry.Directory("$cDir/$name")) } } else -> { val (size, name) = line.split(" ") val cDir = currentDir.format() val entryIndex = tree.indexOfFirst { it.name == cDir } val entry = tree[entryIndex] tree.removeAt(entryIndex) tree.add(entryIndex, entry.copy(entries = entry.entries + Entry.File(name, size.toInt()))) } } } } // tree.forEach { println(it) } val mostOf = tree.filter { it.size(tree) in 1..100_000 }.sumOf { println("${it.name} - ${it.size()}") it.size(tree) } return mostOf } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) val input = readInput("Day07") println(part1(input)) // 1374288 too high // 1347822 too low println(part2(input)) } fun Set<String>.format(): String { return if (size == 1) { first() } else { joinToString("/").drop(1) } } sealed interface Entry { val name: String data class Directory( override val name: String, val entries: List<Entry> = emptyList(), ) : Entry { fun size(other: List<Directory> = emptyList()): Int { val plusSize = other.filter { it.name.contains(name) && it.name != name }.sumOf { it.size() } return entries.sumOf { when (it) { is Directory -> 0 is File -> it.size } } + plusSize } } data class File( override val name: String, val size: Int, ) : Entry }
0
Kotlin
0
0
1b71664d18076210e54b60bab1afda92e975d9ff
3,567
advent-of-code-2022
Apache License 2.0
src/aoc2022/Day08.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2022 import readInput fun main() { val (year, day) = "2022" to "Day08" fun List<String>.parseTrees(): Map<Pair<Int, Int>, Char> { val trees = mutableMapOf<Pair<Int, Int>, Char>() this.forEachIndexed { y, line -> line.forEachIndexed { x, c -> trees[x to y] = c } } return trees } fun viewingDistance(range: IntProgression, height: Char, tree: (Int) -> Char) = when { range.isEmpty() -> 0 else -> { val index = range.map { tree(it) }.indexOfFirst { it >= height } if (index < 0) range.count() else index + 1 } } fun part1(input: List<String>): Int { val trees = input.parseTrees() val size = input.first().length return trees.entries.count { (pos, height) -> val (x, y) = pos val horizontal = (0 until x).all { trees[it to y]!! < height } || (x + 1 until size).all { trees[it to y]!! < height } val vertical = (0 until y).all { trees[x to it]!! < height } || (y + 1 until size).all { trees[x to it]!! < height } horizontal || vertical } } fun part2(input: List<String>): Int { val trees = input.parseTrees() val size = input.first().length return trees.maxOf { (pos, height) -> val (x, y) = pos val left = viewingDistance(x - 1 downTo 0, height) { trees[it to y]!! } val right = viewingDistance(x + 1 until size, height) { trees[it to y]!! } val up = viewingDistance(y - 1 downTo 0, height) { trees[x to it]!! } val down = viewingDistance(y + 1 until size, height) { trees[x to it]!! } left * right * up * down } } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) check(part1(testInput) == 21) println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,121
aoc-kotlin
Apache License 2.0
src/day18/Day18.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day18 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val lavas = File("src/day18/input.txt").readLines().map { it.split(',') }.map { Triple(it[0].toInt(), it[1].toInt(), it[2].toInt()) } val deltas = listOf( Triple(1, 0, 0), Triple(-1, 0, 0), Triple(0, 1, 0), Triple(0, -1, 0), Triple(0, 0, 1), Triple(0, 0, -1) ) println(lavas.sumOf { lava -> deltas.map { delta -> lava + delta }.count { other -> other !in lavas } }) val min = lavas.reduce { t1, t2 -> Triple(min(t1.first, t2.first), min(t1.second, t2.second), min(t1.third, t2.third))} val max = lavas.reduce { t1, t2 -> Triple(max(t1.first, t2.first), max(t1.second, t2.second), max(t1.third, t2.third))} val pockets = mutableListOf<Triple<Int, Int, Int>>() val nonPockets = mutableListOf<Triple<Int, Int, Int>>() for (x in min.first .. max.first) { for (y in min.second .. max.second) { loop@ for (z in min.third .. max.third) { val start = Triple(x, y, z) if (start in lavas || start in pockets || start in nonPockets) continue val potentialPocket = mutableListOf(start) val stack = mutableListOf(start) while (stack.isNotEmpty()) { val next = stack.removeAt(0) val surrounding = deltas.map { delta -> next + delta }.filter { it !in lavas }.filter { it !in potentialPocket } val reachedEdge = surrounding.any { it.first <= min.first || it.second <= min.second || it.third <= min.third || it.first >= max.first || it.second >= max.second || it.third >= max.third } if (reachedEdge) { nonPockets.addAll(potentialPocket) continue@loop } stack.addAll(surrounding) potentialPocket.addAll(surrounding) } pockets.addAll(potentialPocket) // it is a pocket! } } } println(lavas.sumOf { lava -> deltas.map { delta -> lava + delta }.count { other -> other !in lavas && other !in pockets } }) } private operator fun Triple<Int, Int, Int>.plus(other: Triple<Int, Int, Int>) = Triple(first + other.first, second + other.second, third + other.third)
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
2,430
advent-of-code-2022
MIT License
src/Day07.kt
aaronbush
571,776,335
false
{"Kotlin": 34359}
sealed class FileSystemObject data class FileSystemDirectory( val name: String, val children: MutableMap<String, FileSystemObject>, val parent: FileSystemDirectory?, // todo: squash nullable parent. var size: Long = 0 ) : FileSystemObject() { override fun toString() = "FileSystemDirectory(name='$name', children=$children, parent=${parent?.name}, size=$size)" fun cd(name: String) = children[name]!! as FileSystemDirectory // let it fail if not a dir fun <R> map(f: (FileSystemDirectory) -> R): List<R> { fun loop(d: FileSystemDirectory, accum: MutableList<R>) { accum += f(d) d.children.values.filterIsInstance<FileSystemDirectory>().map { loop(it, accum) } } val result = mutableListOf<R>() loop(this, result) return result } fun forEachDir(f: (FileSystemDirectory) -> Unit) { f(this) this.children.values.filterIsInstance<FileSystemDirectory>().forEach { it.forEachDir(f) } } fun calculateSize() { fun loop(pwd: FileSystemDirectory): Long { val sumOfFiles = pwd.children.values.filterIsInstance<FileSystemFile>().sumOf { it.size } pwd.size += sumOfFiles if (pwd.children.values.filterIsInstance<FileSystemDirectory>().isEmpty()) { return sumOfFiles } val subDirSize = pwd.children.values.filterIsInstance<FileSystemDirectory>().sumOf { loop(it) } pwd.size += subDirSize return subDirSize + sumOfFiles } loop(this) } } data class FileSystemFile(val name: String, val size: Long) : FileSystemObject() fun main() { fun parseOutput(input: List<String>): FileSystemDirectory { val root = FileSystemDirectory("/", mutableMapOf(), null) var pwd = root input.forEach { line -> when (line.take(1)) { "$" -> { // cmd line val cmd = line.split(" ") when (cmd[1]) { "cd" -> { pwd = when (cmd[2]) { "/" -> root ".." -> pwd.parent!! else -> pwd.cd(cmd[2]) } } else -> {} // do we care? } } // output line else -> { val type = line.split(" ") when (type[0]) { "dir" -> { val d = FileSystemDirectory(type[1], mutableMapOf(), pwd) pwd.children[d.name] = d } else -> { val f = FileSystemFile(type[1], type[0].toLong()) pwd.children[f.name] = f } } } } } return root } fun part1(input: List<String>): Long { val root = parseOutput(input) root.calculateSize() val withinSpec = root.map { if (it.size <= 100000) it else null }.filterNotNull() return withinSpec.sumOf { it.size } } fun part2(input: List<String>): Long { val root = parseOutput(input) root.calculateSize() val totalSize = 70000000 val neededSize = 30000000 val free = totalSize - root.size val mustFree = neededSize - free val candidates = root.map { if (it.size >= mustFree) it else null }.filterNotNull() val x = candidates.sortedBy { it.size }.map { it.size } return x.first() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println("p1: ${part1(input)}") println("p2: ${part2(input)}") }
0
Kotlin
0
0
d76106244dc7894967cb8ded52387bc4fcadbcde
4,046
aoc-2022-kotlin
Apache License 2.0
src/Day20.kt
sabercon
648,989,596
false
null
fun main() { data class Tile(val id: Int, val data: List<String>) { val top = data.first() val bottom = data.last() val left = data.map { it.first() }.joinToString("") val right = data.map { it.last() }.joinToString("") fun flip() = copy(data = data.reversed()) fun rotate() = copy(data = data.indices.map { i -> data.map { it[i] }.joinToString("") }).flip() fun possibleOriginalTiles(): List<Tile> { return generateSequence(listOf(this)) { it + it.last().rotate() } .elementAt(3) .flatMap { listOf(it, it.flip()) } } fun image(): List<String> = data.drop(1).dropLast(1).map { it.drop(1).dropLast(1) } } fun arrangeTiles(tiles: List<Tile>): List<List<Tile>> { val allPossibleTiles = tiles.flatMap { it.possibleOriginalTiles() } val topEdgeTilesMap = allPossibleTiles.groupBy { it.top } val leftEdgeTilesMap = allPossibleTiles.groupBy { it.left } val topLeftCorner = topEdgeTilesMap.filterValues { it.size == 1 }.map { it.value[0] } .intersect(leftEdgeTilesMap.filterValues { it.size == 1 }.map { it.value[0] }.toSet()) .first() val arrangement = mutableListOf(mutableListOf(topLeftCorner)) while (arrangement.size * arrangement.last().size < tiles.size) { val lastRow = arrangement.last() val lastTile = lastRow.last() if (leftEdgeTilesMap[lastTile.right]!!.size == 1) { val nextTile = topEdgeTilesMap[lastRow.first().bottom]!!.single { it.id != lastRow.first().id } arrangement.add(mutableListOf(nextTile)) } else { val nextTile = leftEdgeTilesMap[lastTile.right]!!.single { it.id != lastTile.id } lastRow.add(nextTile) } } return arrangement } fun mergeTiles(arrangement: List<List<Tile>>): List<String> { return arrangement.flatMap { row -> val images = row.map { it.image() } images[0].indices.map { i -> images.joinToString("") { it[i] } } } } val monster = listOf( " # ", "# ## ## ###", " # # # # # # " ) val monsterIndexes = monster.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') x to y else null } } fun hasMonster(image: List<String>, x: Int, y: Int): Boolean { return monsterIndexes.all { (dx, dy) -> image.getOrNull(y + dy)?.getOrNull(x + dx) == '#' } } fun findMonsters(image: List<String>): Int { return image.indices.sumOf { y -> image[y].indices.count { x -> hasMonster(image, x, y) } } } val input = readText("Day20").split(LINE_SEPARATOR + LINE_SEPARATOR) val tiles = input.map { val lines = it.lines() val (id) = """Tile (\d+):""".toRegex().destructureGroups(lines[0]) Tile(id.toInt(), lines.drop(1)) } val arrangement = arrangeTiles(tiles) (1L * arrangement.first().first().id * arrangement.first().last().id * arrangement.last().first().id * arrangement.last().last().id).println() val image = mergeTiles(arrangement) val monsters = Tile(0, image) .possibleOriginalTiles() .map { findMonsters(it.data) } .single { it > 0 } (image.sumOf { row -> row.count { it == '#' } } - monsters * 15).println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
3,505
advent-of-code-2020
MIT License
src/Day05.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
fun main() { fun String.extractNumbers(): List<Int> { return split(' ').filter { word -> !word.any { char: Char -> !char.isDigit() } }.map { it.toInt() } } fun rotate(n: Int, input: List<List<Char>>): MutableList<MutableList<Char>> { val stacks = MutableList(n) { MutableList(0) { ' ' } } input.forEach { row -> row.forEachIndexed { index, crane -> if (crane != ' ') stacks[index] += crane } } return stacks } class Move(val count: Int, val from: Int, val to: Int) class Map(n: Int, rows: List<List<Char>>) { val stacks = rotate(n, rows) fun perform(move: Move, onceAtTime: Boolean) { val toMove = stacks[move.from].subList(0, move.count) if (onceAtTime) toMove.reverse() stacks[move.to].addAll(0, toMove) stacks[move.from] = stacks[move.from].drop(move.count).toMutableList() } fun getState(): String { return stacks.map { it[0] }.joinToString("") } } fun parseInput(input: String): Pair<Map, List<Move>> { val (mapStr, movesStr) = input.split("\n\n") val rows = mapStr.split('\n') val parsedRows = rows .dropLast(1) .map { it .toCharArray() .toList() .chunked(4) .map { it[1] } } val map = Map(rows.last().split(" ").count(), parsedRows) val moves = movesStr .split('\n') .map { str -> val numbers = str.extractNumbers() Move(numbers[0], numbers[1] - 1, numbers[2] - 1) } return map to moves } fun part1(input: String): String { val (map, moves) = parseInput(input) moves.forEach { move -> map.perform(move, true) } return map.getState() } fun part2(input: String): String { val (map, moves) = parseInput(input) moves.forEach { move -> map.perform(move, false) } return map.getState() } val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput(5) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
2,043
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
solutions/aockt/y2022/Y2022D08.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2022 import io.github.jadarma.aockt.core.Solution object Y2022D08 : Solution { /** Parse the input and return the 2D [ForestMap]. */ private fun parseInput(input: String): ForestMap = input .lines() .map { line -> IntArray(line.length) { i -> line[i].digitToInt() } } .toTypedArray() .let(::ForestMap) /** * All known information about a forest tree. * @property x The X coordinate. * @property y The Y coordinate. * @property height The height of the tree in meters. * @property isVisible Whether the tree is visible from outside the forest. * @property scenicScore How cool a view you'd get from the POV of this tree. */ private data class TreeInfo( val x: Int, val y: Int, val height: Int, val isVisible: Boolean, val scenicScore: Int, ) { init { require(x >= 0 && y >= 0) { "Tree location cannot have negative coordinates." } require(height >= 0) { "Height cannot be negative." } require(scenicScore >= 0) { "Scenic score cannot be negative." } } } /** * A 2D map of a forest with computed visibility information. * @constructor Builds a map from the raw values of the tree heights. */ private class ForestMap(heights: Array<IntArray>) : Iterable<TreeInfo> { /** The width and height of the forest, respectively. */ val dimensions: Pair<Int, Int> /** Info of each tree, indexed by location. */ private val trees: Map<Pair<Int, Int>, TreeInfo> init { require(heights.isNotEmpty() && heights.first().isNotEmpty()) { "Cannot accept empty map." } require(heights.all { it.size == heights.first().size }) { "2D Map is missing some coordinates." } dimensions = heights[0].size to heights.size trees = buildMap { val (width, height) = dimensions for (row in 0 until height) { for (col in 0 until width) { val treeHeight = heights[row][col] val directionView = listOf( (col - 1 downTo 0).map { heights[row][it] }, // Left (col + 1 until width).map { heights[row][it] }, // Right (row - 1 downTo 0).map { heights[it][col] }, // Up, (row + 1 until height).map { heights[it][col] }, // Down ) val isVisible = directionView.any { direction -> direction.all { it < treeHeight } } val scenicScore = directionView .map { direction -> direction to direction.takeWhile { it < treeHeight }.count() } .map { (trees, count) -> count + if (count < trees.size) 1 else 0 } .reduce(Int::times) put(row to col, TreeInfo(row, col, treeHeight, isVisible, scenicScore)) } } } } /** Get info about a tree at the given location; (0,0) is the top left corner. */ operator fun get(x: Int, y: Int): TreeInfo = trees.getValue(x to y) /** Iterates through the forest.*/ override fun iterator(): Iterator<TreeInfo> = trees.values.iterator() } override fun partOne(input: String) = parseInput(input).count { it.isVisible } override fun partTwo(input: String) = parseInput(input).maxOf { it.scenicScore } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
3,613
advent-of-code-kotlin-solutions
The Unlicense
2021/src/Day08.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import kotlin.math.abs // https://adventofcode.com/2021/day/8 fun main() { fun part1() { var result = 0 for (line in readInput("Day08")) { val data = line.split(" | ") result += data[1].split(" ").filter { it.length == 2 || it.length == 3 || it.length == 4 || it.length == 7 }.size } println(result) } fun computeEntry(input: List<String>, output: List<String>): Int { val one = input.find { it.length == 2 }!! val four = input.find { it.length == 4 }!! val seven = input.find { it.length == 3 }!! val eight = input.find { it.length == 7 }!! val lFiveSegments = input.filter { it.length == 5 }.toMutableList() val lSixSegments = input.filter { it.length == 6 }.toMutableList() val three = lFiveSegments.find { it.replace("[$one]".toRegex(), "").length == 3 }!! lFiveSegments.remove(three) val six = lSixSegments.find { it.replace("[$one]".toRegex(), "").length == 5 }!! lSixSegments.remove(six) val topRightSegment = eight.replace("[$six]".toRegex(), "") val five = lFiveSegments.find { !it.contains(topRightSegment) }!! lFiveSegments.remove(five) val two = lFiveSegments.first()!! val nine = lSixSegments.find { three.replace("[$it]".toRegex(), "").length == 0 }!! lSixSegments.remove(nine) val zero = lSixSegments.last()!! val numbers = mapOf(zero to 0, one to 1, two to 2, three to 3, four to 4, five to 5, six to 6, seven to 7, eight to 8, nine to 9) return output.map { numbers[it] }.joinToString("").toInt() } fun part2() { var allData = mutableListOf<Pair<List<String>, List<String>>>() for (line in readInput("Day08")) { val data = line.split(" | ") val input = data[0].split(" ").map { it.toSortedSet().joinToString("") } val output = data[1].split(" ").map { it.toSortedSet().joinToString("") } allData.add(Pair(input, output)) } var result : Long = 0 for (data in allData) { result += computeEntry(data.first, data.second) } println(result) } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
2,069
advent-of-code
Apache License 2.0
src/Day07.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
import kotlin.math.min private class Node(private val parent: Node?, var size: Int, private val type: TYPE) { enum class TYPE { FILE, DIR } var children: MutableMap<String, Node> = mutableMapOf() fun getRealParent(): Node { return parent ?: this } fun recalculateSize(): Int { if (type == TYPE.DIR) { size = 0 } size += children.values.sumOf {it.recalculateSize()} return size } fun sumOfNotGreaterThan(value: Int): Int { return (if (size <= value && type == TYPE.DIR) size else 0) + children.values.sumOf { node -> node.sumOfNotGreaterThan(value) } } fun smallestNotLessThan(value: Int): Int { return min( if (size >= value && type == TYPE.DIR) size else Int.MAX_VALUE, children.values.minOfOrNull { node -> node.smallestNotLessThan(value) } ?: Int.MAX_VALUE) } } fun main() { fun createFilesystem(input: List<String>): Node { val root = Node(null, 0, Node.TYPE.DIR) var currentNode = root input.forEach { when { it.startsWith("$ ls") -> {} it.startsWith("$ cd") -> { currentNode = when (val newDir = it.split(" ")[2]) { ".." -> currentNode.getRealParent() "/" -> root else -> currentNode.children[newDir] ?: error("Child not registered") } } else -> { val (typeOrSize, name) = it.split(" ") if (name !in currentNode.children) { currentNode.children[name] = if (typeOrSize == "dir") Node(currentNode, 0, Node.TYPE.DIR) else Node(currentNode, typeOrSize.toInt(), Node.TYPE.FILE) } } } } root.recalculateSize() return root } fun part1(input: List<String>): Int { val root = createFilesystem(input) return root.sumOfNotGreaterThan(100000) } fun part2(input: List<String>): Int { val root = createFilesystem(input) return root.smallestNotLessThan(30000000 - (70000000 - root.size)) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
2,636
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/day12/Day12.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day12 import java.io.File fun parseInput(lines: List<String>): Map<String, List<String>> = lines.flatMap { val (cave1, cave2) = it.split("-") listOf(cave1 to cave2, cave2 to cave1) }.groupBy({ it.first }, { it.second }) private fun String.isCaveSmall(): Boolean = this.first().isLowerCase() fun countDistinctPathsThatVisitSmallCavesAtMostOnce(map: Map<String, List<String>>): Int { fun rec(cave: String, visited: Set<String>): Int = when { cave == "end" -> 1 visited.contains(cave) -> 0 else -> { map[cave]?.sumOf { rec(it, if (cave.isCaveSmall()) visited + cave else visited) } ?: 0 } } return rec("start", setOf()) } fun countDistinctPathsThatVisitSmallCavesAtMostOnceExceptOneRepetition(map: Map<String, List<String>>): Int { fun rec(cave: String, smallCavesVisited: Set<String>, repetitionUsed: Boolean): Int { return when { cave == "end" -> 1 smallCavesVisited.contains(cave) -> if (repetitionUsed || cave == "start") 0 else map[cave]?.sumOf { rec(it, smallCavesVisited, true) } ?: 0 else -> { val next = if (cave.isCaveSmall()) smallCavesVisited + cave else smallCavesVisited map[cave]?.sumOf { rec(it, next, repetitionUsed) } ?: 0 } } } return rec("start", setOf(), false) } fun main() { File("./input/day12.txt").useLines { lines -> val map = parseInput(lines.toList()) println(countDistinctPathsThatVisitSmallCavesAtMostOnce(map)) println(countDistinctPathsThatVisitSmallCavesAtMostOnceExceptOneRepetition(map)) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
1,582
advent-of-code-2021
MIT License
src/day12/Day12.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day12 import java.io.File fun main() { val grid = File("src/day12/input.txt").readLines().mapIndexed { y, line -> line.mapIndexed { x, c -> Pair(x, y) to c } }.flatten().toMap() val start = grid.filter { it.value == 'S' }.map { it.key }.first() val end = grid.filter { it.value == 'E' }.map { it.key }.first() val lowest = grid.filter { height(it.value) == 0 }.map { it.key }.toSet() println(solve(start, setOf(end), grid) { last, next -> next <= last + 1 }) println(solve(end, lowest, grid) { last, next -> next >= last - 1 }) } private fun solve( start: Pair<Int, Int>, end: Set<Pair<Int, Int>>, grid: Map<Pair<Int, Int>, Char>, validTransition: (Int, Int) -> Boolean ): Int { val directions = listOf(Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) val visited = mutableSetOf<Pair<Int, Int>>() val stack = mutableListOf(listOf(start)) while (stack.isNotEmpty()) { val path = stack.removeAt(0) if (path.last() in end) { return (path.size - 1) } if (path.last() in visited) { continue } visited.add(path.last()) val options = directions .asSequence() .map { direction -> Pair(path.last().first + direction.first, path.last().second + direction.second) } .filter { next -> next in grid.keys } .filter { next -> validTransition(height(grid[path.last()]!!), height(grid[next]!!)) } .map { next -> path + next } .toList() stack.addAll(options) } throw IllegalStateException("No solution") } fun height(c: Char): Int { return when (c) { 'S' -> 0 'E' -> 25 else -> c - 'a' } }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
1,777
advent-of-code-2022
MIT License
src/main/kotlin/codes/jakob/aoc/solution/Day03.kt
The-Self-Taught-Software-Engineer
433,875,929
false
{"Kotlin": 56277}
package codes.jakob.aoc.solution object Day03 : Solution() { override fun solvePart1(input: String): Any { val rows: List<List<Int>> = convertToBitString(input) val mostCommonBits: List<Int> = rows.first().indices.map { findMostCommonBit(rows, it) } val leastCommonBits: List<Int> = mostCommonBits.map { it.bitFlip() } val gammaRate: Int = mostCommonBits.binaryToDecimal() val epsilonRate: Int = leastCommonBits.binaryToDecimal() return gammaRate * epsilonRate } override fun solvePart2(input: String): Any { val rows: List<List<Int>> = convertToBitString(input) val oxygenRating: Int = calculateRating(rows, this::findMostCommonBit) val co2ScrubberRating: Int = calculateRating(rows, this::findLeastCommonBit) return oxygenRating * co2ScrubberRating } private fun convertToBitString(input: String): List<List<Int>> { return input .splitMultiline() .map { row -> row.split("").filter { it.isNotBlank() }.map { it.toInt() } } } private fun calculateRating(rows: List<List<Int>>, bitFinder: (List<List<Int>>, Int) -> Int): Int { var matches: List<List<Int>> = rows for (column: Int in rows.first().indices) { val bit: Int = bitFinder(matches, column) matches = matches.filterNot { row -> row[column] != bit } if (matches.count() == 1) break } require(matches.count() == 1) { "Expected exactly one match to be left over" } return matches.first().binaryToDecimal() } private fun findMostCommonBit(rows: List<List<Int>>, column: Int, equallyCommonDefault: Int = 1): Int { val meanBit: Double = rows.sumOf { it[column] } / rows.count().toDouble() return if (meanBit == 0.5) equallyCommonDefault else if (meanBit > 0.5) 1 else 0 } private fun findLeastCommonBit(rows: List<List<Int>>, column: Int, equallyCommonDefault: Int = 0): Int { val meanBit: Double = rows.sumOf { it[column] } / rows.count().toDouble() if (meanBit == 0.5) { return equallyCommonDefault } val mostCommonBit: Int = if (meanBit > 0.5) 1 else 0 return mostCommonBit.bitFlip() } } fun main() { Day03.solve() }
0
Kotlin
0
6
d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c
2,292
advent-of-code-2021
MIT License
src/year2023/day13/Day13.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day13 import check import readInput import splitByEmptyLines fun main() { val testInput = readInput("2023", "Day13_test") check(part1(testInput), 405) check(part2(testInput), 400) val input = readInput("2023", "Day13") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.solution(smudges = 0) private fun part2(input: List<String>) = input.solution(smudges = 1) private fun List<String>.solution(smudges: Int) = splitByEmptyLines().sumOf { pattern -> val col = pattern.reflectionIndex(smudges) val row = pattern.transpose().reflectionIndex(smudges) col + row * 100 } private fun List<String>.transpose(): List<String> { val maxLength = maxOfOrNull { it.length } ?: return emptyList() val transposed = MutableList(maxLength) { "" } for (line in this) { for ((y, c) in line.withIndex()) { transposed[y] = transposed[y] + c } } return transposed } private fun List<String>.reflectionIndex(smudges: Int = 0): Int { val occurrencesByReflectionIndex = flatMap { it.reflectionIndices() }.groupBy { it }.mapValues { it.value.size } return occurrencesByReflectionIndex.entries.find { it.value == size - smudges }?.key ?: 0 } private fun String.reflectionIndices() = (1..lastIndex).mapNotNull { val first = substring(0, it).reversed() val second = substring(it) if (first.startsWith(second) || second.startsWith(first)) it else null }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,495
AdventOfCode
Apache License 2.0
src/Day09.kt
akijowski
574,262,746
false
{"Kotlin": 56887, "Shell": 101}
import kotlin.math.abs import kotlin.math.sign data class Knot(var x: Int, var y: Int) { fun isAboveOrBelow(other: Knot): Boolean { // if more than 1 away in y return (x == other.x) && abs(y - other.y) > 1 } fun isLeftOrRightOf(other: Knot): Boolean { // if more than 1 away in x return (y == other.y) && abs(x - other.x) > 1 } fun isDiagonalOf(other: Knot): Boolean { // if more than 2 away in x + y return abs(x - other.x) + abs(y - other.y) > 2 } } fun Knot.asPair(): Pair<Int, Int> = x to y fun main() { val directions = mapOf( "R" to (1 to 0), "L" to (-1 to 0), "D" to (0 to -1), "U" to (0 to 1) ) fun follow(head: Knot, tail: Knot): Knot { return when { head.isAboveOrBelow(tail) -> tail.copy(y = tail.y + (head.y - tail.y).sign) head.isLeftOrRightOf(tail) -> tail.copy(x = tail.x + (head.x - tail.x).sign) head.isDiagonalOf(tail) -> Knot( tail.x + (head.x - tail.x).sign, tail.y + (head.y - tail.y).sign ) else -> tail } } fun part1(input: List<String>): Int { val h = Knot(0, 0) var t = Knot(0, 0) val tailVisited = mutableSetOf(h.asPair()) input.forEach { val (dir, n) = it.split(" ") val (dx, dy) = directions[dir]!! for (i in 0 until n.toInt()) { h.x += dx h.y += dy t = follow(h, t) tailVisited.add(t.asPair()) } } return tailVisited.size } fun part2(input: List<String>): Int { val h = Knot(0, 0) val ks = MutableList(9) { Knot(0, 0) } val tailVisited = mutableSetOf(h.asPair()) input.forEach { val (dir, n) = it.split(" ") val (dx, dy) = directions[dir]!! for (i in 0 until n.toInt()) { h.x += dx h.y += dy // move tail for (j in ks.indices) { val head = if (j == 0) h else ks[j - 1] val curr = ks[j] follow(head, curr).let { newPos -> ks[j] = newPos } } tailVisited.add(ks.last().asPair()) } } return tailVisited.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 13) val testInput2 = readInput("Day09_test_2") check(part2(testInput2) == 36) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
1
0
84d86a4bbaee40de72243c25b57e8eaf1d88e6d1
2,725
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-12.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2021 import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2021, "12-input") val test1 = readInputLines(2021, "12-test1") val test2 = readInputLines(2021, "12-test2") val test3 = readInputLines(2021, "12-test3") println("Part1:") println(part1(test1)) println(part1(test2)) println(part1(test3)) println(part1(input)) println() println("Part2:") println(part2(test1)) println(part2(test2)) println(part2(test3)) println(part2(input)) } private fun part1(input: List<String>): Int { val graph = CaveGraph(input) return graph.solve(false) } private fun part2(input: List<String>): Int { val graph = CaveGraph(input) return graph.solve(true) } private class CaveGraph(input: List<String>) { private val map = mutableMapOf<Cave, MutableSet<Cave>>() init { input.map { it.split('-') } .forEach { (from, to) -> val cave1 = Cave.parse(from) val cave2 = Cave.parse(to) val set1 = map.getOrElse(cave1) { mutableSetOf() } set1 += cave2 map[cave1] = set1 val set2 = map.getOrElse(cave2) { mutableSetOf() } set2 += cave1 map[cave2] = set2 } } fun solve(allowVisitingSmallTwice: Boolean): Int { var partialPaths = listOf(Path(listOf(Cave.Start), visitedSmallTwice = !allowVisitingSmallTwice)) val finishedPaths = mutableListOf<Path>() while (partialPaths.isNotEmpty()) { val newPaths = mutableListOf<Path>() partialPaths.forEach { partial -> val end = partial.caves.last() val connections = map[end] ?: return@forEach connections.forEach { conn -> when (conn) { Cave.Start -> {} Cave.End -> { finishedPaths += partial.copy(caves = partial.caves + conn) } is Cave.Big -> { newPaths += partial.copy(caves = partial.caves + conn) } is Cave.Small -> { if (conn !in partial.caves) { newPaths += partial.copy(caves = partial.caves + conn) } else if (!partial.visitedSmallTwice) { newPaths += partial.copy(caves = partial.caves + conn, visitedSmallTwice = true) } } } } } partialPaths = newPaths } return finishedPaths.size } private data class Path(val caves: List<Cave>, val visitedSmallTwice: Boolean = false) sealed class Cave { data object Start : Cave() data object End : Cave() data class Big(val name: String) : Cave() data class Small(val name: String) : Cave() companion object { fun parse(name: String) = when { name == "start" -> Start name == "end" -> End name.all { it.isUpperCase() } -> Big(name) else -> Small(name) } } } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,287
advent-of-code
MIT License
src/main/kotlin/adventofcode2023/day5/day5.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day5 import adventofcode2023.readInput import java.util.stream.LongStream import kotlin.time.measureTime fun main() { val input = readInput("day5") println("Day 5") val duration1 = measureTime { println("Puzzle 1: ${puzzle1(input)}") } println(duration1) println("Puzzle 2 started") val duration2 = measureTime { println("Puzzle 2: ${puzzle2dummy(input)}") } println(duration2) println("Puzzle 2 started") val duration2Parallel = measureTime { println("Puzzle 2 Parallel: ${puzzle2dummyParallel(input)}") } println(duration2Parallel) } data class ParsedInput( val seeds: List<Long>, val mappers: List<Mapper>, ) { data class Mapper( val records: List<MapRecord> ) { data class MapRecord( val destinationIndex: Long, val sourceIndex: Long, val range: Int ) } } fun parseInput(input: List<String>): ParsedInput { val seeds = input.first().split(':') .let { (_, numbers) -> numbers.split(' ') .filter { it.isNotEmpty() } .map { it.toLong() } } val mappers: List<ParsedInput.Mapper> = buildList { var records: MutableList<ParsedInput.Mapper.MapRecord> = mutableListOf() input.drop(2).forEach { line -> when { line.isEmpty() -> { add(ParsedInput.Mapper(records)) } line.first().isLetter() -> { records = mutableListOf() } else -> { line.split(' ') .filter { it.isNotEmpty() } .map { it.toLong() } .let { (dI, sI, r) -> ParsedInput.Mapper.MapRecord( destinationIndex = dI, sourceIndex = sI, range = r.toInt() ) }.let { records.add(it) } } } } add(ParsedInput.Mapper(records)) } return ParsedInput(seeds, mappers) } fun ParsedInput.Mapper.map(value: Long): Long { val mapRecord = records.find { value in LongRange(it.sourceIndex, it.sourceIndex + it.range) } return mapRecord?.let { it.destinationIndex + (value - it.sourceIndex) } ?: value } fun puzzle1(input: List<String>): Long { val parsedInput = parseInput(input) return parsedInput.seeds.map { s -> parsedInput.mappers.fold(s) { s, mapper -> mapper.map(s) } }.min() } fun puzzle2dummy(input: List<String>): Long { val parsedInput = parseInput(input) var minimalValue = Long.MAX_VALUE parsedInput.seeds.windowed(size = 2, step = 2).forEach { (s, r) -> (s..(s + r)).forEach { val v = parsedInput.mappers.fold(it) { s, mapper -> mapper.map(s) } if (minimalValue > v) { minimalValue = v } } } return minimalValue } fun puzzle2dummyParallel(input: List<String>): Long { val parsedInput = parseInput(input) return parsedInput.seeds.windowed(size = 2, step = 2) .stream() .parallel() .flatMapToLong { (s, r) -> LongStream.range(s, s + r) } .map { parsedInput.mappers.fold(it) { s, mapper -> mapper.map(s) } } .min() .asLong }
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
3,472
adventofcode2023
MIT License
src/main/kotlin/day15/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day15 import util.readTestInput import kotlin.math.abs import kotlin.math.max private data class Coord(val x: Int, val y: Int) { fun distanceTo(coord: Coord) = abs(x - coord.x) + abs(y - coord.y) } private data class Sensor(val sensorCoord: Coord, val beaconCoord: Coord) { val range = sensorCoord.distanceTo(beaconCoord) fun rangeAt(y: Int) = max(0, range - abs(sensorCoord.y - y)) fun isInRange(y: Int) = range >= abs(sensorCoord.y - y) fun minXAtY(y: Int) = sensorCoord.x - rangeAt(y) fun maxXAtY(y: Int) = sensorCoord.x + rangeAt(y) } private fun limit(num: Int, min: Int, max: Int): Int { return when { num < min -> min num > max -> max else -> num } } // 1-3 a: abcde private val regex = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") private fun parseSensor(line: String): Sensor = regex.matchEntire(line)!! .destructured .let { (sensorX, sensorY, beaconX, beaconY) -> Sensor(Coord(sensorX.toInt(), sensorY.toInt()), Coord(beaconX.toInt(), beaconY.toInt())) } fun part1(inputLines: List<String>, y: Int): Int { val sensors = inputLines.map { parseSensor(it) } val beaconXCoordsAtY = sensors.filter { it.beaconCoord.y == y }.map { it.beaconCoord.x }.toSet() val coveredXCoords = sensors.fold(mutableSetOf<Int>()) { acc, sensor -> if (sensor.isInRange(y)) { acc.addAll(sensor.minXAtY(y) .. sensor.maxXAtY(y)) } acc } return coveredXCoords.filter { !beaconXCoordsAtY.contains(it) }.size } private fun findCoveredXRanges(y: Int, sensors: List<Sensor>, maxXAndY: Int): Set<IntRange> = sensors.fold(mutableSetOf()) { acc, sensor -> if (sensor.isInRange(y)) { val minX = limit(sensor.minXAtY(y), 0, maxXAndY) val maxX = limit(sensor.maxXAtY(y), 0, maxXAndY) acc.add(IntRange(minX, maxX)) } acc } fun merge(range1: IntRange, range2: IntRange): IntRange? { return when { range1.first >= range2.first && range1.last <= range2.last -> range2 // ...2...1...1...2.. range2.first >= range1.first && range2.last <= range1.last -> range1 // ...1...2...2...1.. range1.first < range2.first && range1.last >= range2.first -> IntRange(range1.first, max(range1.last, range2.last)) // ...1...2...1...2.. range2.first < range1.first && range2.last >= range1.first -> IntRange(range2.first, max(range1.last, range2.last)) // ...2...1...2...1.. else -> null // range1 is fully before or fully after range2 } } fun part2(inputLines: List<String>, maxXAndY: Int): ULong { val sensors = inputLines.map { parseSensor(it) } fun findUncoveredCoord(): Coord? { for (currentY in 0 until maxXAndY) { val coveredRanges = findCoveredXRanges(currentY, sensors, maxXAndY).sortedBy { it.first } var currentRange = coveredRanges.first() for (range in coveredRanges) { val mergedRange = merge(currentRange, range) // merge returns null when ranges are not overlapping, which means we have found the gap if (mergedRange == null) { return Coord(currentRange.last + 1, currentY) } currentRange = mergedRange } } return null } val distressBeaconCoord = findUncoveredCoord() return distressBeaconCoord!!.x.toULong() * 4000000.toULong() + distressBeaconCoord.y.toULong() } fun main() { val inputLines = readTestInput("day15") println(part1(inputLines, 10)) println(part2(inputLines, 4000000)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
3,691
advent-of-code-2022
MIT License
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/problems/DynamicProgramming.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.problems import kotlin.math.max /** * Some problem solved using dynamic programming or Advance DS */ /** * Return longest comming subsequence possible between 2 strings */ fun longestCommonSubsequence(str1: String, str2: String): String { // 1. Prepare a DP table with m+1, n+1 // 2. Compare 2 char, if equal take diagonal + 1, else take max of left, top value // if (a[i] == b[j]) dp[i-1][j-1] + 1 else max(dp[i-1][j],dp[i][j-1] val dp = Array(str1.length + 1) { Array(str2.length + 1) { 0 } } for (i in 1 until dp.size) { for (j in 1 until dp[i].size) { dp[i][j] = if (str1[i - 1] == str2[j - 1]) { dp[i - 1][j - 1] + 1 } else { max(dp[i - 1][j], dp[i][j - 1]) } } } // Getting strings from the db table var output = "" var i = str1.length var j = str2.length while (i > 0 && j > 0) { if (dp[i][j] == dp[i - 1][j]) { i-- } else { output = str1[i - 1] + output i-- j-- } } return output } /** * Calculate number of edits require to change fromString to toString. insert, remove, replace */ fun editDistance(fromString: String, toString: String): Int { //if (dp[i] == dp[j]) dp[i-1][j-1] else min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 val dp = Array(fromString.length + 1) { i -> Array(toString.length + 1) { j -> if (i == 0) j else if (j == 0) i else 0 } } for (i in 1 until dp.size) { for (j in 1 until dp[i].size) { dp[i][j] = if (fromString[i - 1] == toString[j - 1]) { dp[i - 1][j - 1] } else { minOf(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1 } } } return dp.lastOrNull()?.lastOrNull() ?: 0 } fun longestIncreasingSubsequence(list: List<Int>): Int { val dp = Array(list.size) { 0 } dp[0] = 1 fun findElementWithLowerValue(index: Int): Int { var i = index - 1 var maxValue = 0 while (i > 0) { if (list[i] < list[index]) { maxValue = max(maxValue, dp[i]) } i-- } println("maxValue $maxValue") return maxValue } for (i in 1 until dp.size) { dp[i] = if (list[i - 1] < list[i]) { dp[i - 1] + 1 } else { findElementWithLowerValue(i) + 1 } } println("dp ${dp.joinToString { it.toString() }}") return dp.lastOrNull() ?: 0 }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
2,595
kotlin-ds-algo
MIT License
2020/src/year2021/day08/code.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2021.day08 import util.readAllLines fun main() { part1() part2() } val DIGITS = mutableMapOf<Int, String>().apply { put(1, "cf") put(4, "bcdf") put(7, "acf") put(8, "abcdefg") put(2, "acdeg") // common with 1: c, 4: cd, 7: ac put(3, "acdfg") // common with 1: cf, 4: cdf, 7: acf put(5, "abdfg") // common with 1: f, 4: bdf, 7: af put(0, "abcefg") // common with 1: cf, 4: bcf, 7: acf put(6, "abdefg") // common with 1: f, 4: bdf, 7: af put(9, "abcdfg") // common with 1: cf, 4: bcdf, 7: acf } private fun part1() { val outputs = mutableListOf<List<Set<Char>>>() readAllLines("input.txt").map { line -> val (wire, digits) = line.split(" | ") .map { part -> part.split(" ").map { word -> word.toSortedSet() } } outputs.add(digits) } val num = outputs.sumOf { digits -> digits.count { digit -> lengthMatches(digit, 1) || lengthMatches(digit, 4) || lengthMatches(digit, 7) || lengthMatches(digit, 8) } } println(num) } private fun part2() { val unique = setOf(1, 4, 7, 8) val sum = readAllLines("input.txt").sumOf { line -> val (wire, digits) = line.split(" | ") .map { part -> part.split(" ").map { word -> word.toSortedSet() } } val mapDigitStringToNumber = mutableMapOf<Set<Char>, Int>() val mapNumberToDigitString = mutableMapOf<Int, Set<Char>>() val matchUnique = { digit: Set<Char> -> unique.firstOrNull { lengthMatches(digit, it) } } val mapUniqueStrings = { digit: Set<Char> -> val match = matchUnique(digit) when { match == null -> false mapDigitStringToNumber.contains(digit) -> true else -> { mapDigitStringToNumber[digit] = match mapNumberToDigitString[match] = digit true } } } val all = wire + digits val ambiguousDigits = mutableListOf<Set<Char>>() all.forEach { if (!mapUniqueStrings(it)) { ambiguousDigits.add(it) } } for (digit in ambiguousDigits) { val digitLength = digit.size val common = unique.map { digit.intersect(mapNumberToDigitString[it]!!) } val numInCommonWith1 = common[0].size val numInCommonWith4 = common[1].size val number = when { numInCommonWith1 == 1 && digitLength == 6 -> 6 numInCommonWith1 == 1 && numInCommonWith4 == 2 && digitLength == 5 -> 2 numInCommonWith1 == 1 && numInCommonWith4 == 3 && digitLength == 5 -> 5 numInCommonWith1 == 2 && digitLength == 5 -> 3 numInCommonWith1 == 2 && numInCommonWith4 == 3 && digitLength == 6 -> 0 numInCommonWith1 == 2 && numInCommonWith4 == 4 && digitLength == 6 -> 9 else -> error("Unknown number") } mapDigitStringToNumber[digit] = number mapNumberToDigitString[number] = digit if (mapNumberToDigitString.size == 10) { break } } digits.map { mapDigitStringToNumber[it]!! }.joinToString("").toInt() } println(sum) } private fun lengthMatches(value: Set<Char>, testValue: Int) = value.size == DIGITS[testValue]!!.length
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
3,485
adventofcode
MIT License
src/Day25.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun globalMinCut(mat: Array<IntArray>): Pair<Int, List<Int>> { var best = Int.MAX_VALUE to emptyList<Int>() val n = mat.size val co = Array(n) { mutableListOf(it) } for (ph in 1 until n) { val w = mat[0].copyOf() var (s, t) = 0 to 0 for (it in 0 until n - ph) { w[t] = Int.MIN_VALUE s = t t = w.indices.maxBy { w[it] } for (i in 0 until n) w[i] += mat[t][i] } if (best.first > w[t] - mat[t][t]) { best = w[t] - mat[t][t] to co[t] } co[s].addAll(co[t]) for (i in 0 until n) mat[s][i] += mat[t][i] for (i in 0 until n) mat[i][s] = mat[s][i] mat[0][t] = Int.MIN_VALUE } return best } fun main() { fun read(file: String) = readInput(file).associate { line -> val from = line.substringBefore(':') val to = line.substringAfter(": ").split(" ") /*for (t in to) { println("$from --> $t{$t}") }*/ from to to.toMutableSet() }.toMutableMap().also { graph -> for ((v1,edges) in graph.entries.toList()) { for (v2 in edges) { graph.getOrPut(v2) { mutableSetOf() }.add(v1) } } } fun solve1(file: String): Int { val graph = read(file) val names = (graph.keys + graph.values.flatten()).toSet().withIndex().associate { it.index to it.value } val n = names.size val mat = Array(n) { i -> IntArray(n) { j -> if (graph[names[i]!!]?.contains(names[j]!!) == true || graph[names[j]!!]?.contains(names[i]!!) == true) 1 else 0 } } val (cost, cut) = globalMinCut(mat) assert(cost == 3) return cut.size * (names.size - cut.size) } assert(solve1("Day25t") == 54) println(solve1("Day25")) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,902
advent-of-code-kotlin
Apache License 2.0
src/Day03.kt
paul-matthews
433,857,586
false
{"Kotlin": 18652}
fun String.binToDec() = Integer.parseInt(this, 2) fun Pair<String, String>.total() = first.binToDec() * second.binToDec() typealias PowerConsumption = Pair</* Gamma rate */ String, /* Epsilon Rate */ String> typealias LifeSupportRating = Pair</* Oxygen Generator */ String, /* C02 Scrubber */ String> /** * Partition a list of binary strings based on char position */ fun List<String>.partitionBinary(charPos: Int): Pair<List<String>, List<String>> = groupBy { it[charPos] }.let { Pair(it['0'] ?: emptyList(), it['1'] ?: emptyList()) } /** * Reduce a list of binary strings by frequency, either by most frequent or least frequent */ fun List<String>.reduceBinaryByFrequency(mostFrequent: Boolean = true, charPos: Int = 0): String { val f = first() if (size == 1 || charPos > f.length) { return f } val (grp0, grp1) = partitionBinary(charPos) return if ((grp0.size > grp1.size) xor !mostFrequent) { grp0.reduceBinaryByFrequency(mostFrequent, charPos + 1) } else { grp1.reduceBinaryByFrequency(mostFrequent, charPos + 1) } } fun main() { fun part1(input: List<String>): Int = input.first().foldIndexed(PowerConsumption("", "")) {index, acc, _ -> input.partitionBinary(index).let{ (grp0, grp1) -> val firstAddition = if (grp0.size > grp1.size) "1" else "0" val secondAddition = if (grp0.size > grp1.size) "0" else "1" PowerConsumption(acc.first + firstAddition, acc.second + secondAddition) } }.total() fun part2(input: List<String>) = LifeSupportRating( input.reduceBinaryByFrequency(true), input.reduceBinaryByFrequency(false) ).total() // test if implementation meets criteria from the description, like: val testInput = readFileContents("Day03_test") val part1Result = part1(testInput) check(part1Result == 198) { "Expected: 198 but found $part1Result" } val part2Result = part2(testInput) check(part2Result == 230) { "Expected 230 but is: $part2Result" } val input = readFileContents("Day03") println("Part1: " + part1(input)) println("Part2: " + part2(input)) }
0
Kotlin
0
0
2f90856b9b03294bc279db81c00b4801cce08e0e
2,223
advent-of-code-kotlin-template
Apache License 2.0
app/src/main/kotlin/codes/jakob/aoc/solution/Day09.kt
loehnertz
725,944,961
false
{"Kotlin": 59236}
package codes.jakob.aoc.solution import codes.jakob.aoc.shared.splitByLines import codes.jakob.aoc.shared.splitBySpace object Day09 : Solution() { override fun solvePart1(input: String): Any { return parseHistories(input) .map { HistoryTree.resolveFromHistory(it) } .map { it.resolveNextValues() } .sumOf { it.firstLastValue() } } override fun solvePart2(input: String): Any { return parseHistories(input) .map { HistoryTree.resolveFromHistory(it) } .map { it.resolvePreviousValues() } .sumOf { it.firstFirstValue() } } private fun parseHistories(input: String): List<History> { return input .splitByLines() .map { line -> line.splitBySpace() } .map { numbers -> History(numbers.map { it.toLong() }) } } @JvmInline private value class History(val values: List<Long>) { fun addLast(number: Long): History { return History(values + listOf(number)) } fun addFirst(number: Long): History { return History(listOf(number) + values) } fun combine(): History { return History(values.zipWithNext { a, b -> b - a }) } } @JvmInline private value class HistoryTree(val tree: List<History>) { init { require(tree.isNotEmpty()) { "Tree must not be empty" } require(tree.last().allZeroes()) { "Last element of tree must be all zeroes" } } fun resolveNextValues(): HistoryTree { return tree.foldRightIndexed(listOf<History>()) { index, currentHistory, newTree -> if (index == tree.lastIndex) { val newHistory: History = currentHistory.addLast(0) listOf(newHistory) } else { val previousHistory: History = newTree.first() val newLastNumberCurrent: Long = currentHistory.values.last() + previousHistory.values.last() val newHistory: History = currentHistory.addLast(newLastNumberCurrent) listOf(newHistory) + newTree } }.let { HistoryTree(it) } } fun resolvePreviousValues(): HistoryTree { return tree.foldRightIndexed(listOf<History>()) { index, currentHistory, newTree -> if (index == tree.lastIndex) { val newHistory: History = currentHistory.addFirst(0) listOf(newHistory) } else { val previousHistory: History = newTree.first() val newFirstNumberCurrent: Long = currentHistory.values.first() - previousHistory.values.first() val newHistory: History = currentHistory.addFirst(newFirstNumberCurrent) listOf(newHistory) + newTree } }.let { HistoryTree(it) } } companion object { fun resolveFromHistory(history: History): HistoryTree { tailrec fun resolve(history: History, previous: List<History>): HistoryTree { if (history.allZeroes()) return HistoryTree(previous) val newHistory: History = history.combine() return resolve(newHistory, previous + newHistory) } return resolve(history, listOf(history)) } } } private fun History.allZeroes(): Boolean = values.all { it == 0L } private fun HistoryTree.firstLastValue(): Long = tree.first().values.last() private fun HistoryTree.firstFirstValue(): Long = tree.first().values.first() } fun main() = Day09.solve()
0
Kotlin
0
0
6f2bd7bdfc9719fda6432dd172bc53dce049730a
3,740
advent-of-code-2023
MIT License
src/Day09.kt
wujingwe
574,096,169
false
null
import kotlin.math.sign object Day09 { private val ADJACENTS = listOf( 0 to 0, -1 to 0, 1 to 0, 0 to -1, 0 to 1, -1 to -1, -1 to 1, 1 to -1, 1 to 1 ) private val STEPS = mapOf( "U" to (-1 to 0), "D" to (1 to 0), "R" to (0 to 1), "L" to (0 to -1) ) private fun traverse(inputs: List<String>, knotsCount: Int): Int { val knots = mutableListOf(0 to 0) // head repeat(knotsCount) { knots.add(0 to 0) // knots } return inputs.map { s -> val (dir, count) = s.split(" ") dir to count.toInt() }.flatMap { (dir, count) -> generateSequence { dir }.take(count).map { val (sx, sy) = STEPS.getValue(dir) knots[0] = knots[0].first + sx to knots[0].second + sy for (i in 0 until knots.size - 1) { val begin = knots[i] val end = knots[i + 1] val adjacent = ADJACENTS.any { (dx, dy) -> end == (begin.first + dx to begin.second + dy) } if (!adjacent) { val dx = begin.first - end.first val dy = begin.second - end.second val nx = if (dx > 0) 1 else -1 val ny = if (dy > 0) 1 else -1 knots[i + 1] = if (begin.second == end.second) { // same column end.first + nx to end.second } else if (begin.first == end.first) { // same row end.first to end.second + ny } else { end.first + nx to end.second + ny } } } knots[knotsCount] } }.toSet().size } fun part1(inputs: List<String>): Int { return traverse(inputs, 1) } fun part2(inputs: List<String>): Int { return traverse(inputs, 9) } } fun main() { fun part1(inputs: List<String>): Int { return Day09.part1(inputs) } fun part2(inputs: List<String>): Int { return Day09.part2(inputs) } val testInput = readInput("../data/Day09_test") check(part1(testInput) == 88) check(part2(testInput) == 36) val input = readInput("../data/Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a5777a67d234e33dde43589602dc248bc6411aee
2,495
advent-of-code-kotlin-2022
Apache License 2.0
src/Day12.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
data class Graph( val nodes: MutableList<Pair<Int, Int>>, var endNode: Pair<Int, Int>, var startNode: Pair<Int, Int>, val heights: MutableList<MutableList<Int>>, val distances: MutableList<MutableList<Int>>, val predecessors: MutableList<MutableList<Pair<Int, Int>?>>, ) fun charToHeight(item: Char): Int { return when (item) { 'a' -> 1 'b' -> 2 'c' -> 3 'd' -> 4 'e' -> 5 'f' -> 6 'g' -> 7 'h' -> 8 'i' -> 9 'j' -> 10 'k' -> 11 'l' -> 12 'm' -> 13 'n' -> 14 'o' -> 15 'p' -> 16 'q' -> 17 'r' -> 18 's' -> 19 't' -> 20 'u' -> 21 'v' -> 22 'w' -> 23 'x' -> 24 'y' -> 25 'z' -> 26 'E' -> 26 'S' -> 1 else -> throw IllegalArgumentException() } } fun createGraph(input: List<String>): Graph { val graph = Graph( mutableListOf(), 0 to 0, 0 to 0, MutableList(input.size) { mutableListOf() }, MutableList(input.size) { mutableListOf() }, MutableList(input.size) { mutableListOf() }, ) repeat(input.size) { i -> val chars = input[i].toCharArray() chars.forEachIndexed { j, chr -> graph.nodes.add(i to j) graph.heights[i].add(charToHeight(chr)) graph.distances[i].add( if (chr == 'S') { graph.startNode = i to j 0 } else Int.MAX_VALUE ) graph.predecessors[i].add(null) if (chr == 'E') { graph.endNode = i to j } } } return graph } fun shortestPaths(graph: Graph, constraint: (height: Int, neighbourHeight: Int) -> Boolean) { while (graph.nodes.isNotEmpty()) { val node = graph.nodes.minBy { (i, j) -> graph.distances[i][j] } graph.nodes.remove(node) val (i, j) = node val currentHeight = graph.heights[i][j] val neighbourNodes = setOfNotNull( graph.nodes.firstOrNull { it == i + 1 to j }, graph.nodes.firstOrNull { it == i - 1 to j }, graph.nodes.firstOrNull { it == i to j + 1 }, graph.nodes.firstOrNull { it == i to j - 1 }, ) neighbourNodes.forEach { (x, y) -> if (constraint( currentHeight, graph.heights[x][y] ) && graph.distances[i][j] + 1 < graph.distances[x][y] ) { graph.distances[x][y] = graph.distances[i][j] + 1 graph.predecessors[x][y] = i to j } } } } fun shortestPathTo(node: Pair<Int, Int>, graph: Graph): List<Pair<Int, Int>> { var currentNode: Pair<Int, Int>? = node val path = mutableListOf<Pair<Int, Int>>() while (currentNode != null) { path.add(currentNode) val (i, j) = currentNode currentNode = graph.predecessors.getOrNull(i)?.getOrNull(j) } return path } fun main() { fun part1(input: List<String>): Int { val graph = createGraph(input) shortestPaths(graph) { height, neighbourHeight -> neighbourHeight - height <= 1 } return shortestPathTo(graph.endNode, graph).size - 1 } fun part2(input: List<String>): Int { val graph = createGraph(input) graph.startNode.let { (i, j) -> graph.distances[i][j] = Int.MAX_VALUE } graph.endNode.let { (i, j) -> graph.distances[i][j] = 0 } shortestPaths(graph) { height, neighbourHeight -> neighbourHeight - height >= -1 } val paths = mutableListOf<List<Pair<Int, Int>>>() graph.heights.forEachIndexed { i, heights -> heights.forEachIndexed { j, height -> if (height == 1) paths.add(shortestPathTo(i to j, graph)) } } return paths.filter { it.last() == graph.endNode }.minOf { it.size - 1 } } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
4,186
advent-of-code-2022
Apache License 2.0