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/day02/Day02.kt
voom
573,037,586
false
{"Kotlin": 12156}
package day02 import day02.Move.* import day02.RoundResult.* import readInput /** * --- Day 2: Rock Paper Scissors --- */ fun main() { val choiceScore = mapOf( ROCK to 1, PAPER to 2, SCISSORS to 3 ) fun calcRoundScore(pair: Pair<Move, Move>): Int { val comparator = ResultComparator() val result: RoundResult = when (comparator.compare(pair.first, pair.second)) { -1 -> LOST 0 -> DRAW 1 -> WIN else -> throw IllegalArgumentException("Unknown result") } return result.score + choiceScore[pair.second]!! } fun parseMove(code: String): Move { return when (code) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSORS else -> throw IllegalArgumentException("Unknown code $code") } } /* The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). */ fun part1(input: List<String>): Int = input .map { val (o1, o2) = it.split(" ") Pair(parseMove(o1), parseMove(o2)) } .sumOf { calcRoundScore(it) } fun parseExpectedResult(o2: String): RoundResult { return when (o2) { "X" -> LOST "Y" -> DRAW "Z" -> WIN else -> throw IllegalArgumentException("Unknown code $o2") } } fun predictMove(move: Move, expectedResult: RoundResult): Move { val comparator = ResultComparator() return when (expectedResult) { LOST -> Move.values().single { comparator.compare(move, it) == -1 } DRAW -> Move.values().single { comparator.compare(move, it) == 0 } WIN -> Move.values().single { comparator.compare(move, it) == 1 } } } /* Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. */ fun part2(input: List<String>): Int = input .map { val (o1, o2) = it.split(" ") Pair(parseMove(o1), predictMove(parseMove(o1), parseExpectedResult(o2))) } .sumOf { calcRoundScore(it) } // test if implementation meets criteria from the description, like: val testInput = readInput("day02/test_input") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("day02/input") println(part1(input)) println(part2(input)) // An alternative way to solve the puzzles in a very short way val parsed = input .map { it.split(" ").map(String::first) } .map { (him, me) -> (him - 'A') to (me - 'X') } println(parsed.sumOf { (him, me) -> ((me + 4 - him) % 3) * 3 + me + 1 }) println(parsed.sumOf { (him, me) -> (me + 2 + him) % 3 + 1 + me * 3 }) } enum class RoundResult(val score: Int) { LOST(0), DRAW(3), WIN(6) } enum class Move { ROCK, PAPER, SCISSORS } class ResultComparator : Comparator<Move> { override fun compare(op: Move, my: Move): Int { return when { op == my -> 0 (op == ROCK && my == PAPER) || (op == PAPER && my == SCISSORS) || (op == SCISSORS && my == ROCK) -> 1 else -> -1 } } }
0
Kotlin
0
1
a8eb7f7b881d6643116ab8a29177d738d6946a75
3,796
aoc2022
Apache License 2.0
src/aoc2022/Day12.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* import utils.Coord.Companion.get import java.util.* private class Day12(val lines: List<String>) { private fun parseInput(filter: (Node, Node) -> Boolean): List<Node> { val nodes = lines.map { it.toList() }.mapIndexed { r, row -> row.mapIndexed { c, value -> Node(r, c, value) } } nodes.forEach { row -> row.forEach { node -> node.edges.addAll(node.loc.neighborsBounded(row.size, nodes.size, "+") .map { neighbor -> nodes[neighbor] } .filter { neighbor -> filter(node, neighbor) } ) } } return nodes.flatten() } fun part1(): Any? { val nodes = parseInput { node, neighbor -> neighbor.height() - 1 <= node.height() } val pq = PriorityQueue<Pair<Node, Int>>(compareBy { it.second }) val distances = mutableMapOf<Node, Int>() pq.add(nodes.first { it.value == 'S' } to 0) while (pq.isNotEmpty()) { val (node, dist) = pq.poll() if (distances.getOrDefault(node, Int.MAX_VALUE) <= dist) { continue } distances[node] = dist if (node.value == 'E') { return dist } pq.addAll(node.edges.map { it to dist + 1 }) } return null } fun part2(): Any? { val nodes = parseInput { neighbor, node -> neighbor.height() - 1 <= node.height() } val pq = PriorityQueue<Pair<Node, Int>>(compareBy { it.second }) val distances = mutableMapOf<Node, Int>() pq.add(nodes.first { it.value == 'E' } to 0) while (pq.isNotEmpty()) { val (node, dist) = pq.poll() if (distances.getOrDefault(node, Int.MAX_VALUE) <= dist) { continue } distances[node] = dist if (node.height() == 'a'.code) { return dist } pq.addAll(node.edges.map { it to dist + 1 }) } return null } } data class Node(val r: Int, val c: Int, val value: Char) { val loc = Coord.rc(r, c) val edges = mutableListOf<Node>() fun height(): Int { return when (value) { 'S' -> 'a'.code 'E' -> 'z'.code else -> value.code } } } fun main() { val day = "12".toInt() val todayTest = Day12(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 31) val today = Day12(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1", 380) execute(todayTest::part2, "Day[Test] $day: pt 2", 29) execute(today::part2, "Day $day: pt 2", 375) }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
2,447
aoc2022
Apache License 2.0
src/day/_12/Day12.kt
Tchorzyksen37
572,924,533
false
{"Kotlin": 42709}
package day._12 import readInput class Day12(private val nodes: List<List<Node>>) { private val bounds = Bounds(nodes.first().indices, nodes.indices) private val end = findNode { it.state == State.END } fun findShortestPath(isDestination: (Node) -> Boolean): Int { val frontier: ArrayDeque<Step> = ArrayDeque(listOf(Step(end, 0))) val reached = mutableSetOf(end) while (frontier.isNotEmpty()) { val current = frontier.removeFirst() if (isDestination(current.node)) return current.distance current.node.coordinates.adjacent .filter { bounds.contains(it) } .map { nodes[it] } .filter { current.node.height - 1 <= it.height } .filter { it !in reached } .forEach { frontier.add(current nextStep it) reached.add(it) } } throw IllegalStateException("Could not find a path that meets the criteria.") } private fun findNode(predicate: (Node) -> Boolean): Node = nodes.flatten().first(predicate) private operator fun <T> List<List<T>>.get(coordinates: Coordinates) = this[coordinates.y][coordinates.x] private class Bounds(private val eastWestBounds: IntRange, private val northSouthBounds: IntRange) { operator fun contains(coordinates: Coordinates): Boolean = coordinates.x in eastWestBounds && coordinates.y in northSouthBounds } companion object { fun parse(input: List<String>): List<List<Node>> = input.mapIndexed { index, s -> s.mapIndexed { strIndex, char -> Node.from(Coordinates(strIndex, index), char) } } } } data class Step(val node: Node, val distance: Int) { infix fun nextStep(node: Node) = Step(node, distance + 1) } data class Coordinates(val x: Int, val y: Int) { val adjacent: List<Coordinates> by lazy { listOf(Coordinates(x - 1, y), Coordinates(x + 1, y), Coordinates(x, y - 1), Coordinates(x, y + 1)) } } data class Node(val coordinates: Coordinates, val height: Int, val state: State) { companion object { fun from(coordinates: Coordinates, char: Char): Node { val height = when (char) { 'S' -> 0; 'E' -> 'z' - 'a'; else -> char - 'a' } return Node(coordinates, height, State.from(char)) } } } enum class State { START, INTERMEDIATE, END; companion object { fun from(char: Char): State = when (char) { 'S' -> START;'E' -> END;else -> INTERMEDIATE } } } fun main() { val testNodes = Day12.parse(readInput("day/_12/Day12_test")) check(Day12(testNodes).findShortestPath { it.state == State.START } == 31) check(Day12(testNodes).findShortestPath { it.height == 0 } == 29) val nodes = Day12.parse(readInput("day/_12/Day12")) println(Day12(nodes).findShortestPath { it.state == State.START }) println(Day12(nodes).findShortestPath { it.height == 0 }) }
0
Kotlin
0
0
27d4f1a6efee1c79d8ae601872cd3fa91145a3bd
2,708
advent-of-code-2022
Apache License 2.0
src/Day07.kt
jorgecastrejon
573,097,701
false
{"Kotlin": 33669}
fun main() { fun part1(input: List<String>): Long { val (_, dirs) = generateTree(root = TreeItem.Dir("/"), input) return dirs.filter { it.size <= 100000L }.sumOf(TreeItem.Dir::size) } fun part2(input: List<String>): Long { val (root, dirs) = generateTree(root = TreeItem.Dir("/"), input) val toBeDelete = 30000000L - (70000000 - root.size) return dirs.filter { it.size >= toBeDelete }.minBy(TreeItem.Dir::size).size } val input = readInput("Day07") println(part1(input)) println(part2(input)) } private fun generateTree(root: TreeItem.Dir, input: List<String>): Pair<TreeItem.Dir, List<TreeItem.Dir>> { val dirs = mutableListOf<TreeItem.Dir>() input.fold(root) { tree, string -> when { string == "\$ cd /" -> root string == "\$ cd .." -> tree.parent!! string.startsWith("\$ cd") -> { tree.items.filterIsInstance<TreeItem.Dir>() .find { it.name == string.split(" ").last() }!! } string == "\$ ls" -> tree string.startsWith("dir") -> { val name = string.split(" ").last() val dir = TreeItem.Dir(name = name, parent = tree) tree.items.add(dir) dirs.add(dir) tree } else -> { val size = string.split(" ").first().toLong() val name = string.split(" ").last() val dir = TreeItem.File(name = name, parent = tree, size = size) tree.items.add(dir) tree } } } return root to dirs } private sealed class TreeItem { abstract val size: Long data class Dir( val name: String, val items: MutableList<TreeItem> = mutableListOf(), val parent: Dir? = null ) : TreeItem() { override val size: Long get() = items.sumOf { it.size } } data class File( val name: String, override val size: Long, val parent: Dir? = null ) : TreeItem() }
0
Kotlin
0
0
d83b6cea997bd18956141fa10e9188a82c138035
2,112
aoc-2022
Apache License 2.0
src/main/kotlin/Day08.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
fun main() { data class Tree( val height: Int, var n: Tree? = null, var e: Tree? = null, var s: Tree? = null, var w: Tree? = null ) fun buildForest(map: List<String>) = map .map { it .toCharArray() .map(Char::digitToInt) .map(::Tree) } .map { generateSequence( it.reduce { w, e -> w.e = e e.w = w e }, Tree::w ).toList() } .reduce { nRow, sRow -> nRow.zip(sRow) { n, s -> n.s = s s.n = n s } } .first() .let { tree -> generateSequence(tree, Tree::e) + generateSequence(tree.w, Tree::w) } .flatMap { tree -> generateSequence(tree, Tree::n) + generateSequence(tree.s, Tree::s) } fun part1(input: List<String>) = buildForest(input) .filter { tree -> listOf( generateSequence(tree.n, Tree::n), generateSequence(tree.e, Tree::e), generateSequence(tree.s, Tree::s), generateSequence(tree.w, Tree::w) ).any { it.all { it.height < tree.height } } } .count() fun part2(input: List<String>) = buildForest(input) .map { tree -> listOf( generateSequence(tree.n, Tree::n) + Tree(Int.MAX_VALUE), generateSequence(tree.e, Tree::e) + Tree(Int.MAX_VALUE), generateSequence(tree.s, Tree::s) + Tree(Int.MAX_VALUE), generateSequence(tree.w, Tree::w) + Tree(Int.MAX_VALUE) ).map { val i = it.indexOfFirst { it.height >= tree.height } when { it.count() == 0 -> 0 i == it.count() - 1 -> i else -> i + 1 } }.reduce(Int::times) } .max() val testInput = readStrings("Day08_test") check(part1(testInput) == 21) val input = readStrings("Day08") println(part1(input)) check(part2(testInput) == 8) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
2,302
aoc-2022
Apache License 2.0
src/Day07.kt
bigtlb
573,081,626
false
{"Kotlin": 38940}
fun main() { open class File(val name: String, open val size: Long) class Dir(name: String, val parent: Dir? = null, val files: MutableList<File> = mutableListOf()) : File(name, 0) { val head: Dir get() = parent?.head ?: this override val size: Long get() = files.sumOf(File::size) operator fun get(name: String): Dir? = files.firstOrNull { it.name == name && it is Dir } as Dir fun asList(): List<File> = files.flatMap { if (it is Dir) it.asList() else listOf(it) } + this } fun parseTree(input: List<String>): Dir = input.fold(null as Dir?) { acc, cur -> val tokens = cur.split(' ') when { // Parse commands tokens[0] == "$" -> when (tokens[1]) { // change directory, move accumulator "cd" -> when (tokens[2]) { ".." -> acc?.parent else -> acc?.let { acc[tokens[2]] ?: acc.run { files.add(Dir(tokens[2], acc)) acc[tokens[2]] } } ?: Dir(tokens[2]) } else -> acc } else -> { when { tokens[0] == "dir" -> acc?.apply { files.add(Dir(tokens[1], acc)) } else -> acc?.apply { files.add(File(tokens[1], tokens[0].toLong())) } } acc } } }?.head ?: Dir("Not Found") fun part1(input: List<String>): Long = parseTree(input).asList().sumOf { if (it is Dir && it.size <= 100_000) it.size else 0L } ?: 0L fun part2(input: List<String>): Long = parseTree(input).run{ val need = 30_000_000 - (70_000_000 - size) asList().filterIsInstance<Dir>().sortedBy { it.size }.first { it.size > need }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8f76d3c75a30ae00c563c997ed2fb54827ea94a
2,454
aoc-2022-demo
Apache License 2.0
src/main/kotlin/com/ryanmoelter/advent/day08/Tree.kt
ryanmoelter
573,615,605
false
{"Kotlin": 84397}
package com.ryanmoelter.advent.day08 typealias Grid<T> = List<List<T>> fun main() { println(findMostScenicTree(treeData)) } fun findMostScenicTree(input: String): Int { val grid = input.parseGrid() val spaceGrid = grid.spaceRight() times grid.spaceLeft() times grid.spaceUp() times grid.spaceDown() return spaceGrid.maxOf { row -> row.max() } } private infix fun Grid<Int>.times(other: Grid<Int>): Grid<Int> = mapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, space -> space * other[rowIndex][columnIndex] } } fun Grid<Int>.spaceRight(): Grid<Int> = map { it.spaceToRight() } fun Grid<Int>.spaceLeft(): Grid<Int> = map { it.reversed() } .spaceRight() .map { it.reversed() } private fun Grid<Int>.spaceDown(): Grid<Int> = columns() .spaceRight() .columns() private fun Grid<Int>.spaceUp(): Grid<Int> = reversed() .columns() .spaceRight() .columns() .reversed() // Look right fun List<Int>.spaceToRight(): List<Int> = mapIndexed { index, height -> var workingIndex = index + 1 var lastHeight = -1 var trees = 0 while (workingIndex <= this.lastIndex && lastHeight < height) { trees++ lastHeight = this[workingIndex] workingIndex++ } trees } // Part 1 fun findVisibleTrees(input: String): Int { val grid = input.parseGrid() val visibleGrid = grid.lookLeft() or grid.lookRight() or grid.lookDown() or grid.lookUp() return visibleGrid.sumOf { row -> row.sumOf { visible -> if (visible) 1 else 0 as Int } } } private infix fun Grid<Boolean>.or(other: Grid<Boolean>): Grid<Boolean> = mapIndexed { rowIndex, row -> row.mapIndexed { columnIndex, visible -> visible || other[rowIndex][columnIndex] } } private fun Grid<Int>.lookLeft(): Grid<Boolean> = map { it.look() } private fun Grid<Int>.lookRight(): Grid<Boolean> = map { it.reversed() } .lookLeft() .map { it.reversed() } private fun Grid<Int>.lookUp(): Grid<Boolean> = columns() .lookLeft() .columns() private fun Grid<Int>.lookDown(): Grid<Boolean> = reversed() .columns() .lookLeft() .columns() .reversed() private fun List<Int>.look(): List<Boolean> { var tallestSoFar = -1 return fold(emptyList()) { acc, height -> acc + if (height > tallestSoFar) { tallestSoFar = height true } else { false } } } private fun String.parseGrid(): Grid<Int> = lines() .map { it.map { char -> char.digitToInt() } } private fun <T> Grid<T>.columns(): Grid<T> = this[0].indices.map { getColumn(it) } private fun <T> Grid<T>.getColumn(index: Int) = map { it[index] } private fun Grid<Int>.print() { println(fold("") { acc, row -> acc + row.fold("") { rowString, space -> rowString + space } + "\n" }) }
0
Kotlin
0
0
aba1b98a1753fa3f217b70bf55b1f2ff3f69b769
2,713
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day12.kt
vovarova
726,012,901
false
{"Kotlin": 48551}
package days import util.DAY_FILE import util.DayInput class Day12 : Day("12") { class Line(val symbols: List<Char>, val numbers: List<Int>) { fun validSimple(resultIndexes: List<Int>): Boolean { return if (resultIndexes.isEmpty()) { true } else { val lastNumber = numbers[resultIndexes.size - 1] IntRange(0, resultIndexes.last() + lastNumber - 1).filter { symbols[it] == '#' }.count() == numbers.subList(0, resultIndexes.size).sum() && resultIndexes.last() + lastNumber + numbers.subList(resultIndexes.size, numbers.size) .sum() <=symbols.size } } fun valid(): Boolean { return numbers.sum() == symbols.count { it == '#' } } } override fun partOne(dayInput: DayInput): Any { val lines = dayInput.inputList().map { it.split(" ") }.map { Line(it[0].toList(), it[1].split(",").map { it.toInt() }) } val map = lines.map { it to findArrangmentsRecirsively(it) } return map.map { it.second.size }.sum() } fun constructLine(line: Line, resultIndexes: List<Int>): Line { val mutableListOf = mutableListOf(*line.symbols.toTypedArray()) resultIndexes.mapIndexed { index, value -> IntRange(value, value + line.numbers[index] - 1) }.flatten() .map { mutableListOf[it] = '#' } return Line(mutableListOf, line.numbers) } fun findArrangmentsRecirsively( line: Line, numbers: List<Int> = line.numbers, startFrom: Int = 0, resultIndexes: List<Int> = listOf() ): List<Line> { if (numbers.isEmpty()) { val constructLine = constructLine(line, resultIndexes) return if (constructLine.valid()) { listOf(constructLine) } else { println("Not valid lines ${constructLine.symbols}, ${constructLine.numbers}") listOf() } } val constructLine = constructLine(line, resultIndexes) if (!constructLine.validSimple(resultIndexes)) { //println("Not valid lines ${constructLine.symbols}, ${constructLine.numbers}") return listOf() } val number = numbers.first() return line.symbols.windowed(number, 1).mapIndexed { index, value -> index to value.all { it == '?' || it == '#' } }.filter { it.second }.filter { it.first >= startFrom }.map { it.first } .map { findArrangmentsRecirsively( line, numbers.subList(1, numbers.size), it + number + 1, resultIndexes + listOf(it) ) }.flatten() } override fun partTwo(dayInput: DayInput): Any { val lines = dayInput.inputList().map { it.split(" ") }.map { Line(it[0].toList(), it[1].split(",").map { it.toInt() }) }.map { Line( it.symbols + listOf('?') + it.symbols + listOf('?') + it.symbols + listOf('?') + it.symbols + listOf('?') + it.symbols, it.numbers + it.numbers + it.numbers + it.numbers + it.numbers ) } val map = lines.subList(2,5).mapIndexed { index, line -> println("Line ${index}") line to findArrangmentsRecirsively(line) } return map.map { it.second.size }.sum() } } fun main() { println(Day12().partTwo(DayInput("12", DAY_FILE.INPUT))) }
0
Kotlin
0
0
77df1de2a663def33b6f261c87238c17bbf0c1c3
3,638
adventofcode_2023
Creative Commons Zero v1.0 Universal
src/Day08.kt
BenHopeITC
573,352,155
false
null
data class Tree( val treeHeight: Int, val treesLeft: List<Int>, val treesRight: List<Int>, val treesTop: List<Int>, val treesBottom: List<Int> ) { fun isVisible(): Boolean { if (treesLeft.isEmpty() || treesRight.isEmpty() || treesTop.isEmpty() || treesBottom.isEmpty()) { return true } if (treesLeft.none { it >= treeHeight } || treesRight.none { it >= treeHeight } || treesTop.none { it >= treeHeight } || treesBottom.none { it >= treeHeight }) { return true } return false // otherwise not visible } fun viewScore(): Int { val scoreLeft = treesLeft.indexOfFirst { it >= treeHeight }.toViewScore(treesLeft.size) val scoreRight = treesRight.indexOfFirst { it >= treeHeight }.toViewScore(treesRight.size) val scoreTop = treesTop.indexOfFirst { it >= treeHeight }.toViewScore(treesTop.size) val scoreBottom = treesBottom.indexOfFirst { it >= treeHeight }.toViewScore(treesBottom.size) return scoreLeft * scoreRight * scoreTop * scoreBottom } } private fun Int.toViewScore(treeCount: Int) = if (this == -1) treeCount else this + 1 fun main() { val day = "Day08" fun treesFrom(input: List<String>): List<Tree> { val columns = mutableMapOf<Int, String>() input.map { treeRow -> treeRow.toCharArray() }.forEach { it.forEachIndexed { i, c -> val currentVal = columns.getOrDefault(i, "") columns[i] = currentVal + c.toString() } } // .also { println(columns) } val treeObjs = mutableListOf<Tree>() input.mapIndexed { rowIndex, treeRow -> val trees = treeRow.toCharArray().map { it.toString().toInt() } trees.forEachIndexed { columnIndex, treeHeight -> val treesLeft = trees.subList(0, columnIndex).reversed() val treesRight = trees.subList(columnIndex + 1, trees.size) // println("$tree trees left: $treesLeft, right: $treesRight") val colTrees = columns[columnIndex]!!.toCharArray().map { it.toString().toInt() } val treesTop = colTrees.subList(0, rowIndex).reversed() val treesBottom = colTrees.subList(rowIndex + 1, colTrees.size) // println("$tree trees top: $treesTop, bottom: $treesBottom") treeObjs.add(Tree(treeHeight, treesLeft, treesRight, treesTop, treesBottom)) } } return treeObjs } fun part1(input: List<String>): Int { return treesFrom(input).count { it.isVisible() } } fun part2(input: List<String>): Int { return treesFrom(input).maxOf { it.viewScore() } } // test if implementation meets criteria from the description, like: // val testInput = readInput("${day}_test") // println(part1(testInput)) // check(part1(testInput) == 21) // test if implementation meets criteria from the description, like: // val testInput2 = readInput("${day}_test") // println(part2(testInput2)) // check(part2(testInput2) == 8) val input = readInput(day) println(part1(input)) println(part2(input)) check(part1(input) == 1715) check(part2(input) == 374400) }
0
Kotlin
0
0
851b9522d3a64840494b21ff31d83bf8470c9a03
3,297
advent-of-code-2022-kotlin
Apache License 2.0
src/Day12.kt
kipwoker
572,884,607
false
null
class Day12Input( val graph: Map<Point, Int>, val start: Point, val end: Point ) data class Trace(val weight: Int, val current: Point, val prev: Point?, val distance: Int) fun main() { fun getNeighbors(point: Point, graph: Map<Point, Int>): List<Point> { return listOf( Point(point.x - 1, point.y), Point(point.x + 1, point.y), Point(point.x, point.y - 1), Point(point.x, point.y + 1) ).filter { graph.contains(it) } } fun search(graph: Map<Point, Int>, startPoints: List<Point>, endPoint: Point): Int { val visited = startPoints.toMutableSet() val queue = ArrayDeque( startPoints.map { start -> Trace(graph[start]!!, start, null, 0) } ) while (queue.isNotEmpty()) { val item = queue.removeFirst() if (item.current == endPoint) { return item.distance } val source = item.current val sourceWeight = graph[source]!! for (target in getNeighbors(source, graph)) { val targetWeight = graph[target]!! if (targetWeight - sourceWeight > 1 || target in visited) { continue } visited.add(target) queue.addLast(Trace(targetWeight, target, source, item.distance + 1)) } } return -1 } fun parse(input: List<String>): Day12Input { var start = Point(0, 0) var end = Point(0, 0) val graph = input.mapIndexed { i, line -> line.mapIndexed { j, cell -> val value: Int = when (cell) { 'S' -> { start = Point(i, j) 1 } 'E' -> { end = Point(i, j) 'z' - 'a' + 1 } else -> (cell - 'a' + 1) } Point(i, j) to value } }.flatten().toMap() return Day12Input(graph, start, end) } fun part1(input: List<String>): Int { val day12Input = parse(input) return search(day12Input.graph, listOf(day12Input.start), day12Input.end) } fun part2(input: List<String>): Int { val day12Input = parse(input) val startPoints = day12Input.graph.filter { it.value == 1 }.map { it.key } return search(day12Input.graph, startPoints, day12Input.end) } val testInput = readInput("Day12_test") assert(part1(testInput), 31) assert(part2(testInput), 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d8aeea88d1ab3dc4a07b2ff5b071df0715202af2
2,760
aoc2022
Apache License 2.0
src/Day12.kt
Jintin
573,640,224
false
{"Kotlin": 30591}
import java.util.LinkedList fun main() { fun buildMap(input: List<String>, sMapping: Char, eMapping: Char): List<List<Int>> { return input.map { s -> s.replace('S', sMapping).replace('E', eMapping).map { it.code } } } fun find(map: List<List<Int>>, start: Char, end: Char, check: (Int, Int) -> Boolean): Int { val q = LinkedList<Pair<Int, Int>>() val levels = MutableList(map.size) { MutableList(map[0].size) { Int.MAX_VALUE } } map.forEachIndexed { i, chars -> val j = chars.indexOf(start.code) if (j != -1) { levels[i][j] = 0 q.offer(Pair(i, j)) } } while (q.isNotEmpty()) { val (x, y) = q.poll() if (end.code == map[x][y]) { return levels[x][y] } if (x > 0 && check(map[x - 1][y], map[x][y]) && levels[x - 1][y] > levels[x][y] + 1) { levels[x - 1][y] = levels[x][y] + 1 q.offer(Pair(x - 1, y)) } if (x < map.size - 1 && check(map[x + 1][y], map[x][y]) && levels[x + 1][y] > levels[x][y] + 1) { levels[x + 1][y] = levels[x][y] + 1 q.offer(Pair(x + 1, y)) } if (y > 0 && check(map[x][y - 1], map[x][y]) && levels[x][y - 1] > levels[x][y] + 1) { levels[x][y - 1] = levels[x][y] + 1 q.offer(Pair(x, y - 1)) } if (y < map[0].size - 1 && check(map[x][y + 1], map[x][y]) && levels[x][y + 1] > levels[x][y] + 1) { levels[x][y + 1] = levels[x][y] + 1 q.offer(Pair(x, y + 1)) } } return -1 } fun part1(input: List<String>): Int { val map = buildMap(input, 'a' - 1, 'z' + 1) return find(map, 'a' - 1, 'z' + 1) { new, old -> new <= old + 1 } } fun part2(input: List<String>): Int { val map = buildMap(input, 'a', 'z' + 1) return find(map, 'z' + 1, 'a') { new, old -> old <= new + 1 } } val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
4aa00f0d258d55600a623f0118979a25d76b3ecb
2,205
AdventCode2022
Apache License 2.0
src/main/kotlin/Day08.kt
dliszewski
573,836,961
false
{"Kotlin": 57757}
class Day08 { fun part1(input: List<String>): Int { return TreeArea(input).getVisibleTrees() } fun part2(input: List<String>): Int { return TreeArea(input).getBestScore() } class TreeArea(input: List<String>) { private val trees: Array<Array<Tree>> private val size: Int init { val arr: Array<Array<Tree>> = parseTreeArea(input) this.trees = arr this.size = trees.size - 1 } private fun parseTreeArea(input: List<String>): Array<Array<Tree>> { return input.mapIndexed { rowId, row -> row.mapIndexed { columnId, height -> Tree(columnId, rowId, height.digitToInt()) }.toTypedArray() }.toTypedArray() } fun getVisibleTrees(): Int { return trees.flatMap { row -> row.map { isTreeVisible(it) } }.count { it } } fun getBestScore(): Int { return trees.flatMap { row -> row.map { getTreeScore(it) } }.max() } private fun isTreeVisible(tree: Tree): Boolean = isVisibleVertically(tree) || isVisibleHorizontally(tree) private fun isVisibleVertically(tree: Tree): Boolean { return if (tree.rowId == 0 || tree.rowId == size) { true } else { val visibleTop = (tree.rowId - 1 downTo 0).all { tree.height > trees[it][tree.columnId].height } val visibleBottom = (tree.rowId + 1..size).all { tree.height > trees[it][tree.columnId].height } visibleTop || visibleBottom } } private fun isVisibleHorizontally(tree: Tree): Boolean { return if (tree.columnId == 0 || tree.columnId == size) { true } else { val visibleLeft = (tree.columnId - 1 downTo 0).all { tree.height > trees[tree.rowId][it].height } val visibleRight = (tree.columnId + 1..size).all { tree.height > trees[tree.rowId][it].height } visibleLeft || visibleRight } } private fun getTreeScore(tree: Tree): Int = getScoreVertically(tree) * getScoreHorizontally(tree) private fun getScoreVertically(tree: Tree): Int { return if (tree.rowId == 0 || tree.rowId == size) { 1 } else { val scoreTop = (tree.rowId - 1 downTo 0) .map { trees[it][tree.columnId] } .takeUntil { it.height >= tree.height }.count() val scoreBottom = (tree.rowId + 1..size) .map { trees[it][tree.columnId] } .takeUntil { it.height >= tree.height }.count() scoreTop * scoreBottom } } private fun getScoreHorizontally(tree: Tree): Int { return if (tree.columnId == 0 || tree.columnId == size) { 1 } else { val scoreLeft = (tree.columnId - 1 downTo 0) .map { trees[tree.rowId][it] } .takeUntil { it.height >= tree.height }.count() val scoreRight = (tree.columnId + 1..size) .map { trees[tree.rowId][it] } .takeUntil { it.height >= tree.height }.count() scoreLeft * scoreRight } } } data class Tree(val columnId: Int, val rowId: Int, val height: Int) } private fun <T> Iterable<T>.takeUntil(predicate: (T) -> Boolean): List<T> { val list = ArrayList<T>() for (item in this) { list.add(item) if (predicate(item)) break } return list }
0
Kotlin
0
0
76d5eea8ff0c96392f49f450660220c07a264671
3,703
advent-of-code-2022
Apache License 2.0
src/Day07.kt
jamesrobert
573,249,440
false
{"Kotlin": 13069}
import java.util.Deque fun main() { class Command(val name: String, val param: String = "") fun String.command(): Command { val parts = split(" ") return when (parts[1]) { "cd" -> Command(name = "cd", param = parts[2]) "ls" -> Command(name = "ls") else -> error("invalid command") } } fun Map<String, Int>.sizes(directories: ArrayDeque<String>): String { return filter { directories.contains(it.key) }.toList().joinToString { "${it.first}:${it.second}" } } fun ArrayDeque<String>.hierarchy() = joinToString(">") fun calculateFolderStructure(input: List<String>): MutableMap<String, Int> { val map = mutableMapOf<String, Int>() val currentDir = ArrayDeque<String>() for (line in input) { val space = (1..currentDir.size).joinToString(separator = " ") { " " } when { line.startsWith("$ ") -> line.command().let { command -> if (command.name == "cd") { if (command.param == "..") currentDir.removeFirst() else currentDir.addFirst("${currentDir.hierarchy()}>${command.param}") println("${space}cd: ${currentDir.first()}") } if (command.name == "ls") println("${space}ls: ${currentDir.first()}") } line.startsWith("dir ") -> println("${space}dir: $line") line.split(" ").first().toIntOrNull() != null -> currentDir.forEach { map[it] = map.getOrDefault(it, 0) + line.split(" ").first().toInt() }.also { println("${space}file: $line - ${map.sizes(currentDir)}") } } } println(map) return map } fun part1(input: List<String>): Int = calculateFolderStructure(input) .filter { it.value <= 100_000 } .toList() .sumOf { it.second } fun part2(input: List<String>): Int { val folders = calculateFolderStructure(input) val spaceLeft = 70000000 - (folders[">/"] ?: 0) val spaceRequired = 30000000 - spaceLeft return folders.toList() .sortedBy { it.second } .first { it.second >= spaceRequired }.let { println(it) it.second } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") println(testInput) check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println(part1(input)) // first guess 1097622, second 1449447 println(part2(input)) }
0
Kotlin
0
0
d0b49770fc313ae42d802489ec757717033a8fda
2,908
advent-of-code-2022
Apache License 2.0
src/Day15.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
import kotlin.math.abs fun main() { class Position(val x: Long, val y: Long) { fun distance(other: Position): Long { return abs(x - other.x) + abs(y - other.y) } } class Sensor(val pos: Position, val beacon: Position) { fun radius(): Long { return pos.distance(beacon) } } fun readSensor(input: String): Sensor { val regex = Regex("""Sensor at x=(.\d*), y=(.\d*): closest beacon is at x=(.\d*), y=(.\d*)""") val match = regex.matchEntire(input) val (xs, ys, xb, yb) = match!!.groups.drop(1).map { x -> x!!.value.toLong() } return Sensor(Position(xs, ys), Position(xb, yb)) } class CoverageSegment(val start: Long, val end: Long) class Event(val x: Long, val type: Int) fun getCoverage(sensor: Position, distance: Long, y: Long): CoverageSegment? { if (abs(sensor.y - y) > distance) { return null } return CoverageSegment( sensor.x - (distance - abs(sensor.y - y)), sensor.x + (distance - abs(sensor.y - y)) + 1 ) } fun part1(input: List<String>, y: Long): Long { val sensors = input.map(::readSensor) val coverage = sensors.map { sensor -> getCoverage(sensor.pos, sensor.radius(), y) } val left = coverage.minOf { segment -> segment?.start ?: 0 } val right = coverage.maxOf { segment -> segment?.end ?: 0 } var ans = 0L for (x in left..right) { if (sensors.any { sensor -> sensor.beacon.distance(Position(x, y)) == 0L }) { continue } if (sensors.any { sensor -> sensor.pos.distance(Position(x, y)) <= sensor.radius() }) { ans += 1 } } return ans } fun part2(input: List<String>, maxCoordinate: Long): Position { val sensors = input.map(::readSensor) for (y in 0..maxCoordinate) { val coverage = sensors.map { sensor -> getCoverage(sensor.pos, sensor.radius(), y) } val events = coverage.flatMap { s -> if (s != null) { listOf(Event(s.start, 1), Event(s.end, -1)) } else { listOf() } } val sortedEvents = events.sortedWith(compareBy<Event> { e -> e.x }.thenBy { e -> -e.type }) var balance = 0 for (e in sortedEvents) { balance += e.type if ((balance == 0) && (e.x <= maxCoordinate) && sensors.all { sensor -> sensor.beacon.distance( Position( e.x, y ) ) != 0L }) { return Position(e.x, y) } } } return Position(-1, -1) } val testInput = readInput("Day15-test") val input = readInput("Day15") println("Day 15") println("test part1 ${part1(testInput, 10)}") println("real part1 ${part1(input, 2000000)}") val testHiddenBeacon = part2(testInput, 20) println("test part2 ${testHiddenBeacon.x} ${testHiddenBeacon.y} -> ${testHiddenBeacon.x * 4000000 + testHiddenBeacon.y}") val hiddenBeacon = part2(input, 4000000) println("test part2 ${hiddenBeacon.x} ${hiddenBeacon.y} -> ${hiddenBeacon.x * 4000000 + hiddenBeacon.y}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
3,466
aoc-2022
Apache License 2.0
src/aoc2021/Day04.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2021 import readInput fun main() { val (year, day) = "2021" to "Day04" fun List<List<Int>>.sumBoard(markedNumbers: Set<Int>): Int { return sumOf { it.filter { number -> number !in markedNumbers }.sum() } } fun List<List<Int>>.checkBoard(markedNumbers: Set<Int>): Pair<Boolean, Int> { for (row in indices) { val bingo = this[row].all { it in markedNumbers } if (bingo) return Pair(true, sumBoard(markedNumbers)) } for (col in this[0].indices) { val bingo = all { it[col] in markedNumbers } if (bingo) return Pair(true, sumBoard(markedNumbers)) } return false to 0 } fun playBingo( boards: List<List<MutableList<Int>>>, numbers: List<Int>, firstFound: Boolean = true ): Int { val boardBingo = BooleanArray(boards.size) var bingoLeft = boards.size val markedNumbers = mutableSetOf<Int>() numbers.forEach { number -> markedNumbers += number boards.forEachIndexed { index, board -> if (boardBingo[index]) return@forEachIndexed val (bingo, sum) = board.checkBoard(markedNumbers) if (bingo) { boardBingo[index] = bingo if (firstFound || --bingoLeft == 0) { return sum * number } } } } return 0 } fun part1(input: List<String>): Int { val (numbers, boards) = parseInput(input) return playBingo(boards, numbers) } fun part2(input: List<String>): Int { val (numbers, boards) = parseInput(input) return playBingo(boards, numbers, firstFound = false) } val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) check(part1(testInput) == 4512) println(part1(input)) check(part2(testInput) == 1924) println(part2(input)) } fun parseInput(input: List<String>): Pair<List<Int>, List<List<MutableList<Int>>>> { val numbers = input.first().split(",").map { it.toInt() } val lines = input.drop(1).filter { it.isNotEmpty() } val boards = lines.windowed(5, 5).map { it.map { row -> row.split(" ").filter { it.isNotEmpty() }.map { it.toInt() }.toMutableList() }.toMutableList() }.toMutableList() return numbers to boards }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
2,485
aoc-kotlin
Apache License 2.0
src/Day11.kt
dmarcato
576,511,169
false
{"Kotlin": 36664}
import java.util.* data class Monkey( val items: Queue<Long>, val operation: (Long, Long) -> Long, val operationValue: Long?, val testValue: Long, val ifTrueDestination: Int, val ifFalseDestination: Int, var itemsInspected: Long = 0L ) fun makeMonkeys(input: List<String>): Pair<Int, Monkey> { val index = "\\s(\\d+):".toRegex().find(input[0])!!.groupValues[1].toInt() val items = input[1].split(": ")[1].split(", ").map { it.toLong() } val (_, op, valueString) = "old\\s([+*])\\s(\\d+|old)".toRegex().find(input[2])!!.groupValues val opValue = when (valueString) { "old" -> null else -> valueString.toLong() } val operation: (Long, Long) -> Long = when (op) { "+" -> Long::plus "*" -> Long::times else -> throw RuntimeException() } val testValue = input[3].split(" ").last().toLong() val ifTrue = input[4].split(" ").last().toInt() val ifFalse = input[5].split(" ").last().toInt() val queue = LinkedList<Long>() queue.addAll(items) return index to Monkey(queue, operation, opValue, testValue, ifTrue, ifFalse) } fun monkeyBusiness(monkeys: Map<Int, Monkey>, worryLevel: Long?, rounds: Int): Long { val monkeyOrder = monkeys.keys.sorted() val commonDivisor = monkeys.values.fold(1L) { acc, monkey -> acc * monkey.testValue } (0 until rounds).forEach { _ -> monkeyOrder.forEach { num -> val monkey = monkeys[num]!! monkey.items.forEach { item -> var newItem = monkey.operation(item, monkey.operationValue ?: item) newItem = worryLevel?.let { newItem / it } ?: (newItem % commonDivisor) val destMonkey = if (newItem.mod(monkey.testValue) == 0L) { monkey.ifTrueDestination } else { monkey.ifFalseDestination } monkeys[destMonkey]!!.items.offer(newItem) monkey.itemsInspected++ } monkey.items.clear() } } val (m1, m2) = monkeys.values.sortedByDescending { it.itemsInspected }.take(2) return m1.itemsInspected * m2.itemsInspected } fun main() { fun part1(input: List<String>): Long { val monkeys = input.windowed(6, 7, true) { makeMonkeys(it) }.toMap() return monkeyBusiness(monkeys, 3L, 20) } fun part2(input: List<String>): Long { val monkeys = input.windowed(6, 7, true) { makeMonkeys(it) }.toMap() return monkeyBusiness(monkeys, null, 10000) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) { "part1 check failed" } check(part2(testInput) == 2713310158L) { "part2 check failed" } val input = readInput("Day11") part1(input).println() part2(input).println() }
0
Kotlin
0
0
6abd8ca89a1acce49ecc0ca8a51acd3969979464
2,974
aoc2022
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day08.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
package de.niemeyer.aoc2022 /** * Advent of Code 2022, Day 8: Treetop kotlin.aoc2022.niemeyer.aoc2022.Tree House * Problem Description: https://adventofcode.com/2022/day/8 */ import de.niemeyer.aoc.points.Point2D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName import de.niemeyer.aoc.utils.product import de.niemeyer.aoc.utils.takeUntil fun main() { fun part1(input: TreeMap): Int = input.trees.keys.map { tree -> tree visibleIn input }.count { it } fun part2(input: TreeMap): Int { val scores = input.trees.keys.map { tree -> tree.scenicScore(input) } return scores.max() } val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt").toPointMap() val puzzleInput = resourceAsList(fileName = "${name}.txt").toPointMap() check(part1(testInput) == 21) println(part1(puzzleInput)) check(part1(puzzleInput) == 1_820) check(part2(testInput) == 8) println(part2(puzzleInput)) check(part2(puzzleInput) == 385_112) } fun List<String>.toPointMap(): TreeMap = TreeMap(this.flatMapIndexed { row, line -> line.mapIndexed { col, tree -> Point2D(col, row) to tree.digitToInt() } }.toMap()) typealias Tree = Point2D data class TreeMap(val trees: Map<Tree, Int>) { val points = trees.keys.toList() val rows = points.maxOf { it.y } val columns = points.maxOf { it.x } fun upTrees(tree: Tree) = (tree lineTo Point2D(tree.x, 0)) - tree fun downTrees(tree: Tree) = (tree lineTo Point2D(tree.x, columns)) - tree fun leftTrees(tree: Tree) = (tree lineTo Point2D(0, tree.y)) - tree fun rightTrees(tree: Tree) = (tree lineTo Point2D(rows, tree.y)) - tree } infix fun Tree.visibleIn(treeMap: TreeMap): Boolean { fun visibleTrees(trees: List<Tree>, maxHeight: Int) = trees.all { treeMap.trees.getValue(it) < maxHeight } val treeHeight = treeMap.trees.getValue(this) return listOf(treeMap.upTrees(this), treeMap.downTrees(this), treeMap.leftTrees(this), treeMap.rightTrees(this)) .map { trees -> visibleTrees(trees, treeHeight) }.any { it } } fun Tree.scenicScore(treeMap: TreeMap): Int { val treeHeight = treeMap.trees.getValue(this) return listOf(treeMap.upTrees(this), treeMap.downTrees(this), treeMap.leftTrees(this), treeMap.rightTrees(this)) .map { trees -> trees.takeUntil { treeMap.trees.getValue(it) >= treeHeight }.size }.product() }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,572
AoC-2022
Apache License 2.0
src/main/kotlin/day16/Day16.kt
qnox
575,581,183
false
{"Kotlin": 66677}
package day16 import readInput fun main() { data class Valve(val id: String, val rate: Int, val linkedWith: Set<String>) data class Valves(val valves: Map<String, Valve>) { val dist: Map<String, Map<String, Int>> = valves.mapValues { (id, _) -> dist(valves, id) } fun dist(valves: Map<String, Valve>, from: String): Map<String, Int> { val q = ArrayDeque<String>() q.addLast(from) val visited = mutableSetOf(from) val result = mutableMapOf<String, Int>() var dist = 0 while (q.isNotEmpty()) { var rest = q.size while (rest > 0) { val c = q.removeFirst() result[c] = dist q.addAll(valves[c]!!.linkedWith.filter { visited.add(it) }) rest -= 1 } dist += 1 } return result } operator fun get(current: String): Valve = valves[current] ?: error("Unknown valve $current") } val pattern = "Valve (.+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)".toRegex() fun parseValves(input: List<String>) = Valves(input.associate { line -> pattern.matchEntire(line)?.let { match -> val id = match.groups[1]!!.value val rate = match.groups[2]!!.value.toInt() val linkedWith = match.groups[3]!!.value.split(", ") id to Valve(id, rate, linkedWith.toSet()) } ?: error("No match: $line") }) fun solve(valves: Valves, current: List<String>, notVisited: Set<String>, rest: List<Int>): Int { val (currentActor, actorRest) = rest.withIndex().maxBy { it.value } val valveId = current[currentActor] val dist = valves.dist[valveId]!! return notVisited.maxOfOrNull { val newRest = actorRest - dist[it]!! - 1 if (newRest > 0) { val valve = valves[it] val newNotVisited = notVisited - it (newRest * valve.rate) + solve(valves, buildList { addAll(current) set(currentActor, it) }, newNotVisited, buildList { addAll(rest) set(currentActor, newRest) }) } else { 0 } } ?: 0 } fun part1(input: List<String>): Int { val valves = parseValves(input) val notVisited = valves.valves.filter { (_, valve) -> valve.rate > 0 }.keys.toSet() return solve(valves, listOf("AA"), notVisited, listOf(30)) } fun part2(input: List<String>): Int { val valves = parseValves(input) val notVisited = valves.valves.filter { (_, valve) -> valve.rate > 0 }.keys.toSet() return solve(valves, listOf("AA", "AA"), notVisited, listOf(26, 26)) } val testInput = readInput("day16", "test") val input = readInput("day16", "input") val part1 = part1(testInput) println(part1) check(part1 == 1651) println(part1(input)) val part2 = part2(testInput) println(part2) check(part2 == 1707) println(part2(input)) }
0
Kotlin
0
0
727ca335d32000c3de2b750d23248a1364ba03e4
3,216
aoc2022
Apache License 2.0
2022/Day16.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { val input = readInput("Day16") data class Valve( val name: String, val rate: Int, val leads: List<String> ) val valves = input.map { s -> val (valve, rate, leads) = s.split("Valve ", " has flow rate=", "; tunnels lead to valves ", "; tunnel leads to valve ").drop(1) Valve(valve, rate.toInt(), leads.split(", ") ) }.sortedBy { it.rate <= 0 } val dist = Array(valves.size) { IntArray(valves.size) { Int.MAX_VALUE/3 } } val name2Idx = valves.mapIndexed { i, v -> v.name to i }.associate { it } for (i in valves.indices) { dist[i][i] = 0 for (v in valves[i].leads.map { name2Idx[it]!! }) { dist[i][v] = 1 } } for (k in dist.indices) { for (i in dist.indices) { for (j in dist.indices) { dist[i][j] = minOf(dist[i][j], dist[i][k] + dist[k][j]) } } } val n = valves.count { it.rate > 0 } fun solve(s: Int, mask: Int, time: Int): Int { var res = 0 for (v in 0 until n) { val vv = 1 shl v if (vv and mask == 0) { val t = time - dist[s][v] - 1 if (t > 0) { res = maxOf(res, solve(v, mask or vv, t) + t * valves[v].rate) } } } return res } val aa = name2Idx["AA"]!! val res1 = solve(aa, 0, 30) println(res1) val fullMask = (1 shl n) - 1 var res2 = 0 for (mask in 0 until (fullMask shr 1)) { res2 = maxOf(res2, solve(aa, mask, 26) + solve(aa, fullMask xor mask, 26)) } println(res2) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,654
advent-of-code-kotlin
Apache License 2.0
2022/src/main/kotlin/day13_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution import utils.badInput fun main() { Day13Imp.run() } object Day13Imp : Solution<List<Pair<Day13Imp.Fragment.Packet, Day13Imp.Fragment.Packet>>>() { override val name = "day13" sealed class Fragment : Comparable<Fragment> { class Packet(val fragments: List<Fragment>): Fragment() { override fun compareTo(other: Fragment): Int { return if (other is Packet) { val itemCmp = fragments.zip(other.fragments).map { it.first.compareTo(it.second) }.firstOrNull { it != 0 } itemCmp ?: fragments.size.compareTo(other.fragments.size) } else { compareTo(Packet(listOf(other))) } } } class Value(val value: Int): Fragment() { override fun compareTo(other: Fragment): Int { return if (other is Value) { value.compareTo(other.value) } else { Packet(listOf(this)).compareTo(other) } } } companion object { fun parse(input: String): Pair<Fragment, Int> { if (input.startsWith("[")) { var read = 1 val items = mutableListOf<Fragment>() while (read < input.length && input[read] != ']') { val (item, len) = parse(input.substring(read)) items.add(item) read += len if (input[read] == ',') { // advance by one past the splitting comma read++ } } return Packet(items) to read + 1 // add the trailing `]` } val end = input.indexOfFirst { it == ',' || it == ']' }.takeIf { it >= 0 } ?: input.length return Value(input.substring(0, end).toInt()) to end } } } override val parser = Parser { input -> input.split("\n\n").map { packetPair -> val (l, r) = packetPair.trim().split("\n").map { Fragment.parse(it.trim()).first } if (l !is Fragment.Packet) badInput() if (r !is Fragment.Packet) badInput() l to r } } override fun part1(input: List<Pair<Fragment.Packet, Fragment.Packet>>): Int { return input.mapIndexed { index, pair -> if (pair.first < pair.second) (index + 1) else 0 }.sum() } override fun part2(input: List<Pair<Fragment.Packet, Fragment.Packet>>): Int { val dividers = listOf("[[2]]", "[[6]]").map { Fragment.parse(it).first } val packets = (input.flatMap { listOf(it.first, it.second) } + dividers).sorted() return packets.indices.filter { i -> packets[i] in dividers } .also { require(it.size == 2) } .map { it + 1 } .reduce { a, b -> a * b } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,599
aoc_kotlin
MIT License
src/main/kotlin/Day13.kt
Vampire
572,990,104
false
{"Kotlin": 57326}
fun main() { fun getNextList(s: String): String { require(s.first() == '[') var level = 0 return s.takeWhile { 0 < when (it) { '[' -> ++level ']' -> --level else -> level } } + ']' } fun parseList(list: String): List<Any> { require(list.first() == '[') require(list.last() == ']') var remainingListContents = getNextList(list) .drop(1) .dropLast(1) return buildList { while (remainingListContents.isNotEmpty()) { add( when (remainingListContents.first()) { in '0'..'9' -> remainingListContents .substringBefore(',') .also { remainingListContents = remainingListContents .substringAfter(',', "") } .toInt() '[' -> getNextList(remainingListContents) .also { remainingListContents = remainingListContents .substringAfter(it) .substringAfter(',') } .let { parseList(it) } else -> error("Unexpected list contents: $remainingListContents") } ) } } } operator fun List<*>.compareTo(other: List<*>): Int { for (i in indices) { if (i >= other.size) { return 1 } val a = get(i) val b = other[i] when { (a is Int) && (b is Int) -> if (a != b) return a - b (a is List<*>) && (b is List<*>) -> if (a != b) return a.compareTo(b) (a is List<*>) -> if (a != listOf(b)) return a.compareTo(listOf(b)) (b is List<*>) -> if (listOf(a) != b) return listOf(a).compareTo(b) } } if (size < other.size) { return -1 } return 0 } fun part1(input: List<String>) = input .asSequence() .filter { it.isNotBlank() } .map { parseList(it) } .chunked(2) .mapIndexed { i, (a, b) -> if (a < b) (i + 1) else 0 } .sum() fun part2(input: List<String>): Int { val dividers = listOf(listOf(listOf(2)), listOf(listOf(6))) return input .asSequence() .filter { it.isNotBlank() } .map { parseList(it) } .let { it + dividers } .sortedWith { a, b -> a.compareTo(b) } .toList() .let { packets -> dividers.map { packets.indexOf(it) + 1 }.reduce(Int::times) } } val testInput = readStrings("Day13_test") check(part1(testInput) == 13) val input = readStrings("Day13") println(part1(input)) check(part2(testInput) == 140) println(part2(input)) }
0
Kotlin
0
0
16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f
3,167
aoc-2022
Apache License 2.0
src/day15/Day15.kt
GrzegorzBaczek93
572,128,118
false
{"Kotlin": 44027}
package day15 import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min import readInput import utils.withStopwatch fun main() { val testInput = readInput("input15_test") withStopwatch { println(part1(testInput, 10)) } withStopwatch { println(part2(testInput, 0..20)) } val input = readInput("input15") withStopwatch { println(part1(input, 2000000)) } withStopwatch { println(part2(input, 0..4000000)) } } private fun part1(input: List<String>, yLine: Int): Int { val map = mutableMapOf<Position, Field>() parse(input).forEach { (sensor, beacon) -> val radius = calculateDistance(sensor, beacon) val absDistance = (sensor.y - yLine).absoluteValue val xRange = sensor.x - (radius - absDistance)..sensor.x + (radius - absDistance) for (x in xRange) { val position = Position(x, yLine) when { position == sensor -> map[position] = Field.Sensor position == beacon -> map[position] = Field.Beacon map.containsKey(position) && map[position] != Field.Coverage -> {} else -> map[position] = Field.Coverage } } } return map.count { (_, field) -> field == Field.Coverage } } private fun part2(input: List<String>, range: IntRange): Long { val parsed = parse(input) for (x in range) { val ranges = mutableSetOf<IntRange>() parsed.forEach { (sensor, beacon) -> val radius = calculateDistance(sensor, beacon) val positiveXEdge = min(sensor.x + radius, range.last) val negativeXEdge = max(sensor.x - radius, range.first) if (x !in negativeXEdge..positiveXEdge) return@forEach val negativeYEdge = max(sensor.y - (radius - (x - sensor.x).absoluteValue), range.first) val positiveYEdge = min(sensor.y + (radius - (x - sensor.x).absoluteValue), range.last) ranges.add(negativeYEdge..positiveYEdge) } val sorted = ranges.sortedBy { it.first } sorted.reduce { acc, intRange -> when { acc.last >= intRange.first - 1 && acc.last >= intRange.last -> acc acc.last >= intRange.first - 1 && acc.last < intRange.last -> acc.first..intRange.last else -> return x.toLong() * 4000000 + (acc.last + 1) } } } return -1 } private fun parse(input: List<String>) = input.map { line -> line.split(':') .map { halfLine -> halfLine.split(',').map { chunk -> chunk.filter { it.isDigit() || it == '-' }.toInt() } } .map { (x, y) -> Position(x, y) } }.map { (sensor, beacon) -> sensor to beacon } private fun calculateDistance(sensor: Position, beacon: Position): Int = (sensor.x - beacon.x).absoluteValue + (sensor.y - beacon.y).absoluteValue private data class Position( val x: Int, val y: Int, ) private sealed class Field { object Sensor : Field() { override fun toString(): String = "S" } object Beacon : Field() { override fun toString(): String = "B" } object Coverage : Field() { override fun toString(): String = "#" } }
0
Kotlin
0
0
543e7cf0a2d706d23c3213d3737756b61ccbf94b
3,253
advent-of-code-kotlin-2022
Apache License 2.0
src/day09/Day09.kt
MaxBeauchemin
573,094,480
false
{"Kotlin": 60619}
package day09 import readInput import java.lang.Math.abs enum class Direction(val key: String, val xChange: Int, val yChange: Int) { UP("U", 0, 1), DOWN("D", 0, -1), LEFT("L", -1, 0), RIGHT("R", 1, 0); companion object { val keys = Direction.values().associateBy { it.key } } } data class Position(var x: Int, var y: Int) { fun key() = "$x $y" fun apply(direction: Direction) { this.x += direction.xChange this.y += direction.yChange } fun follow(other: Position) { val xDiff = other.x - this.x val yDiff = other.y - this.y val absXDiff = abs(xDiff) val absYDiff = abs(yDiff) val xChange = if (xDiff > 0) 1 else -1 val yChange = if (yDiff > 0) 1 else -1 // If the head is ever two steps directly up, down, left, or right from the tail, // the tail must also move one step in that direction so it remains close enough if ((absXDiff == 2 && yDiff == 0) || (xDiff == 0 && absYDiff == 2)) { if (absXDiff > 0) { this.x += xChange } else { this.y += yChange } return } // Otherwise, if the head and tail aren't touching and aren't in the same row or column, // the tail always moves one step diagonally to keep up if ((absXDiff >= 1 && absYDiff >= 1) && (absXDiff > 1 || absYDiff > 1)) { this.x += xChange this.y += yChange } } } fun main() { fun parseInstructions(input: List<String>): List<Direction> { return input.flatMap { it.split(" ").let { tokens -> val direction = Direction.keys[tokens[0]]!! (1..tokens[1].toInt()).map { direction } } } } fun part1(input: List<String>): Int { val instructions = parseInstructions(input) val head = Position(1, 1) val tail = Position(1, 1) val visited = mutableListOf(tail.key()) instructions.forEach { dir -> head.apply(dir) tail.follow(head) visited.add(tail.key()) } return visited.distinct().size } fun part2(input: List<String>): Int { val instructions = parseInstructions(input) val knots = (1..10).map { Position(1, 1) } val visited = mutableListOf(knots.last().key()) instructions.forEach { dir -> knots[0].apply(dir) for (i in 1..9) { knots[i].follow(knots[i - 1]) } visited.add(knots.last().key()) } return visited.distinct().size } val testInput = readInput("Day09_test") val secondTestInput = readInput("Day09_second_test") val input = readInput("Day09") println("Part 1 [Test] : ${part1(testInput)}") check(part1(testInput) == 13) println("Part 1 [Real] : ${part1(input)}") println("Part 2 [Test] : ${part2(testInput)}") check(part2(testInput) == 1) println("Part 2 [2nd Test] : ${part2(secondTestInput)}") check(part2(secondTestInput) == 36) println("Part 2 [Real] : ${part2(input)}") }
0
Kotlin
0
0
38018d252183bd6b64095a8c9f2920e900863a79
3,239
advent-of-code-2022
Apache License 2.0
2015/Day17/src/main/kotlin/Main.kt
mcrispim
658,165,735
false
null
import java.io.File fun combinations(arr: Array<Int>, r: Int): List<List<Int>> { val data = Array(r) { 0 } val results = mutableListOf<List<Int>>() for (n in 1..r) { combinationUtil(arr, n, 0, data, 0, results) } return results } fun combinationUtil(arr: Array<Int>, r: Int, index: Int, data: Array<Int>, i: Int, results: MutableList<List<Int>>) { if (index == r) { results.add(data.slice(0..<r).toList()) return } if (i >= arr.size) return data[index] = arr[i] combinationUtil(arr, r, index + 1, data, i + 1, results) combinationUtil(arr, r, index, data, i + 1, results) } fun main() { fun part1(input: List<String>, liters: Int): Int { val volumes = input.map { it.toInt() }.sortedDescending() return combinations(volumes.toTypedArray(), volumes.size).filter { it.sum() == liters }.size } fun part2(input: List<String>, liters: Int): Int { val allVolumes = input.map { it.toInt() }.sortedDescending() val volumesWithLiters = combinations(allVolumes.toTypedArray(), allVolumes.size).filter { it.sum() == liters } val minNumberOfVolumes = volumesWithLiters.minOfOrNull { it.size } return volumesWithLiters.filter { it.size == minNumberOfVolumes }.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day17_test") check(part1(testInput, liters = 25) == 4) check(part2(testInput, liters = 25) == 3) val input = readInput("Day17_data") println("Part 1 answer: ${part1(input, 150)}") println("Part 2 answer: ${part2(input, 150)}") } /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines()
0
Kotlin
0
0
2f4be35e78a8a56fd1e078858f4965886dfcd7fd
1,799
AdventOfCode
MIT License
src/Day07.kt
afranken
572,923,112
false
{"Kotlin": 15538}
import Node.Dir import Node.File fun main() { fun treeOf(input: List<String>): Dir { var current = Dir("/", null) input .drop(1) .filterNot(String::isBlank) .forEach { if (it.startsWith("$")) { if (it.startsWith("$ cd")) { val dirName = it.split(' ')[2] current = if (dirName == "..") current.parent!! else current .children .filter { it.name == dirName } .filterIsInstance<Dir>() .firstOrNull() ?: Dir(dirName, current) } } else if (it.startsWith("dir")) { val dirName = it.split(' ')[1] current.children.add(Dir(dirName, current)) } else { val (size, name) = it.split(' ') current.children.add(File(name, size.toInt(), current)) } } while (current.parent != null) { current = current.parent!! } return current } fun part1(input: List<String>): Int { val smallDirs = arrayListOf<Dir>() val queue = ArrayDeque<Dir>() val root = treeOf(input) queue.add(root) while (queue.isNotEmpty()) { val dir = queue.removeFirst() if (dir.size <= 100000) { smallDirs.add(dir) } queue.addAll(dir.children.filterIsInstance<Dir>()) } return smallDirs.sumOf { it.size } } fun part2(input: List<String>): Int { val root = treeOf(input) val needToFree = root.size - 40000000 val dirs = sortedSetOf<Dir>({ o1, o2 -> o1.size.compareTo(o2.size) }) val queue = ArrayDeque<Dir>() queue.add(treeOf(input)) while (queue.isNotEmpty()) { val dir = queue.removeFirst() if (dir.size >= needToFree) { dirs.add(dir) } queue.addAll(dir.children.filterIsInstance<Dir>()) } return dirs.first().size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day07_test") check(part1(testInput) == 95437) println(part1(testInput)) check(part2(testInput) == 24933642) println(part2(testInput)) val input = readInput("Day07") check(part1(input) == 1086293) println(part2(input)) } interface Node { val size: Int val name: String val parent: Dir? data class File(override val name: String, override val size: Int, override val parent: Dir?) : Node data class Dir(override val name: String, override val parent: Dir?) : Node { val children = hashSetOf<Node>() override val size: Int by lazy { children.sumOf { it.size } } } }
0
Kotlin
0
0
f047d34dc2a22286134dc4705b5a7c2558bad9e7
2,926
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/Excercise08.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
private fun part1() { getInputAsTest("08") .map { InputRow.of(it) } .sumOf { row -> row.digitSegments.takeLast(4).count { it.size in setOf(2, 3, 4, 7) } } .let { println("Part1 $it") } } private fun part2() { getInputAsTest("08").map { InputRow.of(it) }.sumOf { row -> row.calculateValue() }.let { println("Part2 $it") } } private class InputRow(val digitSegments: List<Set<Char>>) { private val digitValues = discoverMappings() fun calculateValue(): Int = (digitValues.getValue(digitSegments[10]) * 1000) + (digitValues.getValue(digitSegments[11]) * 100) + (digitValues.getValue(digitSegments[12]) * 10) + digitValues.getValue(digitSegments[13]) private fun discoverMappings(): Map<Set<Char>, Int> { val digitToString = Array<Set<Char>>(10) { emptySet() } // Unique based on size digitToString[1] = digitSegments.first { it.size == 2 } digitToString[4] = digitSegments.first { it.size == 4 } digitToString[7] = digitSegments.first { it.size == 3 } digitToString[8] = digitSegments.first { it.size == 7 } // 3 is length 5 and overlaps 1 digitToString[3] = digitSegments.filter { it.size == 5 }.first { it overlaps digitToString[1] } // 9 is length 6 and overlaps 3 digitToString[9] = digitSegments.filter { it.size == 6 }.first { it overlaps digitToString[3] } // 0 is length 6, overlaps 1 and 7, and is not 9 digitToString[0] = digitSegments .filter { it.size == 6 } .filter { it overlaps digitToString[1] && it overlaps digitToString[7] } .first { it != digitToString[9] } // 6 is length 6 and is not 0 or 9 digitToString[6] = digitSegments.filter { it.size == 6 }.first { it != digitToString[0] && it != digitToString[9] } // 5 is length 5 and is overlapped by 6 digitToString[5] = digitSegments.filter { it.size == 5 }.first { digitToString[6] overlaps it } // 2 is length 5 and is not 3 or 5 digitToString[2] = digitSegments.filter { it.size == 5 }.first { it != digitToString[3] && it != digitToString[5] } return digitToString.mapIndexed { index, chars -> chars to index }.toMap() } private infix fun Set<Char>.overlaps(that: Set<Char>): Boolean = this.containsAll(that) companion object { fun of(input: String): InputRow = InputRow(input.split(" ").filterNot { it == "|" }.map { it.toSet() }) } } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
2,469
advent-of-code-2021
MIT License
src/Day03.kt
CrazyBene
573,111,401
false
{"Kotlin": 50149}
fun main() { fun <T> getItemsInBothLists(list1: List<T>, list2: List<T>) = list1.filter { list2.contains(it) }.distinct() data class Item(val character: Char) { fun getPriorityValue(): Int { return if (character.isLowerCase()) character - 'a' + 1 else if (character.isUpperCase()) character - 'A' + 27 else error("Item $this seems to be neither lower nor upper case.") } } data class Rucksack(val compartment1: List<Item>, val compartment2: List<Item>) { fun getAllItems() = compartment1 + compartment2 fun getDuplicateItem(): Item { val itemsInBothLists = getItemsInBothLists(compartment1, compartment2) if (itemsInBothLists.size == 1) return itemsInBothLists.first() error("There are ${itemsInBothLists.size} items which appear in both compartments of $this.") } } data class ElvesGroup(val rucksacks: List<Rucksack>) { fun getItemInAllRucksacks(): List<Item> { if (rucksacks.isEmpty()) return emptyList() if (rucksacks.size == 1) return rucksacks.first().getAllItems() var itemsToCompare = rucksacks.first().getAllItems() for (i in 1 until rucksacks.size) itemsToCompare = getItemsInBothLists(itemsToCompare, rucksacks[i].getAllItems()) return itemsToCompare } } fun String.splitInHalf(): Pair<String, String> { if (length % 2 != 0) error("String '$this' needs an event amount of characters to be split in half.") val middle = length / 2 return substring(0, middle) to substring(middle, length) } fun String.toItemList(): List<Item> { return toList().map { Item(it) } } fun part1(input: List<String>): Int { val rucksacks = input.map { val (compartment1, compartment2) = it.splitInHalf() Rucksack(compartment1.toItemList(), compartment2.toItemList()) } return rucksacks.sumOf { it.getDuplicateItem().getPriorityValue() } } fun part2(input: List<String>): Int { val elvesGroups = input.map { val (compartment1, compartment2) = it.splitInHalf() Rucksack(compartment1.toItemList(), compartment2.toItemList()) }.chunked(3).map { ElvesGroup(it) } return elvesGroups.sumOf { val itemsInAllRucksacks = it.getItemInAllRucksacks() if (itemsInAllRucksacks.size != 1) error("There seems to not exactly one item which is present in $it.") itemsInAllRucksacks.first().getPriorityValue() } } val testInput = readInput("Day03Test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println("Question 1 - Answer: ${part1(input)}") println("Question 2 - Answer: ${part2(input)}") }
0
Kotlin
0
0
dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26
2,987
AdventOfCode2022
Apache License 2.0
src/main/kotlin/Day9.kt
Ostkontentitan
434,500,914
false
{"Kotlin": 73563}
fun puzzleDayNinePartOne() { val inputs = readInput(9).map { lines -> lines.map { Integer.parseInt(it.toString()) } } val bumpedSum = findLowPoints(inputs).map { it.height }.sumOf { it + 1 } println("Low point sum is: $bumpedSum") } fun puzzleDayNinePartTwo() { val inputs = readInput(9).map { lines -> lines.map { Integer.parseInt(it.toString()) } } val lowPoints = findLowPoints(inputs) val basins = detectBasinSizes(inputs, lowPoints) val sizesMultiplied = basins.sortedDescending().take(3).fold(0L) { acc, item -> if (acc == 0L) item.toLong() else item * acc } println("Multiplied basin size is: $sizesMultiplied") } fun detectBasinSizes(inputs: List<List<Int>>, lowPoints: List<FloorTile>): List<Int> = lowPoints.map { lowPoint -> var surroundings = getSurroundings(inputs, lowPoint) val results = (listOf(lowPoint) + surroundings).toMutableSet() while (surroundings.isNotEmpty()) { surroundings = surroundings.flatMap { tile -> getSurroundings(inputs, tile) }.filterNot { results.contains(it) }.toSet() results.addAll(surroundings) println("new surroundings addded: ${surroundings.size} - resultsize: ${results.size}") } results.size } fun getSurroundings(inputs: List<List<Int>>, tile: FloorTile): Set<FloorTile> { val x = tile.posX val y = tile.posY val above = if (y != inputs.lastIndex) notNineOrNull(inputs, x, y + 1) else null val below = if (y != 0) notNineOrNull(inputs, x, y - 1) else null val left = if (x != 0) notNineOrNull(inputs, x - 1, y) else null val right = if (x != inputs[0].lastIndex) notNineOrNull(inputs, x + 1, y) else null return setOfNotNull(above, below, left, right) } fun notNineOrNull(inputs: List<List<Int>>, x: Int, y: Int): FloorTile? { val input = inputs[y][x] return if (input != 9) { FloorTile(x, y, input) } else null } fun findLowPoints(inputs: List<List<Int>>): List<FloorTile> { val lowPoints = mutableListOf<FloorTile>() (0..inputs.lastIndex).forEach { y -> (0..inputs[0].lastIndex).forEach { x -> val above = if (y != inputs.lastIndex) inputs[y + 1][x] else 10 val below = if (y != 0) inputs[y - 1][x] else 10 val left = if (x != 0) inputs[y][x - 1] else 10 val right = if (x != inputs[0].lastIndex) inputs[y][x + 1] else 10 val current = inputs[y][x] if (current < above && current < below && current < left && current < right) { lowPoints += FloorTile(x, y, current) } } } return lowPoints } data class FloorTile(val posX: Int, val posY: Int, val height: Int)
0
Kotlin
0
0
e0e5022238747e4b934cac0f6235b92831ca8ac7
2,711
advent-of-kotlin-2021
Apache License 2.0
src/Day07.kt
sebokopter
570,715,585
false
{"Kotlin": 38263}
import java.util.* const val TOTAL_DISK_SPACE = 70_000_000 const val REQUIRED_SPACE = 30_000_000 fun Stack<String>.toAbsolutePath(subDir: String = ""): String { val dirs = if (subDir.isNotBlank()) subList(1, this.size) + subDir else subList(1, this.size) return dirs.joinToString("/", "/") } fun main() { fun findAllDirs(input: List<String>): Set<String> { val dirs = mutableSetOf<String>() val currentDir = Stack<String>() input.forEach { line -> if (line.startsWith("$ ls ")) return@forEach if (line.startsWith("$ cd ")) { val (_, _, cdDir) = line if (cdDir == "..") currentDir.pop() else currentDir.push(cdDir) dirs.add(currentDir.toAbsolutePath()) } if (line.startsWith("dir")) { val (_, dirName) = line dirs.add((currentDir.toAbsolutePath(dirName))) } } return dirs } fun dirSize(input: List<String>, dir: String): Int { var size = 0 val currentDir = Stack<String>() input.forEachIndexed { index, line -> if (line.startsWith("$ cd ")) { val (_, _, cdDir) = line if (cdDir == "..") currentDir.pop() else currentDir.push(cdDir) } if (line.startsWith("$ ls") && currentDir.toAbsolutePath() == dir) { val lsOutputs = input.subList(index + 1, input.size).takeWhile { !it.startsWith("$") } size += lsOutputs.sumOf { lsOutput -> return@sumOf if (lsOutput.startsWith("dir")) { val (_, dirName) = lsOutput dirSize(input, currentDir.toAbsolutePath(dirName)) } else { val (fileSize) = lsOutput fileSize.toInt() } } } } return size } fun part1(input: List<String>): Int { val dirs = findAllDirs(input) val dirSizes = dirs.map { dir -> dir to dirSize(input, dir) } return dirSizes.sumOf { if (it.second < 100_000) it.second else 0 } } fun part2(input: List<String>): Int { val dirs = findAllDirs(input) val dirSizes = dirs.map { dir -> dir to dirSize(input, dir) } val currentFreeSpace = TOTAL_DISK_SPACE - dirSizes.first { (dirName, _) -> dirName == "/" }.second val spaceToBeFreed = REQUIRED_SPACE - currentFreeSpace return dirSizes.filter { it.second > spaceToBeFreed }.minOf { it.second } } val testInput = readInput("Day07_test") println("part1(testInput): " + part1(testInput)) println("part2(testInput): " + part2(testInput)) check(part1(testInput) == 95437) check(part2(testInput) == 24933642) val input = readInput("Day07") println("part1(input): " + part1(input)) println("part2(input): " + part2(input)) }
0
Kotlin
0
0
bb2b689f48063d7a1b6892fc1807587f7050b9db
3,031
advent-of-code-2022
Apache License 2.0
src/main/kotlin/_2023/Day07.kt
novikmisha
572,840,526
false
{"Kotlin": 145780}
package _2023 import Day import InputReader enum class HandPower(val power: Int, val validation: (cardOccurrences: Map<Char, Int>) -> Boolean) { FIVE_OF_A_KIND(6, ::fiveOfAKindValidation), FOUR_OF_A_KIND(5, ::fourOfAKindValidation), FULL_HOUSE(4, ::fullHouseValidation), THREE_OF_A_KIND(3, ::threeOfAKindValidation), TWO_PAIRS(2, ::twoPairValidation), ONE_PAIR(1, ::onePairValidation), HIGH_CARD(0, ::highCardValidation) } fun getCardOccurrences(hand: String) = hand.groupingBy { it }.eachCount() fun highCardValidation(cardOccurrences: Map<Char, Int>) = cardOccurrences.filter { it.value == 1 }.size == 5 fun onePairValidation(cardOccurrences: Map<Char, Int>): Boolean { val hasPair = cardOccurrences.filter { it.value == 2 }.size == 1 val allDifferent = cardOccurrences.filter { it.value == 1 }.size == 3 return hasPair && allDifferent } fun twoPairValidation(cardOccurrences: Map<Char, Int>): Boolean { val hasPair = cardOccurrences.filter { it.value == 2 }.size == 2 val allDifferent = cardOccurrences.filter { it.value == 1 }.size == 1 return hasPair && allDifferent } fun threeOfAKindValidation(cardOccurrences: Map<Char, Int>): Boolean { val hasThree = cardOccurrences.filter { it.value == 3 }.size == 1 val allDifferent = cardOccurrences.filter { it.value == 1 }.size == 2 return hasThree && allDifferent } fun fullHouseValidation(cardOccurrences: Map<Char, Int>): Boolean { val hasThree = cardOccurrences.filter { it.value == 3 }.size == 1 val hasPair = cardOccurrences.filter { it.value == 2 }.size == 1 return hasThree && hasPair } fun fourOfAKindValidation(cardOccurrences: Map<Char, Int>) = cardOccurrences.filter { it.value == 4 }.size == 1 fun fiveOfAKindValidation(cardOccurrences: Map<Char, Int>) = cardOccurrences.filter { it.value == 5 }.size == 1 data class Game( val hand: String, val bid: Int ) class Day07 : Day(2023, 7) { override val firstTestAnswer = 6440 override val secondTestAnswer = 5905 private fun solve(input: InputReader, cards: List<Char>, getHandPower: (hand: String) -> HandPower): Int { val games = input.asLines().map { line -> val (hand, bid) = line.split(" ") Game(hand, bid.toInt()) } val handPowersMap = games.associate { game -> game.hand to getHandPower(game.hand) } val gameComparator = Comparator<Game> { firstGame, secondGame -> val firstHandPower = handPowersMap[firstGame.hand]!! val secondHandPower = handPowersMap[secondGame.hand]!! if (firstHandPower != secondHandPower) { firstHandPower.power - secondHandPower.power } else { for (i in 0 until 5) { val firstGameCharIndex = cards.indexOf(firstGame.hand[i]) val secondGameCharIndex = cards.indexOf(secondGame.hand[i]) if (firstGameCharIndex != secondGameCharIndex) { return@Comparator secondGameCharIndex - firstGameCharIndex } } error("can't get here") } } return games.sortedWith(gameComparator).mapIndexed { index, game -> (index + 1) * game.bid }.sum() } override fun first(input: InputReader): Int { val cards = listOf( 'A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2', ) return solve(input, cards) { hand -> val cardOccurrences = getCardOccurrences(hand) HandPower.entries.firstOrNull { it.validation(cardOccurrences) } ?: error("$hand has no power") } } override fun second(input: InputReader): Int { val cards = listOf( 'A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J', ) fun getHandPower(hand: String): HandPower { return if (hand.any { it == 'J' }) { cards.dropLast(1).map { mimic -> val newHand = hand.replace("J", mimic.toString()) getHandPower(newHand) }.maxBy { it.power } } else { val cardOccurrences = getCardOccurrences(hand) HandPower.entries.firstOrNull { it.validation(cardOccurrences) } ?: error("$hand has no power") } } return solve(input, cards, ::getHandPower) } } fun main() { Day07().solve() }
0
Kotlin
0
0
0c78596d46f3a8bf977bf356019ea9940ee04c88
4,779
advent-of-code
Apache License 2.0
src/year2021/09/Day09.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2021.`09` import readInput private data class Point( val x: Int, val y: Int, ) { override fun toString(): String { return "[$x,$y]" } } private fun Point.neighbours(): Set<Point> { return setOf( Point(x = x, y = y + 1), Point(x = x, y = y - 1), Point(x = x + 1, y = y), Point(x = x - 1, y = y), ) } fun main() { fun parseMap(input: List<String>): Map<Point, Int> { val mutableMap = mutableMapOf<Point, Int>() input.forEachIndexed { y, line -> line.split("") .filter { it.isNotBlank() } .forEachIndexed { x, value -> mutableMap[Point(x, y)] = value.toInt() } } return mutableMap } fun findAllLowesPoints(input: Map<Point, Int>): Set<Point> { return input.keys.filter { currentPoint -> val currentValue = input[currentPoint]!! currentPoint .neighbours() .mapNotNull { input[it] } .all { neighbourValue -> currentValue < neighbourValue } } .toSet() } fun part1(input: List<String>): Int { val parsedMap = parseMap(input) return findAllLowesPoints(parsedMap) .sumOf { currentPoint -> val currentValue = parsedMap[currentPoint]!! currentValue + 1 } } fun recourciveFindAllBasins( point: Point, mapOfValues: Map<Point, Int>, processed: MutableSet<Point> ) { if (mapOfValues[point] == 9) return if (point in processed) return processed.add(point) point.neighbours() .filter { mapOfValues[it] != null } .forEach { currentPoint -> recourciveFindAllBasins(currentPoint, mapOfValues, processed) } } fun part2(input: List<String>): Int { val parsedMap = parseMap(input) val points = findAllLowesPoints(parsedMap) return points.map { val firstSet = mutableSetOf<Point>() recourciveFindAllBasins(it, parsedMap, firstSet) firstSet.size } .sorted() .takeLast(3) .reduce { acc, i -> acc * i } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 15) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
2,633
KotlinAdventOfCode
Apache License 2.0
src/Day13.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
sealed class Node: Comparable<Node> class NumberNode(val value: Int): Node() { override fun compareTo(other: Node): Int { return when (other) { is NumberNode -> this.value.compareTo(other.value) else -> ListNode(listOf(this)).compareTo(other) } } override fun toString(): String { return value.toString() } } class ListNode(): Node() { val values: MutableList<Node> = MutableList(0) { NumberNode(0) } constructor(items: List<Node>): this() { values.addAll(items) } override fun compareTo(other: Node): Int { return when (other) { is NumberNode -> this.compareTo(ListNode(listOf(other))) is ListNode -> (this.values zip other.values) .map { it.first.compareTo(it.second) } .find { it != 0 } ?: this.values.size.compareTo(other.values.size) } } override fun toString(): String { return "[${values.joinToString(",")}]" } } fun main() { fun parseNode(line: List<String>, cur: Int): Pair<Node, Int> { if (line[cur] == "[") { var nextInd = cur + 1 val node = ListNode() while (line[nextInd] != "]") { val result = parseNode(line, nextInd) node.values.add(result.first) nextInd = result.second } return node to nextInd + 1 } return NumberNode(line[cur].toInt()) to cur + 1 } fun parseNode(line: String): Node { val words = line .replace("[", ",[,") .replace("]", ",],") .removeSurrounding(",") .split(",") .filter { it.isNotEmpty() } return parseNode(words, 0).first } fun parseInput(input: List<String>): List<Pair<Node, Node>> { return input.filter { it.isNotEmpty() }.chunked(2).map { parseNode(it[0]) to parseNode(it[1]) } } fun part1(input: List<String>): Int { val pairs = parseInput(input) return pairs .mapIndexed { i, pair -> i + 1 to pair.first.compareTo(pair.second) } .filter { it.second < 0 } .sumOf { it.first } } fun part2(input: List<String>): Int { val packets = parseInput(input).flatMap { listOf(it.first, it.second) }.toMutableList() val divider1 = ListNode(listOf(ListNode(listOf(NumberNode(2))))) val divider2 = ListNode(listOf(ListNode(listOf(NumberNode(6))))) packets.add(divider1) packets.add(divider2) val sorted = packets.sortedWith { a, b -> a.compareTo(b) } return (sorted.indexOf(divider1) + 1) * (sorted.indexOf(divider2) + 1) } val testInput = readInputLines("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInputLines(13) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
2,632
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day08.kt
rromanowski-figure
573,003,468
false
{"Kotlin": 35951}
object Day08 : Runner<Int, Int>(8, 21, 8) { override fun part1(input: List<String>): Int { val height = input.size val treePatch = TreePatch(List(height) { input[it].toCharArray().map { c -> Tree(c.digitToInt()) } }) val width = treePatch.trees[0].size for (x in 0 until width) { for (y in 0 until height) { val otherTrees = treePatch.cross(x, y) val tree = treePatch.trees[x][y] tree.isVisible = tree.isVisible(otherTrees) } } return treePatch.trees.flatten().count { tree -> tree.isVisible ?: false } } override fun part2(input: List<String>): Int { val height = input.size val treePatch = TreePatch(List(height) { input[it].toCharArray().map { c -> Tree(c.digitToInt()) } }) val width = treePatch.trees[0].size for (x in 0 until width) { for (y in 0 until height) { val otherTrees = treePatch.cross(x, y) val tree = treePatch.trees[x][y] tree.scenicScore = tree.countVisibleTrees(otherTrees.left) * tree.countVisibleTrees(otherTrees.right) * tree.countVisibleTrees(otherTrees.top) * tree.countVisibleTrees(otherTrees.bottom) } } return treePatch.trees.flatten().maxOf { it.scenicScore } } data class TreePatch( val trees: List<List<Tree>> ) { fun cross(x: Int, y: Int) = Cross( left = trees[x].subList(0, y).asReversed(), right = trees[x].subList(y + 1, width), top = (0 until x).map { trees[it][y] }.asReversed(), bottom = (x + 1 until height).map { trees[it][y] } ) private val width by lazy { trees.first().size } private val height by lazy { trees.size } } data class Cross( val left: List<Tree>, val right: List<Tree>, val top: List<Tree>, val bottom: List<Tree> ) data class Tree( val height: Int, var isVisible: Boolean? = null, var scenicScore: Int = -1 ) { override fun toString(): String { return height.toString() } fun isVisible(cross: Cross): Boolean { return cross.left.all { it.height < height } || cross.right.all { it.height < height } || cross.top.all { it.height < height } || cross.bottom.all { it.height < height } } fun countVisibleTrees(list: List<Tree>): Int { return when { list.isEmpty() -> 0 list.none { it.height >= height } -> list.size else -> list.indexOfFirst { it.height >= height } + 1 } } } }
0
Kotlin
0
0
6ca5f70872f1185429c04dcb8bc3f3651e3c2a84
2,826
advent-of-code-2022-kotlin
Apache License 2.0
src/day7.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 7 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x.split(" ").let { Pair(it.first(), it.last().toInt()) } } val input = loadInput(DAY, false, transformer) println(input) println(solvePart1(input)) println(solvePart2(input)) } // Part 1 private fun solvePart1(input: List<Pair<String, Int>>): Int { val cards = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2').reversed() val comp = Comparator { c1: Pair<String, Int>, c2: Pair<String, Int> -> compareSameCards(c1.first, c2.first, cards) } val sorted = input.sortedWith(comp).sortedBy { getCardStrength(it.first) } return sorted.mapIndexed { i, card -> (i + 1) * card.second }.sum() } fun compareSameCards(card1: String, card2: String, cards: List<Char>): Int { var i = -1 while (true) { i++ if (card1[i] == card2[i]) { continue } return cards.indexOf(card1[i]) - cards.indexOf(card2[i]) } } fun getCardStrength(card: String): Int { val ranked = card.groupingBy { it }.eachCount().values return when { 5 in ranked -> 50 4 in ranked -> 40 3 in ranked && 2 in ranked -> 30 3 in ranked -> 20 ranked.groupingBy { it }.eachCount()[2] == 2 -> 10 2 in ranked -> 5 else -> 1 } } // Part 2 private fun solvePart2(input: List<Pair<String, Int>>): Int { val cards = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J').reversed() val comp = Comparator { c1: Pair<String, Int>, c2: Pair<String, Int> -> compareSameCards(c1.first, c2.first, cards) } val sorted = input.sortedWith(comp).sortedBy { getCardStrengthWithJokers(it.first) } return sorted.mapIndexed { i, card -> (i + 1) * card.second }.sum() } fun getCardStrengthWithJokers(card: String): Int { val ranked_ = card.groupingBy { it }.eachCount().toMutableMap() if ('J' in ranked_) { val j = ranked_.remove('J') if (j == 5) { ranked_['A'] = 5 } else { val rev = ranked_.entries.associate { (k, v) -> v to k }.toSortedMap().reversed() val u: Char = rev.firstEntry().value ranked_[u] = ranked_[u]!! + j!! } } val ranked = ranked_.values return when { 5 in ranked -> 50 4 in ranked -> 40 3 in ranked && 2 in ranked -> 30 3 in ranked -> 20 ranked.groupingBy { it }.eachCount()[2] == 2 -> 10 2 in ranked -> 5 else -> 1 } }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
2,746
aoc2023
MIT License
src/y2022/Day15.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.Pos import util.readInput import kotlin.math.abs object Day15 { data class SensorBeacon(val sensor: Pos, val beacon: Pos) { constructor(s: List<Int>, b: List<Int>) : this(s.toPair(), b.toPair()) fun manhattanDist(): Int { return sensor.manhattanDist(beacon) } } fun Pos.manhattanDist(other: Pos): Int { return abs(this.first - other.first) + abs(this.second - other.second) } fun <T> List<T>.toPair(): Pair<T, T> { val (first, second) = this return first to second } private fun parse(input: List<String>): List<SensorBeacon> { return input.map { line -> val s = line.substringAfter("x=").substringBefore(":").split((", y=")).map { it.toInt() } val b = line.substringAfterLast("x=").split((", y=")).map { it.toInt() } SensorBeacon(s, b) } } fun part1(input: List<String>, line: Int): Int { val sensorBeacons = parse(input) val coveredPositions = coveredPositionsInLine(sensorBeacons, line) val minX = coveredPositions.minOf { it.first } val maxX = coveredPositions.maxOf { it.last } var count = 0 for (i in minX..maxX) { if (coveredPositions.any { i in it }) { count++ } } return count - sensorBeacons.filter { it.beacon.second == line }.map { it.beacon }.distinct().count() } fun part2(input: List<String>, max: Int): Long { val sensorBeacons = parse(input) val coveredPositions = (0..max).map { line -> coveredPositionsInLine(sensorBeacons, line) } var y = -1 var yLine = listOf<IntRange>() coveredPositions.forEachIndexed { idx, line -> var mergedRanges = line for (i in 0..line.size) { val overlaps = mergedRanges.filter { overlapsOrTouches(mergedRanges[0], it) }.toSet() val newMerged = overlaps.minOf { it.first }..overlaps.maxOf { it.last } mergedRanges = mergedRanges.filter { it !in overlaps } + listOf(newMerged) } if (mergedRanges.size == 2) { y = idx yLine = mergedRanges return@forEachIndexed } } println(y) println(yLine) val x = yLine.minBy { it.first }.last + 1 return x * 4_000_000L + y } private fun coveredPositionsInLine( sensorBeacons: List<SensorBeacon>, line: Int, ) = sensorBeacons.map { val diff = it.manhattanDist() - abs(it.sensor.second - line) if (diff >= 0) { ((it.sensor.first - diff)..(it.sensor.first + diff)) } else { IntRange.EMPTY } }.filter { !it.isEmpty() } private fun overlapsOrTouches(range1: IntRange, range2: IntRange): Boolean { val extended = (range2.first - 1)..(range2.last + 1) return listOf( range1.first in extended, range1.last in extended, range2.first in range1 ).any { it } } } fun main() { val testInput = """ 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().split("\n") println("------Tests------") println(Day15.part1(testInput, 10)) println(Day15.part2(testInput, 20)) println("------Real------") val input = readInput("resources/2022/day15") println(Day15.part1(input, 2000000)) println(3405562L * 4000000L + 3246513L) println(Day15.part2(input, 4000000)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
4,386
advent-of-code
Apache License 2.0
src/Day11.kt
anisch
573,147,806
false
{"Kotlin": 38951}
data class Monkey( val name: Int, val items: MutableList<Long>, val op: (Long) -> Long, val divBy: Long, val test: (Long) -> Boolean, val success: Int, // if true: throw to val fail: Int, // if false: trow to var inspectCounter: Long = 0, ) fun getMonkeys(input: List<String>): List<Monkey> = input .chunked(7) .map { m -> val items = m[1].substringAfter(": ").split(", ").map { it.toLong() } val ops = m[2].substringAfter("old ").split(" ") val test = m[3].substringAfter("by ").toInt() Monkey( name = m[0].substringAfter(" ")[0].digitToInt(), items = items.toMutableList(), divBy = test.toLong(), op = { old -> val item = if (ops[1] == "old") old else ops[1].toLong() when (ops[0]) { "+" -> (old + item) "*" -> old * item else -> error("wtf???") } }, test = { item -> item % test == 0L }, success = m[4].substringAfter("monkey ").toInt(), fail = m[5].substringAfter("monkey ").toInt(), ) } fun inspection(monkeys: List<Monkey>, divider: Long, monkeyMod: Long? = null) { monkeys.forEach { monkey -> monkey.inspectCounter += monkey.items.size monkey.items.forEach { item -> var worry = monkey.op(item) / divider monkeyMod?.let { worry %= monkeyMod } val test = monkey.test(worry) if (test) monkeys[monkey.success].items += worry else monkeys[monkey.fail].items += worry } monkey.items.clear() } } fun main() { fun part1(input: List<String>): Long { val monkeys = getMonkeys(input) repeat(20) { inspection(monkeys, 3) } val (a, b) = monkeys.sortedByDescending { m -> m.inspectCounter } return a.inspectCounter * b.inspectCounter } fun part2(input: List<String>): Long { val monkeys = getMonkeys(input) val monkeyMod = monkeys .map { m -> m.divBy } .reduce { a, b -> a * b } repeat(10_000) { inspection(monkeys, 1, monkeyMod) } val (a, b) = monkeys.sortedByDescending { m -> m.inspectCounter } return a.inspectCounter * b.inspectCounter } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") val input = readInput("Day11") check(part1(testInput) == 10605L) println(part1(input)) check(part2(testInput) == 2713310158L) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
2,718
Advent-of-Code-2022
Apache License 2.0
src/Day08/Day08.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
fun main() { fun preprocess(input: List<String>): List<Pair<List<String>, List<String>>> { fun preprocessSingle(input: String): Pair<List<String>, List<String>> { val split = input.split('|') val fst = split[0].split(' ').filter { it.isNotBlank() } val snd = split[1].split(' ').filter { it.isNotBlank() } return Pair(fst, snd) } return input.map { preprocessSingle(it) } } fun part1(input: List<Pair<List<String>, List<String>>>): Int { return input.map { it.second }.sumOf { it.count { e -> listOf(2, 3, 4, 7).contains(e.length) } } } fun part2(input: List<Pair<List<String>, List<String>>>): Int { fun processSingle(line: Pair<List<String>, List<String>>): Int { val second = line.second.map { it.toSet() } val all = line.first + line.second val one = all.filter { it.length == 2 }[0].toSet() val four = all.filter { it.length == 4 }[0].toSet() val known = mapOf(Pair(2, "1"), Pair(3, "7"), Pair(4, "4"), Pair(7, "8")) var res = "" for (e in second) { res += if (e.size in known.keys) { known[e.size] } else if (e.size == 5) { if (e.intersect(one).size == 2) { "3" } else if (e.intersect(four).size == 2) { "2" } else { "5" } } else { if (e.intersect(one).size == 1) { "6" } else if (e.intersect(four).size == 4) { "9" } else { "0" } } } return res.toInt() } return input.sumOf { processSingle(it) } } val testInput = preprocess(readInput(8, true)) val input = preprocess(readInput(8)) check(part1(testInput) == 26) println(part1(input)) check(part2(testInput) == 61229) println(part2(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
2,151
advent-of-code-2021
Apache License 2.0
src/Day12.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { data class Node(val i: Int, val j: Int, val char: Char, var cost: Int) { val height = when (char) { 'S' -> 'a' 'E' -> 'z' else -> char }.code } fun exists(i: Int, j: Int, map: Array<Node>): Boolean { return map.any { it.i == i && it.j == j } } fun node(i: Int, j: Int, map: Array<Node>): Node { return map.first { it.i == i && it.j == j } } fun dijkstra(parent: Node, node: Node, map: Array<Node>) { if (node.height - parent.height > 1) { return } val cost = parent.cost + 1 if (cost >= node.cost) { return } node.cost = cost if (exists(node.i - 1, node.j, map)) { dijkstra(node, node(node.i - 1, node.j, map), map) } if (exists(node.i + 1, node.j, map)) { dijkstra(node, node(node.i + 1, node.j, map), map) } if (exists(node.i, node.j - 1, map)) { dijkstra(node, node(node.i, node.j - 1, map), map) } if (exists(node.i, node.j + 1, map)) { dijkstra(node, node(node.i, node.j + 1, map), map) } } fun analyse(input: List<String>) = input .mapIndexed { row, line -> line .toCharArray() .mapIndexed { column, char -> Node(row, column, char, Int.MAX_VALUE) } } .flatten() .toTypedArray() fun part1(input: List<String>): Int { val map = analyse(input) map .filter { it.char == 'S' } .forEach { node -> dijkstra(Node(-1, -1, 'S', -1), node, map) } val end = map.first { it.char == 'E' } return end.cost } fun part2(input: List<String>): Int { val map = analyse(input) map .filter { it.char == 'a' || it.char == 'S' } .forEach { node -> dijkstra(Node(-1, -1, 'S', -1), node, map) } val end = map.first { it.char == 'E' } return end.cost } // test if implementation meets criteria from the description, like: val testInputExample = readInput("Day12_example") check(part1(testInputExample) == 31) check(part2(testInputExample) == 29) val testInput = readInput("Day12_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
2,399
aoc-2022-in-kotlin
Apache License 2.0
src/day3/Day03.kt
ousa17
573,435,223
false
{"Kotlin": 8095}
package day3 import readInput fun main() { val input = readInput("day3/Day03") part1(input) part2(input) } private fun part2(input: List<String>) { val badges = input.windowed(3, step = 3).map { findBadge(it) } val mapMyList = getMapCharPriority() val sumPriority = badges.map { input -> mapMyList.filter { it.key == input.first() }.values.first() }.sum() println(sumPriority) } fun findBadge(list: List<String>): String { val item1 = list.get(0) val item2 = list.get(1) val item3 = list.get(2) return item1.filter { item2.contains(it) && item3.contains(it) } } private fun part1(input: List<String>) { val mapMyList = getMapCharPriority() val mapSplitted = input.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2, it.length)) } val listWrong = mapSplitted.map { twoString -> twoString.first.filter { twoString.second.contains(it) } } val sumPriority = listWrong.map { input -> mapMyList.filter { it.key == input.first() }.values.first() }.sum() println(sumPriority) } private fun getMapCharPriority(): Map<Char, Int> { val alphabetMajuscule = ('A'..'Z').toMutableList() val alphabetMinuscule = ('a'..'z').toMutableList() var map: Map<Char, Int> = emptyMap() for (i in 1..26) { map = map.plus(alphabetMinuscule[i - 1] to i) } for (i in 27..52) { map = map.plus(alphabetMajuscule[i - 27] to i) } return map }
0
Kotlin
0
0
aa7f2cb7774925b7e88676a9ca64ca9548bce5b2
1,492
advent-day-1
Apache License 2.0
Advent-of-Code-2023/src/Day22.kt
Radnar9
726,180,837
false
{"Kotlin": 93593}
private const val AOC_DAY = "Day22" private const val INPUT_FILE = AOC_DAY private data class Brick(val minX: Int, val maxX: Int, val minY: Int, val maxY: Int, val minZ: Int, val maxZ: Int) { fun down(): Brick = Brick(minX, maxX, minY, maxY, minZ - 1, maxZ - 1) fun supports(b: Brick) = minX <= b.maxX && maxX >= b.minX && minY <= b.maxY && maxY >= b.minY && minZ <= b.maxZ - 1 && maxZ >= b.minZ - 1 fun isUnsupported(stack: List<Brick>, disintegrated: Set<Brick> = emptySet()) = minZ > 1 && stack.none { it.supports(this) && it !== this && it !in disintegrated } companion object { operator fun <T> List<T>.component6() = this[5] fun parse(s: String): Brick { val (x1, y1, z1, x2, y2, z2) = s.split(',', '~').map { it.toInt() } return Brick(minOf(x1, x2), maxOf(x1, x2), minOf(y1, y2), maxOf(y1, y2), minOf(z1, z2), maxOf(z1, z2)) } } } private class BrickStack(input: List<String>) { val bricks = buildList<Brick> { for (brick in input.map { Brick.parse(it) }.sortedBy { it.minZ }) { var pos = brick while (pos.isUnsupported(this)) pos = pos.down() add(pos) } sortBy { it.minZ } } fun canDisintegrate(disintegratedBrick: Brick): Boolean { val disintegrated = setOf(disintegratedBrick) return bricks.none { it.isUnsupported(bricks, disintegrated) } } fun countFalls(initial: Brick): Int { val work = mutableListOf(initial) val disintegrated = mutableSetOf(initial) while (work.isNotEmpty()) { val current = work.removeLast() for (brick in bricks) { // If brick is below other, it can't possibly fall if (brick.maxZ < current.minZ) continue // Brick can't be directly supported by any remaining since the stack is sorted by Z if (brick.minZ > current.maxZ + 1) break if (brick !in disintegrated && brick.isUnsupported(bricks, disintegrated)) { disintegrated.add(brick) work.add(brick) } } } return disintegrated.size - 1 } } fun main() { fun part1(input: List<String>): Int { val stack = BrickStack(input) return stack.bricks.count { stack.canDisintegrate(it) } } fun part2(input: List<String>): Int { val stack = BrickStack(input) return stack.bricks.sumOf { stack.countFalls(it) } } val input = readInputToList(INPUT_FILE) part1(input).println() part2(input).println() } /* // Python solution from collections import deque bricks = [list(map(int, line.replace("~", ",").split(","))) for line in open(0)] bricks.sort(key=lambda brick: brick[2]) def overlaps(a, b): return max(a[0], b[0]) <= min(a[3], b[3]) and max(a[1], b[1]) <= min(a[4], b[4]) for index, brick in enumerate(bricks): max_z = 1 for check in bricks[:index]: if overlaps(brick, check): max_z = max(max_z, check[5] + 1) brick[5] -= brick[2] - max_z brick[2] = max_z bricks.sort(key=lambda brick: brick[2]) k_supports_v = {i: set() for i in range(len(bricks))} v_supports_k = {i: set() for i in range(len(bricks))} for j, upper in enumerate(bricks): for i, lower in enumerate(bricks[:j]): if overlaps(lower, upper) and upper[2] == lower[5] + 1: k_supports_v[i].add(j) v_supports_k[j].add(i) total = 0 # Part 1 for i in range(len(bricks)): if all(len(v_supports_k[j]) >= 2 for j in k_supports_v[i]): total += 1 # Part 2 for i in range(len(bricks)): q = deque(j for j in k_supports_v[i] if len(v_supports_k[j]) == 1) falling = set(q) falling.add(i) while q: j = q.popleft() for k in k_supports_v[j] - falling: if v_supports_k[k] <= falling: q.append(k) falling.add(k) total += len(falling) - 1 print(total) */
0
Kotlin
0
0
e6b1caa25bcab4cb5eded12c35231c7c795c5506
4,084
Advent-of-Code-2023
Apache License 2.0
src/day11/Day11.kt
seastco
574,758,881
false
{"Kotlin": 72220}
package day11 import readText data class Monkey(var items: MutableList<Long>, val operation: List<String>, val divisor: Long, val trueMonkey: Int, val falseMonkey: Int) { var inspected = 0L fun getWorryLevel(item: Long): Long { val operator = operation[0] val number = if (operation[1] == "old") item else operation[1].toLong() return when (operator) { "+" -> item + number "*" -> item * number else -> 0L } } } private fun parseInput(input: String): Pair<List<Monkey>, Long> { val monkeyInput = input.split("\n\n") val monkeys = monkeyInput.map { val monkeyDescription = it.split("\n") val items = monkeyDescription[1] .substringAfter(":").trim() .split(",") .map { item -> item.trim().toLong() }.toMutableList() val operation = monkeyDescription[2] .split(" ") .takeLast(2) val divisor = monkeyDescription[3].split(" ").last().toLong() val trueMonkey = monkeyDescription[4].split(" ").last().toInt() val falseMonkey = monkeyDescription[5].split(" ").last().toInt() Monkey(items, operation, divisor, trueMonkey, falseMonkey) } val lcm = monkeys.map { it.divisor }.reduce { acc, bigInteger -> acc * bigInteger } return monkeys to lcm } private fun part1(input: String): Long { val (monkeys) = parseInput(input) repeat(20) { monkeys.forEach { for (i in it.items.indices) { val item = it.items[i] val worryLevel = it.getWorryLevel(item) / 3 val nextMonkey = if (worryLevel % it.divisor == 0L) it.trueMonkey else it.falseMonkey monkeys[nextMonkey].items.add(worryLevel) } it.inspected += it.items.size it.items.clear() } } return monkeys .sortedByDescending { it.inspected } .let{ it[0].inspected * it[1].inspected } } private fun part2(input: String): Long { val (monkeys, lcm) = parseInput(input) repeat(10000) { monkeys.forEach { for (i in it.items.indices) { val item = it.items[i] val worryLevel = it.getWorryLevel(item) % lcm val nextMonkey = if (worryLevel % it.divisor == 0L) it.trueMonkey else it.falseMonkey monkeys[nextMonkey].items.add(worryLevel) } it.inspected += it.items.size it.items.clear() } } return monkeys .sortedByDescending { it.inspected } .take(2) .let{ it[0].inspected * it[1].inspected } } fun main() { println(part1(readText("day11/test"))) println(part1(readText("day11/input"))) println(part2(readText("day11/test"))) println(part2(readText("day11/input"))) }
0
Kotlin
0
0
2d8f796089cd53afc6b575d4b4279e70d99875f5
2,866
aoc2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-07.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, "07-input") val test1 = readInputLines(2023, "07-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Int { val hands = input.map { line -> line.split(" ").let { Hand(it[0], it[1].toInt()) } } return hands.sorted().withIndex().sumOf { (index, hand) -> (index + 1) * hand.bid } } private fun part2(input: List<String>): Int { val hands = input.map { line -> line.split(" ").let { HandWithJoker(it[0], it[1].toInt()) } } return hands.sorted().withIndex().sumOf { (index, hand) -> (index + 1) * hand.bid } } private enum class HandType { Five, Four, FullHouse, Three, TwoPair, Pair, HighCard } private data class Hand(val cards: String, val bid: Int): Comparable<Hand> { companion object { val labels = listOf('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2') } private val type: HandType init { val counts = cards.groupingBy { it }.eachCount().entries.sortedByDescending { it.value } type = when { counts.size == 1 -> HandType.Five counts[0].value == 4 -> HandType.Four counts[0].value == 3 && counts[1].value == 2 -> HandType.FullHouse counts[0].value == 3 -> HandType.Three counts[0].value == 2 && counts[1].value == 2 -> HandType.TwoPair counts[0].value == 2 -> HandType.Pair else -> HandType.HighCard } } override fun compareTo(other: Hand): Int { if (type != other.type) return other.type.ordinal - type.ordinal cards.forEachIndexed { index, c -> if (c != other.cards[index]) return labels.indexOf(other.cards[index]) - labels.indexOf(c) } return 0 } } private data class HandWithJoker(val cards: String, val bid: Int): Comparable<HandWithJoker> { companion object { val labels = listOf('A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J') } private val type: HandType init { val jokers = cards.count { it == 'J' } val counts = cards.groupingBy { it }.eachCount().let { it - 'J' }.entries.sortedByDescending { it.value } type = when { jokers == 5 || counts[0].value + jokers == 5 -> HandType.Five counts[0].value + jokers == 4 -> HandType.Four counts[0].value == 3 && counts[1].value == 2 -> HandType.FullHouse counts[0].value == 2 && counts[1].value == 2 && jokers == 1 -> HandType.FullHouse counts[0].value + jokers == 3 -> HandType.Three counts[0].value == 2 && counts[1].value == 2 -> HandType.TwoPair counts[0].value + jokers == 2 -> HandType.Pair else -> HandType.HighCard } } override fun compareTo(other: HandWithJoker): Int { if (type != other.type) return other.type.ordinal - type.ordinal cards.forEachIndexed { index, c -> if (c != other.cards[index]) return labels.indexOf(other.cards[index]) - labels.indexOf(c) } return 0 } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,405
advent-of-code
MIT License
src/days/day7/Day7.kt
Riven-Spell
113,698,657
false
{"Kotlin": 25729}
package days.day7 import kotlin.math.abs data class Program(val Name: String, val Weight: Int, val Links: List<String>) val nregex = Regex("[a-z]+") val wregex = Regex("\\(\\d+\\)") val weregex = Regex("\\d+") val lregex = Regex("->") fun day7p1(s: String) : String { var programs = HashMap<String,Program>() var linkbacks = HashMap<String,MutableList<String>>() return toBase(linkbacks, s.split("\n").map { prog -> val links: List<String> = if(lregex.containsMatchIn(prog)) nregex.findAll(lregex.split(prog)[1]).map{it.value}.toList() else listOf() val name: String = nregex.find(lregex.split(prog)[0])!!.value val weight: Int = weregex.find(wregex.find(prog)!!.value)!!.value.toInt() Program(name,weight,links) }.map { prog -> programs[prog.Name] = prog linkbacks[prog.Name] = mutableListOf() prog }.map { prog -> prog.Links.forEach { linked -> linkbacks[linked]!!.add(prog.Name) } prog.Name }.first()) } fun Program.findTotalWeight(programs: HashMap<String,Program>): Int = this.Weight + this.Links.map { programs[it]!!.findTotalWeight(programs) }.sum() data class WeightTree(val Name: String, val Weight:Int, val Subs:List<WeightTree>) { fun CorrectWeight(): Int { val wts = HashMap<Int,Int>() Subs.forEach { if(wts.contains(it.Weight)) { wts[it.Weight] = wts[it.Weight]!! + 1 } else { wts[it.Weight] = 1 } } return wts.keys.toList()[wts.values.indexOf(wts.values.max()!!)] } fun FindWrong(): WeightTree { val cWeight = CorrectWeight() val icw = Subs.find { it.Weight != cWeight } return if(icw == null) { this } else { icw.FindWrong() } } } fun Program.buildWeightTree(programs: HashMap<String,Program>): WeightTree { val w = this.findTotalWeight(programs) val sw = this.Links.map { programs[it]!!.buildWeightTree(programs) } return WeightTree(this.Name, w, sw) } fun day7p2(s: String) : String { var programs = HashMap<String,Program>() var linkbacks = HashMap<String,MutableList<String>>() val base = toBase(linkbacks, s.split("\n").map { prog -> val links: List<String> = if(lregex.containsMatchIn(prog)) nregex.findAll(lregex.split(prog)[1]).map{it.value}.toList() else listOf() val name: String = nregex.find(lregex.split(prog)[0])!!.value val weight: Int = weregex.find(wregex.find(prog)!!.value)!!.value.toInt() Program(name,weight,links) }.map { prog -> programs[prog.Name] = prog linkbacks[prog.Name] = mutableListOf() prog }.map { prog -> prog.Links.forEach { linked -> linkbacks[linked]!!.add(prog.Name) } prog.Name }.first()) val bwt = programs[base]!!.buildWeightTree(programs) val iwt = bwt.FindWrong() val cwt = programs[linkbacks[iwt.Name]!![0]]!!.buildWeightTree(programs) return (programs[iwt.Name]!!.Weight - abs(iwt.Weight - cwt.CorrectWeight())).toString() } fun toBase(linkbacks: HashMap<String,MutableList<String>>, name:String): String = if(linkbacks[name]!!.isEmpty()) name else { linkbacks[name]!!.map { toBase(linkbacks, it) }.first() }
0
Kotlin
0
1
dbbdb390a0addee98c7876647106af208c3d9bc7
3,331
Kotlin-AdventOfCode-2017
MIT License
src/main/kotlin/aoc23/Day02.kt
tom-power
573,330,992
false
{"Kotlin": 254717, "Shell": 1026}
package aoc23 import aoc23.Day02Domain.Bag import aoc23.Day02Domain.Cube import aoc23.Day02Domain.Cube.* import aoc23.Day02Domain.CubeGame import aoc23.Day02Domain.Round import aoc23.Day02Parser.toCubeGame import aoc23.Day02Solution.part1Day02 import aoc23.Day02Solution.part2Day02 import common.Collections.product import common.Misc.capitalise import common.Year23 object Day02 : Year23 { fun List<String>.part1(): Int = part1Day02() fun List<String>.part2(): Int = part2Day02() } object Day02Solution { private val part1Bag = Bag( cubeCount = mapOf( Red to 12, Green to 13, Blue to 14, ) ) fun List<String>.part1Day02(): Int = map { it.toCubeGame() }.filter { it.isPossibleWith(part1Bag) } .sumOf { it.id } fun List<String>.part2Day02(): Int = map { it.toCubeGame().smallestBagNeeded() } .sumOf { it.powerOfCubes() } } object Day02Domain { data class CubeGame( val id: Int, val rounds: List<Round> ) { fun isPossibleWith(bag: Bag): Boolean = rounds.all { round -> bag.hasEnoughCubesFor(round) } fun smallestBagNeeded(): Bag = Bag( cubeCount = Cube.entries .associateWith { cube -> rounds.maxOf { it.countFor(cube) } } ) } data class Bag( override val cubeCount: Map<Cube, Int> ) : HasCubeCount data class Round( override val cubeCount: Map<Cube, Int> ) : HasCubeCount interface HasCubeCount { val cubeCount: Map<Cube, Int> fun countFor(key: Cube): Int = (this.cubeCount[key] ?: 0) fun hasEnoughCubesFor(other: HasCubeCount): Boolean = cubeCount.all { (cube, count) -> count >= other.countFor(cube) } fun powerOfCubes(): Int = cubeCount.values.toList().product() } enum class Cube { Green, Red, Blue } } object Day02Parser { // Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green fun String.toCubeGame(): CubeGame = this.split(":").let { game -> CubeGame( id = game.first().filter { it.isDigit() }.toInt(), rounds = game.last().split(";") .map { round -> Round( cubeCount = round.split(",") .map { cubeCount -> val cubeName = cubeCount.filter { it.isLetter() }.capitalise() val count = cubeCount.filter { it.isDigit() }.toInt() Cube.valueOf(cubeName) to count }.toMap() ) } ) } }
0
Kotlin
0
0
baccc7ff572540fc7d5551eaa59d6a1466a08f56
2,951
aoc
Apache License 2.0
advent-of-code-2023/src/Day13.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
import kotlin.math.min private const val DAY = "Day13" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 405 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 400 measureAnswer { part2(input()) } } } private fun part1(input: List<List<String>>): Int = input.sumOf { calculateMirrorPosition(it) } private fun part2(input: List<List<String>>): Int = input.sumOf { calculateMirrorPosition(it, smudges = 1) } private fun calculateMirrorPosition(pattern: List<String>, smudges: Int = 0): Int { val verticalPosition = findMirrorPosition(pattern, smudges) val horizontalPosition = if (verticalPosition == 0) findMirrorPosition(pattern.columns(), smudges) else 0 return horizontalPosition + verticalPosition * 100 } private fun List<String>.columns(): List<String> = buildList { for (i in first().indices) { val column = buildString { for (line in this@columns) append(line[i]) } add(column) } } private fun findMirrorPosition(pattern: List<String>, requiredSmudges: Int): Int { for (i in 0..<pattern.lastIndex) { var foundSmudges = 0 for (diff in 0..min(i, pattern.size - i - 2)) { foundSmudges += pattern[i - diff] countDiffWith pattern[i + 1 + diff] if (foundSmudges > requiredSmudges) break } if (foundSmudges == requiredSmudges) return i + 1 } return 0 } private infix fun String.countDiffWith(other: String): Int = indices.count { i -> this[i] != other[i] } private fun readInput(name: String) = readText(name).split("\n\n").map { it.lines() }
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
1,711
advent-of-code
Apache License 2.0
src/Day04.kt
niltsiar
572,887,970
false
{"Kotlin": 16548}
fun main() { fun part1(input: List<String>): Int { return input.getPairsOfRanges() .map { ranges -> when { ranges.first.first in ranges.second && ranges.first.last in ranges.second -> 1 ranges.second.first in ranges.first && ranges.second.last in ranges.first -> 1 else -> 0 } }.sum() } fun part2(input: List<String>): Int { return input.getPairsOfRanges() .count { ranges -> ranges.first overlaps ranges.second } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun List<String>.getPairsOfRanges(): List<Pair<IntRange, IntRange>> { return map { line -> val ranges = line.split(',') .map { section -> section.split('-') } .map { limit -> limit[0].toInt()..limit[1].toInt() } ranges[0] to ranges[1] } } private infix fun IntRange.overlaps(other: IntRange): Boolean { return first <= other.last && other.first <= last }
0
Kotlin
0
0
766b3e168fc481e4039fc41a90de4283133d3dd5
1,352
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/days/Day6.kt
hughjdavey
159,955,618
false
null
package days class Day6 : Day(6) { private val coords = toNamedCoords(inputList) override fun partOne(): Int { println("// Day 6 Part 1 takes about 6 seconds...") val allGridCoords = (0..maxX(coords.values)).flatMap { x -> (0..maxY(coords.values)).map { y -> Pair(x, y) } } return allGridCoords.asSequence().map { toClosestName(it) to it }.groupingBy { it.first } .aggregate { _, accumulator: Set<Pair<Int, Int>>?, element, _ -> accumulator?.plus(element.second) ?: setOf(element.second) } .filter { it.value.none { c -> isInfinite(c) } } .map { it.value.size }.max() ?: 0 } private fun isInfinite(gridCoord: Pair<Int, Int>) : Boolean { return gridCoord.first == 0 || gridCoord.first == maxX(coords.values) || gridCoord.second == 0 || gridCoord.second == maxY(coords.values) } private fun toClosestName(gridCoord: Pair<Int, Int>): String { val baz = coords.map { namedCoord -> namedCoord.key to manhattanDistance(namedCoord.value, gridCoord) }.sortedBy { it.second } return if (baz.count { it.second == baz.first().second } > 1) "." else baz.first().first } override fun partTwo(): Int { val allGridCoords = (0..maxX(coords.values)).flatMap { x -> (0..maxY(coords.values)).map { y -> Pair(x, y) } } return allGridCoords.count { coord -> val distancesFromCoords = coords.map { entry -> Pair(entry.key, manhattanDistance(entry.value, coord)) }.sortedBy { it.second } distancesFromCoords.map { it.second }.sum() < 10000 } } companion object { fun toNamedCoords(input: List<String>): Map<String, Pair<Int, Int>> { return input.map { it.split(',') } .map { it.map { s -> s.trim() } } .mapIndexed { index, splits -> getCoordName(index) to Pair(splits[0].toInt(), splits[1].toInt()) } .toMap() } fun manhattanDistance(c1: Pair<Int, Int>, c2: Pair<Int, Int>): Int { return diff(c1.first, c2.first) + diff(c1.second, c2.second) } fun maxX(coords: Collection<Pair<Int, Int>>) = coords.sortedBy { it.first }.last().first fun maxY(coords: Collection<Pair<Int, Int>>) = coords.sortedBy { it.second }.last().second private fun diff(x: Int, y: Int): Int { return Math.max(x, y) - Math.min(x, y) } private fun getCoordName(index: Int): String { val repeatCount = (index / 26) + 1 return ('A' + (index % 26)).toString().repeat(repeatCount) } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
2,643
aoc-2018
Creative Commons Zero v1.0 Universal
y2022/src/main/kotlin/adventofcode/y2022/Day15.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2022 import adventofcode.io.AdventSolution import adventofcode.util.vector.Vec2 import kotlin.math.abs object Day15 : AdventSolution(2022, 15, "Beacon Exclusion Zone") { override fun solvePartOne(input: String) = solvePartOne(input, 2_000_000) fun solvePartOne(input: String, y: Int): Int { val signals = parse(input).toList() val intervals = signals.map { it.lineAt(y) } .filter { it.first <= it.last } .sortedBy { it.first } val beacons = signals.mapNotNull { it.beaconAt(y) }.distinct() val cuttingPoints = intervals.flatMap { listOf(it.first, it.last + 1) } val slices = intervals.flatMap { range -> val points = cuttingPoints.filter { it in range }.sorted() + (range.last + 1) points.zipWithNext(Int::until) } .distinct() return slices.sumOf { it.last - it.first + 1 } - beacons.count() } override fun solvePartTwo(input: String): Long { //rotate the grid 45 degrees. now all areas are squares! val areas = parse(input).map { Diamond(it.sensor, it.dist).rotate() }.toList() //sort all x- and y-boundary values val xs = areas.flatMap { (a, b) -> listOf(a.x, b.x + 1) }.toSortedSet().toList() val ys = areas.flatMap { (a, b) -> listOf(a.y, b.y + 1) }.toSortedSet().toList() //use indices instead of the huge actual values val ixs = xs.withIndex().associate { it.value to it.index } val iys = ys.withIndex().associate { it.value to it.index } //draw a small grid using the indices val grid = Array(ys.size - 1) { BooleanArray(xs.size - 1) { false } } //for each area, cross out the covered indices in the grid areas.forEach { a -> (iys.getValue(a.topLeft.y) until iys.getValue(a.bottomRight.y + 1)).forEach { y -> (ixs.getValue(a.topLeft.x) until ixs.getValue(a.bottomRight.x + 1)).forEach { x -> grid[y][x] = true } } } //uncovered 1x1 areas. only one is correct, the others will be outside the original scanning boundary val candidates = (0 until ys.lastIndex).asSequence() .flatMap { iy -> (0 until xs.lastIndex).map { ix -> Vec2(ix, iy) } } .filter { (ix, _) -> xs[ix] + 1 == xs[ix + 1] } //1 wide .filter { (_, iy) -> ys[iy] + 1 == ys[iy + 1] } //1 high .filter { (ix, iy) -> !grid[iy][ix] } //uncovered //back to original coordinates val transformed = candidates.map { Vec2(xs[it.x], ys[it.y]) } .map { it.fromRotated() } //filter incorrect candidates val boundary = 4_000_000 val answer = transformed.single { it.x in 0..boundary && it.y in 0..boundary } //tuning frequency return answer.x * 4_000_000L + answer.y } } private fun parse(input: String): Sequence<Signal> { val regex = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""") return input.lineSequence().map { regex.matchEntire(it)!!.groupValues.drop(1).map(String::toInt) } .map { (sx, sy, bx, by) -> Signal(Vec2(sx, sy), Vec2(bx, by)) } } private data class Signal(val sensor: Vec2, val beacon: Vec2) { val dist = sensor.distance(beacon) fun lineAt(y: Int): IntRange { val distanceToLine = abs(sensor.y - y) val remainder = dist - distanceToLine return (sensor.x - remainder)..(sensor.x + remainder) } fun beaconAt(y: Int): Int? = if (beacon.y == y) beacon.x else null } private data class Diamond(val center: Vec2, val radius: Int) { fun rotate() = Area( center.copy(y = center.y - radius).toRotated(), center.copy(y = center.y + radius).toRotated() ) } private data class Area(val topLeft: Vec2, val bottomRight: Vec2) //rotate the axes CCW 45 degrees (and scale) private fun Vec2.toRotated() = Vec2(x + y, y - x) //rotate the axes CW 45 degrees (and rescale) private fun Vec2.fromRotated() = Vec2((x - y) / 2, (y + x) / 2)
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
4,175
advent-of-code
MIT License
src/Day15.kt
thorny-thorny
573,065,588
false
{"Kotlin": 57129}
import kotlin.math.abs data class Beacon(val x: Int, val y: Int) data class Sensor(val x: Int, val y: Int, val beacon: Beacon) { fun coverRangeAtY(rangeY: Int): IntRange { val distance = abs(x - beacon.x) + abs(y - beacon.y) val yCorrection = abs(y - rangeY) val left = x - distance + yCorrection val right = x + distance - yCorrection return left..right } } fun main() { fun parseLine(line: String): Sensor { val match = Regex("""Sensor at x=(-?\d+), y=(-?\d+): closest beacon is at x=(-?\d+), y=(-?\d+)""").matchEntire(line) ?: throw Exception("Unknown format") val (sensorX, sensorY, beaconX, beaconY) = match.destructured val beacon = Beacon(beaconX.toInt(), beaconY.toInt()) return Sensor(sensorX.toInt(), sensorY.toInt(), beacon) } fun part1(input: List<String>, y: Int): Int { val sensors = input .map { val sensor = parseLine(it) val range = sensor.coverRangeAtY(y) sensor to range } .filter { !it.second.isEmpty() } val left = sensors.minOf { it.second.first } val right = sensors.maxOf { it.second.last } return (left..right).count { x -> val inRange = sensors.any { x in it.second } when { inRange -> { val isSensor = sensors.any { it.first.x == x && it.first.y == y } val isBeacon = sensors.any { it.first.beacon.x == x && it.first.beacon.y == y } !isSensor && !isBeacon } else -> false } } } fun part2(input: List<String>, searchRange: IntRange): Long { val sensors = input.map(::parseLine) return searchRange.firstNotNullOf { y -> var x = searchRange.first while (x <= searchRange.last) { val range = sensors.firstNotNullOfOrNull { val range = it.coverRangeAtY(y) when { range.isEmpty() || x !in range -> null else -> range } } when (range) { null -> return@firstNotNullOf x.toLong() * 4000000L + y.toLong() else -> x = range.last + 1 } } null } } val testInput = readInput("Day15_test") check(part1(testInput, 10) == 26) check(part2(testInput, 0..20) == 56000011L) val input = readInput("Day15") println(part1(input, 2000000)) println(part2(input, 0..4000000)) }
0
Kotlin
0
0
843869d19d5457dc972c98a9a4d48b690fa094a6
2,699
aoc-2022
Apache License 2.0
src/day22/Code.kt
fcolasuonno
221,697,249
false
null
package day22 import java.io.File import java.util.* import kotlin.math.abs fun main() { val name = if (false) "test.txt" else "input.txt" val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } private val xRange = 0..34 private val yRange = 0..28 data class Node(val x: Int, val y: Int, val size: Int, val used: Int, val avail: Int, val usePercent: Int) data class SimpleNode(val pos: Pair<Int, Int>, val size: Int, val used: Int) data class NodeMap(val empty: SimpleNode, val goal: SimpleNode, val steps: Int = 0) { var grid: SortedSet<SimpleNode> = sortedSetOf(compareBy<SimpleNode> { it.pos.first }.thenBy { it.pos.second }) fun candidates() = setOf(empty.pos.copy(first = empty.pos.first - 1), empty.pos.copy(first = empty.pos.first + 1), empty.pos.copy(second = empty.pos.second - 1), empty.pos.copy(second = empty.pos.second + 1)) .filter { it.first in xRange && it.second in yRange }.let { newEmptyPositions -> grid.filter { it.pos in newEmptyPositions } }.mapNotNull { newNode -> if (empty.size >= newNode.used) { val newEmptyNode = newNode.copy(used = 0) val simpleNode = empty.copy(used = newNode.used) this.copy(empty = newEmptyNode, goal = if (newEmptyNode.pos == goal.pos) simpleNode else goal, steps = steps + 1).also { it.grid.addAll(grid.filter { it.pos != newNode.pos && it.pos != empty.pos } + setOf(newEmptyNode, simpleNode)) } } else null } fun emptyToGoal() = abs(empty.pos.first - xRange.last - 1) + empty.pos.second fun goalToZero() = goal.pos.first + goal.pos.second } private val lineStructure = """/dev/grid/node-x(\d+)-y(\d+)\s+(\d+)T\s+(\d+)T\s+(\d+)T\s+(\d+)%""".toRegex() fun parse(input: List<String>) = input.drop(2).map { lineStructure.matchEntire(it)?.destructured?.let { val (name, data) = it.toList().map { it.toInt() }.let { it.take(2) to it.drop(2) } val (x, y) = name val (size, used, avail, use) = data Node(x, y, size, used, avail, use) } }.requireNoNulls().toSet() fun part1(input: Set<Node>): Any? = input.filter { it.used != 0 }.sumBy { node -> (input - node).count { node.used <= it.avail } } fun part2(input: Set<Node>): Int { val newInput = input.map { SimpleNode(it.x to it.y, it.size, it.used) } var solution: NodeMap? = null val candidates = NodeMap( newInput.single { it.used == 0 }, newInput.single { it.pos.first == xRange.last && it.pos.second == 0 } ).also { it.grid.addAll(newInput) }.candidates() .toSortedSet(compareBy<NodeMap> { it.steps + it.emptyToGoal() } .thenBy { it.empty.pos.first }.thenBy { it.empty.pos.second }) val seen = mutableSetOf<Pair<Int, Int>>() while (candidates.isNotEmpty()) { val first = candidates.first() seen.add(first.empty.pos) candidates.remove(first) if (first.emptyToGoal() == 1) { solution = first } else { candidates.addAll(first.candidates().filter { it.empty.pos !in seen }) } } val newCandidates = solution!!.candidates().toSortedSet(compareBy<NodeMap> { it.goal.pos.first } .thenBy { it.goal.pos.second } .thenBy { it.steps } .thenBy { it.empty.pos.first }.thenBy { it.empty.pos.second }) while (newCandidates.isNotEmpty()) { val first = newCandidates.first() newCandidates.remove(first) if (first.goalToZero() == 0) { return first.steps } else { newCandidates.addAll(first.candidates()) } } return 0 }
0
Kotlin
0
0
73110eb4b40f474e91e53a1569b9a24455984900
3,955
AOC2016
MIT License
src/day2/Day2.kt
bartoszm
572,719,007
false
{"Kotlin": 39186}
package day2 import readInput import toPair fun main() { val testInput = parse(readInput("day02/test")) val input = parse(readInput("day02/input")) println(solve1(testInput)) println(solve1(input)) println(solve2(testInput)) println(solve2(input)) } fun parse(input: List<String>): List<Pair<String, String>> { return input.map { i -> i.split("\\s+".toRegex()).map { it.trim() }.toPair() } } enum class Score(val score: Int) { Loose(0), Tie(3), Win(6) } enum class Hand(val points: Int) { Rock(1), Paper(2), Scissors(3); fun better(): Hand = Hand.values()[(this.ordinal + 1) % 3] fun worse(): Hand = Hand.values()[(this.ordinal - 1 + 3) % 3] fun play(other: Hand): Score { return when (other) { this -> Score.Tie this.better() -> Score.Loose else -> Score.Win } } } val theyEncoding = mapOf( "A" to Hand.Rock, "B" to Hand.Paper, "C" to Hand.Scissors ) fun solve1(input: List<Pair<String, String>>): Int { val mineEncoding = mapOf( "X" to Hand.Rock, "Y" to Hand.Paper, "Z" to Hand.Scissors ) fun score(them: Hand, you: Hand) = you.points + you.play(them).score return input.map { (them, you) -> theyEncoding[them]!! to mineEncoding[you]!! }.sumOf { score(it.first, it.second) } } fun solve2(input: List<Pair<String, String>>): Int { fun score(v: String): Score { return when (v) { "X" -> Score.Loose "Y" -> Score.Tie "Z" -> Score.Win else -> throw IllegalStateException() } } fun score(them: Hand, result: String): Int { val sc = score(result) val mine = when (sc) { Score.Win -> them.better() Score.Tie -> them Score.Loose -> them.worse() } return sc.score + mine.points } return input.map { (them, result) -> theyEncoding[them]!! to result }.sumOf { score(it.first, it.second) } }
0
Kotlin
0
0
f1ac6838de23beb71a5636976d6c157a5be344ac
2,032
aoc-2022
Apache License 2.0
src/day16/Day16.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day16 import utils.* val LINE_REGEX = ( """Valve (\w+) has flow rate=(\d+); """ + """tunnels? leads? to valves? (.*)""" ).toRegex() data class Valve(val name: String, val rate: Int) { lateinit var links: List<Valve> lateinit var openingCosts: Map<Valve, Int> fun computeOpeningCosts() { val result = mutableMapOf<Valve, Int>() val visited = mutableSetOf<Valve>() var openingCost = 1 generateSequence(listOf(this)) { stack -> stack .onEach { if (it.rate > 0) result[it] = openingCost } .flatMap { valve -> valve.links } .filter { it !in visited } .also { visited.addAll(it) openingCost++ } }.find { it.isEmpty() } openingCosts = result } } data class State( val currentValve: Valve, val time: Int, val openValves: Set<Valve> = setOf(), val score: Int = 0 ) { val subStates get() = currentValve.openingCosts .filter { (valve, length) -> valve !in openValves && length < time } .map { (valve, openingTime) -> State( valve, time - openingTime, openValves + valve, score + valve.rate * (time - openingTime) ) } } fun parseRootValve(input: List<String>): Valve { val valveChildren = mutableMapOf<String, List<String>>() val valves = input.associate { line -> val (name, rate, children) = LINE_REGEX.find(line)!!.groupValues.drop(1) valveChildren[name] = children.split(", ") name to Valve(name, rate.toInt()) } valves.entries.forEach { (name, valve) -> valve.links = valveChildren[name]!!.map { valves[it]!! } } valves.values.forEach { it.computeOpeningCosts() } return valves["AA"]!! } fun computePaths( root: Valve, totalTime: Int, openValves: Set<Valve> = setOf() ): List<Pair<Set<Valve>, Int>> { val rootState = State(root, totalTime, openValves) val visited = mutableSetOf(rootState) val result = mutableMapOf<Set<Valve>, Int>() generateSequence(listOf(rootState)) { stack -> stack .flatMap { state -> if (result[state.openValves]?.let { state.score > it } != false) result[state.openValves] = state.score state.subStates .filter { it !in visited } .also { visited.addAll(it) } } }.find { it.isEmpty() } return result.map { it.toPair() } } fun part1(input: List<String>): Int { val root = parseRootValve(input) val paths = computePaths(root, 30) return paths.maxOf { it.second } } fun part2(input: List<String>): Int { val root = parseRootValve(input) val paths = computePaths(root, 26) return paths.maxOf { (openValves, baseScore) -> val otherScore = computePaths(root, 26, openValves).maxOf { it.second } baseScore + otherScore } } fun main() { val testInput = readInput("Day16_test") expect(part1(testInput), 1651) expect(part2(testInput), 1707) val input = readInput("Day16") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
3,386
AOC-2022-Kotlin
Apache License 2.0
src/main/kotlin/aoc2023/Day11.kt
j4velin
572,870,735
false
{"Kotlin": 285016, "Python": 1446}
package aoc2023 import Point import readInput import to2dCharArray object Day11 { fun getDistanceSum(input: List<String>, emptyMultiplier: Int = 2): Long { val initialMap = input.to2dCharArray() val emptyColumns = initialMap.withIndex().filter { (x, column) -> column.all { it == '.' } }.map { it.index } val emptyRows = input.withIndex().filter { (y, row) -> row.all { it == '.' } }.map { it.index } val galaxies = initialMap.withIndex().flatMap { (x, column) -> column.withIndex().filter { (y, char) -> char == '#' }.map { (y, char) -> Point( x + emptyColumns.filter { it < x }.size * (emptyMultiplier - 1), y + emptyRows.filter { it < y }.size * (emptyMultiplier - 1) ) } } val distances = galaxies.flatMap { g1 -> galaxies.filter { it != g1 }.map { g2 -> g1 to g2 } }.distinctBy { // order by x, then by y if (it.first.x < it.second.x || (it.first.x == it.second.x && it.first.y < it.second.y)) { "${it.first.x},${it.first.y}|${it.second.x},${it.second.y}" } else { "${it.second.x},${it.second.y}|${it.first.x},${it.first.y}" } }.map { it.first.longDistanceTo(it.second) } return distances.sum() } fun part1(input: List<String>) = getDistanceSum(input).toInt() fun part2(input: List<String>) = getDistanceSum(input, 1_000_000) } fun main() { val testInput = readInput("Day11_test", 2023) check(Day11.part1(testInput) == 374) check(Day11.getDistanceSum(testInput, 10) == 1030L) check(Day11.getDistanceSum(testInput, 100) == 8410L) val input = readInput("Day11", 2023) println(Day11.part1(input)) println(Day11.part2(input)) }
0
Kotlin
0
0
f67b4d11ef6a02cba5b206aba340df1e9631b42b
1,823
adventOfCode
Apache License 2.0
src/2022/Day19.kt
ttypic
572,859,357
false
{"Kotlin": 94821}
package `2022` import readInput fun main() { fun parseBlueprint(blueprintConfig: String): Blueprint { val regex = """Blueprint (\d+): Each ore robot costs (\d+) ore. Each clay robot costs (\d+) ore. Each obsidian robot costs (\d+) ore and (\d+) clay. Each geode robot costs (\d+) ore and (\d+) obsidian""".toRegex() val groups = regex.find(blueprintConfig)!!.groups return Blueprint( id = groups[1]!!.value.toInt(), oreRobotCost = groups[2]!!.value.toInt(), clayRobotCost = groups[3]!!.value.toInt(), obsidianRobotCost = groups[4]!!.value.toInt() to groups[5]!!.value.toInt(), geodeRobotCost = groups[6]!!.value.toInt() to groups[7]!!.value.toInt(), ) } fun findMaxGeodesRobot(initialState: Day19State, blueprint: Blueprint): Int { var states = listOf(initialState to initialState) do { states = states.flatMap { (state, prev) -> buildList { if (state.canBuild(blueprint, Robot.geode)) { add(state.buildRobot(blueprint, Robot.geode) to state) } else { add(state.tick(1) to state) listOf(Robot.ore, Robot.clay, Robot.obsidian).forEach { robot -> val canBuild = prev.canBuild(blueprint, robot) val skipped = prev.eqByRobots(state) val canBuildNow = state.canBuild(blueprint, robot) if (!(canBuild && skipped) && canBuildNow) { add(state.buildRobot(blueprint, robot) to state) } } } } } } while (states.first().first.countdown != 0) return states.maxOf { it.first.geode } } fun part1(input: List<String>): Int { val blueprints = input.map { parseBlueprint(it) } return blueprints.sumOf { val max = findMaxGeodesRobot(Day19State(), it) it.id * max } } fun part2(input: List<String>): Int { val blueprints = input.map { parseBlueprint(it) }.take(3) return blueprints.map { findMaxGeodesRobot(Day19State(countdown = 32), it) }.reduce(Int::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day19_test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 33) check(part2(testInput) == 62 * 56) val input = readInput("Day19") println(part1(input)) println(part2(input)) } data class Blueprint( val id: Int, val oreRobotCost: Int, val clayRobotCost: Int, val obsidianRobotCost: Pair<Int, Int>, val geodeRobotCost: Pair<Int, Int> ) data class Day19State( val countdown: Int = 24, val oreProducers: Int = 1, val clayProducers: Int = 0, val obsidianProducers: Int = 0, val geodeProducers: Int = 0, val ore: Int = 0, val clay: Int = 0, val obsidian: Int = 0, val geode: Int = 0 ) fun Day19State.isValid(): Boolean { return ore >= 0 && clay >= 0 && obsidian >= 0 } fun Day19State.tick(time: Int): Day19State { return copy( countdown = countdown - time, ore = oreProducers * time + ore, clay = clayProducers * time + clay, obsidian = obsidianProducers * time + obsidian, geode = geodeProducers * time + geode, ) } fun Day19State.produceGeode(blueprint: Blueprint, removeOne: Boolean = false): Day19State { return copy( geodeProducers = geodeProducers + 1, ore = ore - blueprint.geodeRobotCost.first, obsidian = obsidian - blueprint.geodeRobotCost.second, geode = if (removeOne) geode - 1 else geode, ) } fun Day19State.produceObsidian(blueprint: Blueprint, removeOne: Boolean = false): Day19State { return copy( obsidianProducers = obsidianProducers + 1, ore = ore - blueprint.obsidianRobotCost.first, clay = clay - blueprint.obsidianRobotCost.second, obsidian = if (removeOne) obsidian - 1 else obsidian, ) } fun Day19State.produceClay(blueprint: Blueprint, removeOne: Boolean = false): Day19State { return copy( clayProducers = clayProducers + 1, ore = ore - blueprint.clayRobotCost, clay = if (removeOne) clay - 1 else clay, ) } fun Day19State.produceOre(blueprint: Blueprint, removeOne: Boolean = false): Day19State { val nextOre = ore - blueprint.oreRobotCost return copy( oreProducers = oreProducers + 1, ore = if (removeOne) nextOre - 1 else nextOre, ) } fun Day19State.eqByRobots(other: Day19State): Boolean { return oreProducers == other.oreProducers && clayProducers == other.clayProducers && obsidianProducers == other.obsidianProducers && geodeProducers == other.geodeProducers } fun Day19State.buildRobot(blueprint: Blueprint, robot: Robot): Day19State { return when (robot) { Robot.geode -> this.produceGeode(blueprint, true) Robot.obsidian -> this.produceObsidian(blueprint, true) Robot.clay -> this.produceClay(blueprint, true) Robot.ore -> this.produceOre(blueprint, true) }.tick(1) } fun Blueprint.maxOre(): Int { return oreRobotCost .coerceAtLeast(clayRobotCost) .coerceAtLeast(obsidianRobotCost.first) .coerceAtLeast(geodeRobotCost.first) } fun Day19State.canBuild(blueprint: Blueprint, robot: Robot): Boolean { val hasReason = when (robot) { Robot.geode -> true Robot.obsidian -> obsidianProducers < blueprint.geodeRobotCost.second Robot.clay -> clayProducers < blueprint.obsidianRobotCost.second Robot.ore -> oreProducers < blueprint.maxOre() } return hasReason && when (robot) { Robot.geode -> this.produceGeode(blueprint) Robot.obsidian -> this.produceObsidian(blueprint) Robot.clay -> this.produceClay(blueprint) Robot.ore -> this.produceOre(blueprint) }.isValid() } enum class Robot { geode, obsidian, clay, ore }
0
Kotlin
0
0
b3e718d122e04a7322ed160b4c02029c33fbad78
6,251
aoc-2022-in-kotlin
Apache License 2.0
src/day14/Day14.kt
spyroid
433,555,350
false
null
package day14 import com.github.ajalt.mordant.terminal.Terminal import readInput import kotlin.system.measureTimeMillis fun main() { class Polymer(input: List<String>) { var template = input.first() val pairCounts = input.first().asSequence() .windowed(2) .map { it.joinToString("") } .groupingBy { it } .eachCount() .mapValues { (_, v) -> v.toLong() } val spawnRules = input.drop(2).associate { it.split(" -> ").let { (pair, insertion) -> pair to Pair(pair.first() + insertion, insertion + pair.last()) } } fun calculate(iterations: Int): Long { return generateSequence(pairCounts) { getNewCounts(it) } .drop(iterations) .first() .let { countLetters(it) } .values .sortedBy { it }.let { it.last() - it.first() } } private fun countLetters(pairCounts: Map<String, Long>): Map<Char, Long> { val letterCounts = mutableMapOf<Char, Long>().apply { pairCounts.entries.forEach { (key, value) -> this[key.first()] = getOrDefault(key.first(), 0) + value this[key.last()] = getOrDefault(key.last(), 0) + value } } return letterCounts.entries.associate { (key, value) -> when (key) { template.first(), template.last() -> key to (value + 1) / 2 else -> key to value / 2 } } } private fun getNewCounts(pairCounts: Map<String, Long>): Map<String, Long> { return mutableMapOf<String, Long>().apply { pairCounts.forEach { pair -> val pp = spawnRules[pair.key] if (pp != null) { this[pp.first] = getOrDefault(pp.first, 0L) + pair.value this[pp.second] = getOrDefault(pp.second, 0L) + pair.value } } } } } fun part1(input: List<String>) = Polymer(input).calculate(10) fun part2(input: List<String>) = Polymer(input).calculate(40) val testData = readInput("day14/test") val inputData = readInput("day14/input") val term = Terminal() var res1 = part1(testData) check(res1 == 1588L) { "Expected 1588 but got $res1" } var time = measureTimeMillis { res1 = part1(inputData) } term.success("⭐️ Part1: $res1 in $time ms") time = measureTimeMillis { res1 = part2(inputData) } term.success("⭐️ Part2: $res1 in $time ms") }
0
Kotlin
0
0
939c77c47e6337138a277b5e6e883a7a3a92f5c7
2,702
Advent-of-Code-2021
Apache License 2.0
src/Day07.kt
Migge
572,695,764
false
{"Kotlin": 9496}
private fun part1(input: List<String>): Int { val root = buildDisk(input.drop(1)) return root.flatMap() .map { it.size } .filter { it <= 100000 } .sorted() .sum() } private fun part2(input: List<String>): Int { val root = buildDisk(input.drop(1)) val remaining = 30000000 - (70000000 - root.size) return root.flatMap() .map { it.size } .filter { it >= remaining } .min() } private fun buildDisk(instrs: List<String>): Dir { val root = Dir("/", null) var dir = root for (instr in instrs) { val t = instr.split(" ") when { instr == "$ cd .." -> dir = dir.parent!! t[1] == "cd" -> dir = dir.children.first { it.name == t[2] } t[0] == "dir" -> dir.children += Dir(t[1], dir) t[0].toIntOrNull() != null -> dir.addFile(File(t[1], t[0].toInt())) } } return root } data class File(val name: String, val size: Int) class Dir(val name: String, val parent: Dir?) { val children = mutableListOf<Dir>() val size get() = _size private val files = mutableListOf<File>() private var _size = 0 private fun sizeChanged(size: Int) { _size += size parent?.sizeChanged(size) } fun addFile(file: File) { files += file sizeChanged(file.size) } } private fun Dir.flatMap(): List<Dir> = listOf(this) + children.fold(emptyList()) { list, e -> list + e.flatMap() } fun main() { 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
c7ca68b2ec6b836e73464d7f5d115af3e6592a21
1,706
adventofcode2022
Apache License 2.0
src/year2015/day24/Day24.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2015.day24 import check import readInput fun main() { // test if implementation meets criteria from the description, like: val testInput = readInput("2015", "Day24_test") check(part1(testInput), 99) check(part2(testInput), 44) val input = readInput("2015", "Day24") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Long { val presents = input.map { it.toLong() } val targetWeight = presents.sum() / 3 val combinations = getTargetWeightCombinations(presents, targetWeight, 6) val validCombinations = combinations.filter { val remainingWeights = presents - it hasTargetWeightCombinations(remainingWeights, targetWeight, remainingWeights.size / 2) } val minSize = validCombinations.minOf { it.size } val minQE = validCombinations.filter { it.size == minSize }.minBy { it.reduce(Long::times) } return minQE.reduce(Long::times) } private fun part2(input: List<String>): Long { val presents = input.map { it.toLong() } val targetWeight = presents.sum() / 4 val combinations = getTargetWeightCombinations(presents, targetWeight, 5) val validCombinations = combinations.filter { val remainingWeights = presents - it hasTargetWeightCombinations(remainingWeights, targetWeight, remainingWeights.size / 2) } val minSize = validCombinations.minOf { it.size } val minQE = validCombinations.filter { it.size == minSize }.minBy { it.reduce(Long::times) } return minQE.reduce(Long::times) } private fun getTargetWeightCombinations( remainingWeights: List<Long>, targetWeight: Long, maxSize: Int, weight: Long = 0, combination: Set<Long> = emptySet(), cache: MutableMap<Set<Long>, Set<Set<Long>>> = hashMapOf(), ): Set<Set<Long>> { if (weight > targetWeight || combination.size > maxSize) return emptySet() if (weight == targetWeight) return setOf(combination) return cache.getOrPut(combination) { remainingWeights.flatMapTo(hashSetOf()) { getTargetWeightCombinations( remainingWeights = remainingWeights.filter { w -> w > it }, targetWeight = targetWeight, maxSize = maxSize, weight = weight + it, combination = combination + it, cache = cache, ) } } } private fun hasTargetWeightCombinations( remainingWeights: List<Long>, targetWeight: Long, maxSize: Int, weight: Long = 0, combination: Set<Long> = emptySet(), cache: MutableMap<Set<Long>, Boolean> = hashMapOf(), ): Boolean { if (weight > targetWeight || combination.size > maxSize) return false if (weight == targetWeight) return true return cache.getOrPut(combination) { remainingWeights.any { hasTargetWeightCombinations( remainingWeights = remainingWeights.filter { w -> w > it }, targetWeight = targetWeight, maxSize = maxSize, weight = weight + it, combination = combination + it, cache = cache, ) } } }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
3,178
AdventOfCode
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2023/Day19.kt
tginsberg
723,688,654
false
{"Kotlin": 112398}
/* * Copyright (c) 2023 by <NAME> */ /** * Advent of Code 2023, Day 19 - Aplenty * Problem Description: http://adventofcode.com/2023/day/19 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2023/day19/ */ package com.ginsberg.advent2023 class Day19(input: List<String>) { private val workflows = input.takeWhile { it.isNotBlank() }.map { Workflow.of(it) }.associateBy { it.name } private val partRatings = input.dropWhile { it.isNotBlank() }.drop(1).map { PartRating.of(it) } fun solvePart1(): Int = partRatings.filter { rating -> workflows.getValue("in").evaluate(rating, workflows) == "A" }.sumOf { it.total } fun solvePart2(): Long = workflows.getValue("in") .countRanges( workflows.withDefault { Workflow(it, emptyList()) }, "xmas".associateWith { 1..4000 } ) private data class PartRating(val categories: Map<Char, Int>) { val total: Int = categories.values.sum() operator fun get(category: Char): Int = categories.getValue(category) companion object { fun of(input: String): PartRating = PartRating( input .removeSurrounding("{", "}") .split(",") .associate { it.first() to it.substring(2).toInt() } ) } } private data class Workflow(val name: String, val rules: List<Rule>) { fun evaluate(part: PartRating, workflows: Map<String, Workflow>): String = rules.firstNotNullOf { rule -> when (val answer = rule.eval(part)) { null, in setOf("A", "R") -> answer else -> workflows.getValue(answer).evaluate(part, workflows) } } fun countRanges(allWorkflows: Map<String, Workflow>, ranges: Map<Char, IntRange>): Long = when (name) { "R" -> 0 "A" -> ranges.values.map { it.length().toLong() }.reduce(Long::times) else -> { val constrainedRanges = ranges.toMutableMap() rules .map { it to allWorkflows.getValue(it.nextWorkflow) } .sumOf { (rule, workflow) -> when (rule) { is Rule.Other -> workflow .countRanges(allWorkflows, constrainedRanges) is Rule.RangeCheck -> constrainedRanges.getValue(rule.category).let { before -> constrainedRanges[rule.category] = before intersectRange rule.range workflow.countRanges(allWorkflows, constrainedRanges).also { constrainedRanges[rule.category] = before intersectRange rule.antiRange } } } } } } companion object { fun of(input: String): Workflow = Workflow( input.substringBefore("{"), input .substringAfter("{") .substringBefore("}") .split(",") .map { rule -> Rule.of(rule) } ) } } private sealed class Rule(val nextWorkflow: String) { companion object { fun of(input: String): Rule = if ('>' in input || '<' in input) { val variable = input[0] val test = input[1] val amount = input.substring(2).substringBefore(":").toInt() val target = input.substringAfter(":") RangeCheck( variable, if (test == '<') (1..<amount) else (amount + 1..4000), if (test == '<') (amount..4000) else (1..amount), target ) } else Other(input) } abstract fun eval(partRating: PartRating): String? class RangeCheck( val category: Char, val range: IntRange, val antiRange: IntRange, nextWorkflow: String ) : Rule(nextWorkflow) { override fun eval(partRating: PartRating): String? = if (partRating[category] in range) nextWorkflow else null } class Other(nextWorkflow: String) : Rule(nextWorkflow) { override fun eval(partRating: PartRating): String = nextWorkflow } } }
0
Kotlin
0
12
0d5732508025a7e340366594c879b99fe6e7cbf0
4,925
advent-2023-kotlin
Apache License 2.0
src/Day13.kt
ambrosil
572,667,754
false
{"Kotlin": 70967}
private sealed class Packet : Comparable<Packet> { companion object { fun of(input: String): Packet = of(input.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex()) .filter { it.isNotBlank() } .filter { it != "," } .iterator() ) private fun of(input: Iterator<String>): Packet { val packets = mutableListOf<Packet>() while (input.hasNext()) { when (val symbol = input.next()) { "]" -> return ListPacket(packets) "[" -> packets.add(of(input)) else -> packets.add(IntPacket(symbol.toInt())) } } return ListPacket(packets) } } } private class IntPacket(val amount: Int) : Packet() { fun asList(): Packet = ListPacket(listOf(this)) override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> amount.compareTo(other.amount) is ListPacket -> asList().compareTo(other) } } private class ListPacket(val subPackets: List<Packet>) : Packet() { override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> compareTo(other.asList()) is ListPacket -> subPackets.zip(other.subPackets) .map { it.first.compareTo(it.second) } .firstOrNull { it != 0 } ?: subPackets.size.compareTo(other.subPackets.size) } } fun main() { fun parse(input: List<String>): Sequence<Packet> { return input.asSequence().filter { it.isNotBlank() }.map { Packet.of(it) } } fun part1(input: List<String>): Int { return parse(input) .chunked(2) .mapIndexed { index, (first, second) -> if (first < second) index + 1 else 0 }.sum() } fun part2(input: List<String>): Int { val packets = parse(input) val divider1 = Packet.of("[[2]]") val divider2 = Packet.of("[[6]]") val ordered = (packets + divider1 + divider2).sorted() return (ordered.indexOf(divider1) + 1) * (ordered.indexOf(divider2) + 1) } val input = readInput("inputs/Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebaacfc65877bb5387ba6b43e748898c15b1b80a
2,312
aoc-2022
Apache License 2.0
src/aoc2022/Day18.kt
NoMoor
571,730,615
false
{"Kotlin": 101800}
package aoc2022 import utils.* private class Day18(val lines: List<String>) { data class Coord3d(val x:Int, val y:Int, val z:Int) { fun getCrossNeighbors() : List<Coord3d> { return listOf( this.offset(dx = 1), this.offset(dx = -1), this.offset(dy = 1), this.offset(dy = -1), this.offset(dz = 1), this.offset(dz = -1)) } fun getAllNeighbors() : List<Coord3d> { return (-1..1).flatMap { x -> (-1..1).flatMap { y -> (-1..1).filter { z -> x != 0 || y != 0 || z != 0 } .map { z -> Coord3d(this.x + x, this.y + y, this.z + z) } } } } fun offset(dx: Int = 0, dy: Int = 0, dz: Int = 0) : Coord3d { return Coord3d(x + dx, y + dy, z + dz) } } fun part1(): Int { val drops = lines.map { val (x, y, z) = it.split(",").map { it.toInt() } Coord3d(x, y, z) }.toSet() return drops.sumOf { 6 - it.getCrossNeighbors().count { it in drops } } } fun part2(): Int { val drops = lines.map { val (x, y, z) = it.split(",").map { it.toInt() } Coord3d(x, y, z) }.toSet() val surfaceCount = drops.sumOf { 6 - it.getCrossNeighbors().count { it in drops } } // These are the ones I'm trying to figure out for surface area val allCrossNeighbors = drops.flatMap { it.getCrossNeighbors() }.filter { it !in drops }.distinct() // For traversing around val allNonLavaNeighborsIncludingDiagonals = drops.flatMap { it.getAllNeighbors() }.filter { it !in drops }.toSet() val definitelyOutsideNeighbor = drops.maxBy { it.x }.offset(dx = 1) val visitedOutside = mutableSetOf<Coord3d>() val toVisit = mutableListOf<Coord3d>() toVisit.add(definitelyOutsideNeighbor) while (toVisit.isNotEmpty()) { val curr = toVisit.removeFirst() if (curr in visitedOutside) { continue } visitedOutside.add(curr) toVisit.addAll(curr.getCrossNeighbors().filter { it in allNonLavaNeighborsIncludingDiagonals }) } val insideNeighbors = allCrossNeighbors.toMutableList().filter { it !in visitedOutside } val insidesSurfaces = insideNeighbors.sumOf { it.getCrossNeighbors().count { it in drops } } return surfaceCount - insidesSurfaces } } fun main() { val day = "18".toInt() val todayTest = Day18(readInput(day, 2022, true)) execute(todayTest::part1, "Day[Test] $day: pt 1", 64) val today = Day18(readInput(day, 2022)) execute(today::part1, "Day $day: pt 1") execute(todayTest::part2, "Day[Test] $day: pt 2", 58) execute(today::part2, "Day $day: pt 2") // Wrong guesses = 3374 }
0
Kotlin
1
2
d561db73c98d2d82e7e4bc6ef35b599f98b3e333
2,689
aoc2022
Apache License 2.0
src/main/kotlin/day7/Day7.kt
stoerti
726,442,865
false
{"Kotlin": 19680}
package io.github.stoerti.aoc.day7 import io.github.stoerti.aoc.IOUtils import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt fun main(args: Array<String>) { val lines = IOUtils.readInput("day_7_input") val result1 = lines.map { it.split(" ") } .map { Hand(it[1].toInt(), it[0]) } .sortedBy { it.getHandValue() } // .onEachIndexed { i, it -> println("${i + 1} ${it.cards} ${it.bet} ${it.getHandValue()}") } .mapIndexed { i, it -> (i + 1) * it.bet } .sum() val result2 = lines.map { it.split(" ") } .map { Hand(it[1].toInt(), it[0], true) } .sortedBy { it.getHandValue() } // .onEachIndexed { i, it -> println("${i + 1} ${it.cards} ${it.bet} ${it.getHandValue()}") } .mapIndexed { i, it -> (i + 1) * it.bet } .sum() println("Result1: $result1") println("Result2: $result2") } data class Hand( val bet: Int, val cards: String, val jokerRule: Boolean = false ) { private val groupedCards = cards.toCharArray().filter { !jokerRule || it != 'J' } .groupBy { it }.mapValues { it.value.size } val numJokers = cards.toCharArray().count { jokerRule && it == 'J' } private fun hasFiveOfAKind(): Boolean = numJokers == 5 || groupedCards.values.maxOf { it + numJokers } == 5 private fun hasFourOfAKind(): Boolean = groupedCards.values.maxOf { it + numJokers } == 4 private fun hasFullHouse(): Boolean = ( groupedCards.containsValue(3) && groupedCards.containsValue(2)) || ( groupedCards.filterValues { it == 2 }.size == 2 && numJokers == 1) private fun hasThreeOfAKind(): Boolean = groupedCards.values.maxOf { it + numJokers } == 3 private fun hasTwoPair(): Boolean = groupedCards.filterValues { it == 2 }.size == 2 private fun hasOnePair(): Boolean = groupedCards.values.maxOf { it + numJokers } == 2 private fun getHandType(): String { if (hasFiveOfAKind()) return "9" if (hasFourOfAKind()) return "8" if (hasFullHouse()) return "7" if (hasThreeOfAKind()) return "6" if (hasTwoPair()) return "5" if (hasOnePair()) return "4" return "0" } fun getHandValue(): String { return this.getHandType() + mapCardToValue(cards[0]) + mapCardToValue(cards[1]) + mapCardToValue(cards[2]) + mapCardToValue(cards[3]) + mapCardToValue(cards[4]) } fun mapCardToValue(card: Char): String { return when (card) { 'A' -> "14" 'K' -> "13" 'Q' -> "12" 'J' -> "01" 'T' -> "10" else -> "0$card" } } }
0
Kotlin
0
0
05668206293c4c51138bfa61ac64073de174e1b0
2,522
advent-of-code
Apache License 2.0
src/adventofcode/day05/Day05.kt
bstoney
574,187,310
false
{"Kotlin": 27851}
package adventofcode.day05 import adventofcode.* fun main() { Solution.solve() } typealias Crate = Char object Solution : AdventOfCodeSolution<String>() { override fun solve() { solve(5, "CMZ", "MCD") } override fun part1(input: List<String>): String { return getSupplyStacks(input) { crates -> crates.reversed() } .map { it.getTopCrate() } .joinToString("") { it.toString() } } override fun part2(input: List<String>): String { return getSupplyStacks(input) { crates -> crates } .map { it.getTopCrate() } .joinToString("") { it.toString() } } private fun getSupplyStacks( input: List<String>, moveBy: (List<Crate>) -> List<Crate> ): List<SupplyStack> { val (supplyStacksInput, instructionsInput) = input.splitAt { it.isEmpty() } val supplyStacks = getSupplyStacksInitialState(supplyStacksInput) debug(supplyStacks) val regex = Regex("move (\\d+) from (\\w+) to (\\w+)") return instructionsInput.mapNotNull { regex.find(it) } .map { val (count, from, to) = it.destructured Instruction(count.toInt(), from, to) } .peek { debug(it) } .fold(supplyStacks.values) { stacks, instruction -> var movedCrates: List<Crate> = emptyList() stacks.map { when (it.id) { instruction.fromId -> { movedCrates = it.getTopCrates(instruction.count) ({ it.removeCrates(instruction.count) }) } instruction.toId -> ({ it.addCrates(moveBy(movedCrates)) }) else -> ({ it }) } } .map { it() } } .sortedBy(SupplyStack::id) } private fun getSupplyStacksInitialState(supplyStacksInput: List<String>): Map<String, SupplyStack> { val supplyStacks = supplyStacksInput.map { it.chunked(4) { stack -> stack[1] } } .reversed() .fold(listOf<SupplyStack>()) { acc, chars -> if (acc.isEmpty()) { chars.map { SupplyStack(it.toString(), listOf()) } } else { acc.zipAll(chars) { a, b -> if (b != null && b != ' ') { SupplyStack(a!!.id, a.crates + b) } else { a!! } } .toList() } } .fold(mapOf<String, SupplyStack>()) { acc, supplyStack -> acc + Pair(supplyStack.id, supplyStack) } return supplyStacks } data class SupplyStack(val id: String, val crates: List<Crate>) { fun getTopCrate() = crates.last() fun getTopCrates(count: Int) = crates.takeLast(count) fun removeCrates(count: Int) = SupplyStack(id, crates.subList(0, crates.size - count)) fun addCrates(crates: List<Crate>) = SupplyStack(id, this.crates + crates) } data class Instruction(val count: Int, val fromId: String, val toId: String) { override fun toString(): String { return "moving $count crate(s) from $fromId to $toId" } } }
0
Kotlin
0
0
81ac98b533f5057fdf59f08940add73c8d5df190
3,408
fantastic-chainsaw
Apache License 2.0
src/main/kotlin/d19/D19_2.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d19 import d13.split import input.Input import kotlin.math.max import kotlin.math.min data class Rule( val breakpoint: Int, val category: Char, val operation: Char, val target: String ) fun parseWorkflows2(lines: List<String>): Map<String, List<Rule>> { return lines.map { line -> val parts = line.split("{", "}") val name = parts[0] val workflow = parts[1] val rules: List<Rule> = workflow.split(",").map rules@{ ruleStr -> val conditionAndTarget = ruleStr.split(":") if (conditionAndTarget.size == 1) { val target = conditionAndTarget[0] return@rules Rule(0, 'X', 'X', target) } val conditionStr = conditionAndTarget[0] val target = conditionAndTarget[1] return@rules Rule( conditionStr.substring(2).toInt(), conditionStr[0], conditionStr[1], target ) } Pair(name, rules) }.toMap() } fun main() { val lines = Input.read("input.txt") val workflowsAndParts = lines.split { it.isEmpty() } val workflows = parseWorkflows2(workflowsAndParts[0]) val initialRanges = mapOf( Pair('x', Pair(1, 4000)), Pair('m', Pair(1, 4000)), Pair('a', Pair(1, 4000)), Pair('s', Pair(1, 4000)) ) val combinations = getCombinations(initialRanges, "in", workflows) println(combinations) } fun getTrueRange(currentRange: Pair<Int, Int>, rule: Rule): Pair<Int, Int>? { val range = when (rule.operation) { '<' -> { val upperBound = min(currentRange.second, rule.breakpoint - 1) Pair(currentRange.first, upperBound) } '>' -> { val lowerBound = max(currentRange.first, rule.breakpoint + 1) Pair(lowerBound, currentRange.second) } else -> throw RuntimeException("no such operation") } return if (range.first <= range.second) range else null } fun getFalseRange(currentRange: Pair<Int, Int>, rule: Rule): Pair<Int, Int>? { val range = when (rule.operation) { '<' -> { val lowerBound = max(currentRange.first, rule.breakpoint) Pair(lowerBound, currentRange.second) } '>' -> { val upperBound = min(currentRange.second, rule.breakpoint) Pair(currentRange.first, upperBound) } else -> throw RuntimeException("no such operation") } return if (range.first <= range.second) range else null } fun getCategoryRangesCopy( categoryRanges: Map<Char, Pair<Int, Int>>, category: Char, newRange: Pair<Int, Int> ): Map<Char, Pair<Int, Int>> { val categoryRangesCopy = categoryRanges.toMutableMap() categoryRangesCopy[category] = newRange return categoryRangesCopy } fun getCombinations( categoryRanges: Map<Char, Pair<Int, Int>>, workflowLabel: String, workflows: Map<String, List<Rule>> ): Long { if (workflowLabel == "R") return 0 if (workflowLabel == "A") return combinationsOfRanges(categoryRanges.values) val currentCategoryRanges = categoryRanges.toMutableMap() val workflow = workflows[workflowLabel]!! var sum = 0L for (rule in workflow) { if (rule.operation == 'X') return sum + getCombinations(currentCategoryRanges, rule.target, workflows) val trueRange = getTrueRange(currentCategoryRanges[rule.category]!!, rule) val falseRange = getFalseRange(currentCategoryRanges[rule.category]!!, rule) if (trueRange != null) { sum += getCombinations( getCategoryRangesCopy(currentCategoryRanges, rule.category, trueRange), rule.target, workflows ) } if (falseRange == null) break currentCategoryRanges[rule.category] = falseRange } return sum } fun combinationsOfRanges(ranges: Collection<Pair<Int, Int>>): Long { return ranges.map { it.second.toLong() - it.first + 1 }.reduce { acc, l -> acc * l } }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
4,107
aoc2023-kotlin
MIT License
src/Day03.kt
ManueruEd
573,678,383
false
{"Kotlin": 10647}
fun main() { val lower = ('a'..'z').mapIndexed { index, c -> c to (index + 1) } val upper = ('A'..'Z').mapIndexed { index, c -> c to (index + 27) } fun part1(input: List<String>): Int { val a = input.map { StringBuilder(it) .insert(it.length / 2, " ") .split(" ") } val uniqueItems = a.map { (a, b) -> a.toCharArray().first { b.toCharArray().contains(it) } } return uniqueItems.sumOf { when (it) { in 'a'..'z' -> lower.first { l -> l.first == it }.second else -> upper.first { l -> l.first == it }.second } } } fun part2(input: List<String>): Int { val a = input.windowed(3, step = 3) val uniqueItems = a.map { it.map { it.trim().toCharArray() } }.map { (a, b, c) -> a.first { b.contains(it) && c.contains(it) } } println(uniqueItems) return uniqueItems.sumOf { when (it) { in 'a'..'z' -> lower.first { l -> l.first == it }.second else -> upper.first { l -> l.first == it }.second } } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
09f3357e059e31fda3dd2dfda5ce603c31614d77
1,547
AdventOfCode2022
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch2/Problem26.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 import dev.bogwalk.util.maths.primeNumbers import java.math.BigInteger /** * Problem 26: Reciprocal Cycles * * https://projecteuler.net/problem=26 * * Goal: Find the value of the smallest d less than N for which 1/d contains the longest * recurring cycle in its decimal fraction part. * * Constraints: 4 <= N <= 1e4 * * Repetend/Reptend: The infinitely repeated digit sequence of the decimal representation of a * number. * * e.g.: N = 10 * 1/2 = 0.5 * 1/3 = 0.(3) -> 1-digit recurring cycle * 1/4 = 0.25 * 1/5 = 0.2 * 1/6 = 0.1(6) -> 1-digit recurring cycle * 1/7 = 0.(142857) -> 6-digit recurring cycle * 1/8 = 0.125 * 1/9 = 0.(1) -> 1-digit recurring cycle * result = 7 */ class ReciprocalCycles { /** * Solution based on the following: * * - If a fraction contains a repetend, the latter's length (K) will never be greater than * the fraction's denominator minus 1. * * - A denominator of 3 produces the first repetend, with K = 1. * * - All fractions that are a power of 1/2 or the product of 1/5 times a power of 1/2 will * have exact decimal equivalents, not repetends. * * - Multiples of a denominator will have same K value (multiples of 7 are special in that * both K and repetend will be equal). * * - For each 1/p, where p is a prime number but not 2 or 5, for k in [1, p), * 10^k % p produces a repetend, when the remainder is 1. * * - e.g. p = 11 -> (10^1 - 1) % 11 != 0, but (10^2 - 1) / 11 has 99 evenly divided by 11 * giving 9. Since k = 2, there must be 2 repeating digits, so repetend = 09. * * SPEED (WORST) 4.18s for N = 1e4 */ fun longestRepetendDenomUsingPrimes(n: Int): Int { // only primes considered as only the smallest N is required & anything larger would be // a multiple of a smaller prime with equivalent K val primes = primeNumbers(n - 1) - listOf(2, 3, 5) var denominator = 3 var longestK = 1 val one = BigInteger.ONE val ten = BigInteger.TEN for (p in primes) { for (k in 1 until p) { if (ten.modPow(k.toBigInteger(), p.toBigInteger()) == one) { if (k > longestK) { longestK = k denominator = p } break } } } return denominator } /** * Solution using primes above is optimised based on the following: * * - Full Repetend Primes are primes that, as 1/p, will have the longest repetend of * k = p - 1. A prime qualifies if, for k in [1, p-1], only the last k returns True for * 10^k % p = 1. * * - e.g. p = 7 -> for k in [1, 7), 10^k % p = [3, 2, 6, 4, 5, 1], so 7 is a full * repetend prime. * * - Other than N = 3 and N = 6 both having K = 1, repetend length increases as primes * increase since the longest repetends will be produced by full repetend primes & not be * repeated. So the loop can be started from the largest prime and broken once the first * full repetend prime is found. * * SPEED (BETTER) 16.89ms for N = 1e4 */ fun longestRepetendDenomUsingPrimesImproved(n: Int): Int { if (n < 8) return 3 val primes = primeNumbers(n - 1).reversed() var denominator = 3 val one = BigInteger.ONE val ten = BigInteger.TEN for (p in primes) { var k = 1 while (ten.modPow(k.toBigInteger(), p.toBigInteger()) != one) { k++ } if (k == p - 1) { denominator = p break } } return denominator } /** * Repeatedly divides & stores decimal parts until a decimal part is repeated & compares * length of stored parts. * * SPEED (BEST) 1.63ms for N = 1e4 */ fun longestRepetendDenominator(n: Int): Int { var denominator = n var longestK = 0 val upperN = if (n % 2 == 0) n - 1 else n - 2 val lowerN = upperN / 2 for (i in upperN downTo lowerN step 2) { if (longestK >= i) break val remainders = IntArray(i) var remainder = 1 var position = 0 while (remainders[remainder] == 0 && remainder != 0) { remainders[remainder] = position++ remainder = remainder * 10 % i } if (position - remainders[remainder] >= longestK) { longestK = position - remainders[remainder] denominator = i } } return denominator } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
4,847
project-euler-kotlin
MIT License
src/Day15.kt
ZiomaleQ
573,349,910
false
{"Kotlin": 49609}
fun main() { fun part1(input: List<String>, yAxis: Int): Int { val points = parseInput(input) var maxX = Int.MIN_VALUE var minX = Int.MAX_VALUE for ((sensor, beacon) in points) { val dist = sensor.distance(beacon) val distanceToY = dist - kotlin.math.abs(yAxis - sensor.y) if (distanceToY < 0) continue val middle = sensor.x maxX = maxOf(maxX, middle + dist) minX = minOf(minX, middle - dist) } return (minX..maxX).count { points.any { pnt -> Cords(it, yAxis).let { cord -> cord.inRadius(pnt) && pnt.second != cord } } } } fun part2(input: List<String>, max: Int): Long { val points = parseInput(input) val out = (0..max).mapNotNull { val ranges = getRowRanges(it, points) if (ranges.size < 2) null else Pair(it, ranges) } return out.first().let { (it.second.first().last + 1) * 4_000_000L + it.first.toLong() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") part1(testInput, 10).also { println(it); check(it == 26) } val input = readInput("Day15") println(part1(input, 2000000)) part2(testInput, 20).also { println(it); check(it == 56000011L) } println(part2(input, 4_000_000)) } private fun parseInput(input: List<String>): List<Pair<Cords, Cords>> = input.map { val sensorX = it.substring(it.indexOf("x=") + 2, it.indexOf(",")).trim().toInt() val sensorY = it.substring(it.indexOf("y=") + 2, it.indexOf(":")).trim().toInt() val nextCords = it.substring(it.indexOf("is at") + "is at".length) val beaconX = nextCords.substring(nextCords.indexOf("x=") + 2, nextCords.indexOf(",")).trim().toInt() val beaconY = nextCords.substring(nextCords.indexOf("y=") + 2).trim().toInt() Pair(Cords(sensorX, sensorY), Cords(beaconX, beaconY)) } private fun Cords.inRadius(radius: Pair<Cords, Cords>): Boolean = radius.first.distance(this) <= radius.first.distance(radius.second) private fun Cords.distance(other: Cords): Int = kotlin.math.abs(x - other.x) + kotlin.math.abs(y - other.y) private fun getRowRanges(y: Int, list: List<Pair<Cords, Cords>>): MutableList<IntRange> { val ranges = list.mapNotNull { val dist = it.first.distance(it.second) val offset = dist - kotlin.math.abs(it.first.y - y) if (offset < 0) null else ((it.first.x - offset)..(it.first.x + offset)) }.sortedBy { it.first }.toMutableList() val tempOut = mutableListOf(ranges.removeFirst()) for (next in ranges) { val lastIdx = tempOut.lastIndex val last = tempOut.last() if (next.first <= last.last || (last.last + 1) == next.first) { if (next.last > last.last) { tempOut[lastIdx] = (last.first..next.last) } } else { tempOut.add(next) } } return tempOut }
0
Kotlin
0
0
b8811a6a9c03e80224e4655013879ac8a90e69b5
2,906
aoc-2022
Apache License 2.0
src/year2022/day19/Solution.kt
TheSunshinator
572,121,335
false
{"Kotlin": 144661}
package year2022.day19 import io.kotest.matchers.shouldBe import java.util.PriorityQueue import kotlin.math.ceil import kotlin.math.max import utils.readInput fun main() { val testInput = readInput("19", "test_input").let(::parseBlueprints) val realInput = readInput("19", "input").let(::parseBlueprints) testInput.associateWith { it.maxGeodeProduced(24) } .asSequence() .sumOf { (blueprint, maxGeodeProduced) -> blueprint.identifier * maxGeodeProduced } .also(::println) shouldBe 33 realInput.associateWith { it.maxGeodeProduced(24) } .asSequence() .sumOf { (blueprint, maxGeodeProduced) -> blueprint.identifier * maxGeodeProduced } .let(::println) testInput.asSequence() .take(3) .map { it.maxGeodeProduced(32) } .reduce(Int::times) .also(::println) shouldBe (56 * 62) realInput.asSequence() .take(3) .map { it.maxGeodeProduced(32) } .reduce(Int::times) .let(::println) } private fun parseBlueprints(input: List<String>): List<Blueprint> { return input.asSequence() .mapNotNull(parsingRegex::matchEntire) .map { it.destructured } .mapTo(mutableListOf()) { (identifier, oreRobotCost, clayRobotCost, obsidianRobotOreCost, obsidianRobotClayCost, geodeRobotOreCost, geodeRobotObsidianCost) -> Blueprint( identifier.toInt(), robotCost = buildMap { this[Rock.ORE] = mapOf(Rock.ORE to oreRobotCost.toInt()) this[Rock.CLAY] = mapOf(Rock.ORE to clayRobotCost.toInt()) this[Rock.OBSIDIAN] = mapOf( Rock.ORE to obsidianRobotOreCost.toInt(), Rock.CLAY to obsidianRobotClayCost.toInt(), ) this[Rock.GEODE] = mapOf( Rock.ORE to geodeRobotOreCost.toInt(), Rock.OBSIDIAN to geodeRobotObsidianCost.toInt(), ) }, ) } } private data class Blueprint( val identifier: Int, val robotCost: Map<MiningRobot, Map<Rock, Int>>, ) { val maxCosts = Rock.values().associateWith { rock -> robotCost.asSequence() .flatMap { it.value.asSequence() } .filter { it.key == rock } .maxOfOrNull { it.value } ?: Int.MAX_VALUE } } private enum class Rock { ORE, CLAY, OBSIDIAN, GEODE } private typealias MiningRobot = Rock private data class State( val minutesLeft: Int, val robotCount: Map<MiningRobot, Int> = mapOf(Rock.ORE to 1), val rockCount: Map<Rock, Int> = emptyMap(), ) { val potentialGeodeCount = rockCount.getOrDefault(Rock.GEODE, 0) + robotCount.getOrDefault(Rock.GEODE, 0) * minutesLeft + minutesLeft.let { it * it - 1 } / 2 } private val parsingRegex = "Blueprint (\\d+): Each ore robot costs (\\d+) ore. Each clay robot costs (\\d+) ore. Each obsidian robot costs (\\d+) ore and (\\d+) clay. Each geode robot costs (\\d+) ore and (\\d+) obsidian.".toRegex() private fun Blueprint.maxGeodeProduced(minutesAvailable: Int): Int { val priorityQueue = PriorityQueue(compareByDescending(State::potentialGeodeCount)) .apply { add(State(minutesAvailable)) } return generateSequence(priorityQueue::poll) .filterOutInsufficientPotential() .onEach { priorityQueue.addAll(it.potentialNextStates(this)) } .maxOf { it.rockCount.getOrDefault(Rock.GEODE, 0) + it.robotCount.getOrDefault(Rock.GEODE, 0) * it.minutesLeft } } private fun State.potentialNextStates(blueprint: Blueprint): Set<State> { return blueprint.robotCost .asSequence() .filter { (miningRobot, cost) -> cost.all { (rock, _) -> robotCount.getOrDefault(rock, 0) > 0 } && robotCount.getOrDefault(miningRobot, 0) < blueprint.maxCosts.getValue(miningRobot) } .mapNotNullTo(mutableSetOf()) { (robot, rockCost) -> val timeToSaveToBuild = rockCost.maxOf { (rock, cost) -> val currentStash = rockCount.getOrDefault(rock, 0) if (currentStash >= cost) 0 else ceil((cost - currentStash) / robotCount.getValue(rock).toDouble()).toInt() } + 1 if (timeToSaveToBuild < minutesLeft) State( minutesLeft = minutesLeft - timeToSaveToBuild, robotCount = robotCount.toMutableMap().apply { compute(robot) { _, count -> count?.plus(1) ?: 1 } }, rockCount = Rock.values().associateWith { rock -> rockCount.getOrDefault(rock, 0) + timeToSaveToBuild * robotCount.getOrDefault(rock, 0) - rockCost.getOrDefault(rock, 0) }, ) else null } } private fun Sequence<State>.filterOutInsufficientPotential() = object : Sequence<State> { private var maxGeode = -1 override fun iterator(): Iterator<State> { return this@filterOutInsufficientPotential.takeWhile { it.potentialGeodeCount > maxGeode } .onEach { maxGeode = max(maxGeode, it.rockCount.getOrDefault(Rock.GEODE, 0)) } .iterator() } }
0
Kotlin
0
0
d050e86fa5591447f4dd38816877b475fba512d0
5,327
Advent-of-Code
Apache License 2.0
src/y2023/Day05.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2023 import util.readInput import util.split import util.timingStatistics object Day05 { data class MyMap(val destinationStart: Long, val sourceRange: LongRange) { fun destinationFor(source: Long): Long { return destinationStart + (source - sourceRange.first) } } private fun parse(input: List<String>): Pair<List<Long>, List<List<MyMap>>> { val parts = input.split { it.isEmpty() } val seeds = parts[0][0].split(" ").drop(1).map { it.toLong() } val maps = parts.drop(1).map { map -> map.drop(1).map { line -> val (destinationStart, sourceStart, range) = line.split(" ").map { it.toLong() } MyMap( destinationStart, sourceStart until sourceStart + range ) } } return seeds to maps } fun part1(input: List<String>): Long { val (seeds, maps) = parse(input) val locations = seeds.map { seed -> maps.fold(seed) { currentNumber, map -> val match = map.find { currentNumber in it.sourceRange } match?.destinationFor(currentNumber) ?: currentNumber } } return locations.min() } fun part2(input: List<String>): Long { val (seeds, maps) = parse(input) val seedRanges = seeds.chunked(2).map { it[0] until it[0] + it[1] } val locationRanges = maps.fold(seedRanges) { currentRanges, map -> // val sumOfRanges = currentRanges.sumOf { it.last - it.first + 1 } // println("sum of Ranges: $sumOfRanges") val allCoveringMap = getAllCoveringMap(map) currentRanges.flatMap { range -> val overlapping = allCoveringMap .dropWhile { it.sourceRange.last < range.first } .takeWhile { it.sourceRange.first <= range.last } overlapping.mapIndexed { index, myMap -> val start = if (index == 0) { myMap.destinationFor(range.first) } else { myMap.destinationFor(myMap.sourceRange.first) } val end = if (index == overlapping.size - 1) { myMap.destinationFor(range.last) } else { myMap.destinationFor(myMap.sourceRange.last) } start..end } } } return locationRanges.minOf { it.first } } fun part2Naive(input: List<String>): Long { val (seeds, maps) = parse(input) val seedRanges = seeds.chunked(2).map { it[0] until it[0] + it[1] } return seedRanges.minOf { range -> println("evaluating range $range -> ${range.last - range.first + 1} seeds") range.minOf { seed -> maps.fold(seed) { currentNumber, map -> val match = map.find { currentNumber in it.sourceRange } match?.destinationFor(currentNumber) ?: currentNumber } } } } private fun getAllCoveringMap(exampleMap: List<MyMap>): List<MyMap> { val sorted = exampleMap.sortedBy { it.sourceRange.first } val basicCovers = sorted.windowed(2) .flatMap { (first, second) -> if (first.sourceRange.last + 1 == second.sourceRange.first) { // no gap to cover listOf(first) } else { listOf( first, MyMap( first.sourceRange.last + 1, first.sourceRange.last + 1 until second.sourceRange.first ) ) } } val start = if (sorted.first().sourceRange.first == 0L) { listOf() } else { listOf(MyMap(0, 0 until sorted.first().sourceRange.first)) } return start + basicCovers + listOf( sorted.last(), MyMap(sorted.last().sourceRange.last + 1, sorted.last().sourceRange.last + 1..Long.MAX_VALUE) ) } } fun main() { val testInput = """ seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 """.trimIndent().split("\n") println("------Tests------") println(Day05.part1(testInput)) println(Day05.part2(testInput)) println("------Real------") val input = readInput(2023, 5) println("Part 1 result: ${Day05.part1(input)}") println("Part 2 result: ${Day05.part2(input)}") timingStatistics { Day05.part1(input) } timingStatistics { Day05.part2(input) } timingStatistics(maxRuns = 1) { Day05.part2Naive(input) } }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
5,323
advent-of-code
Apache License 2.0
src/Day12.kt
proggler23
573,129,757
false
{"Kotlin": 27990}
fun main() { fun part1(input: List<String>): Int { return HeightMap.fromLines(input).solvePart1() } fun part2(input: List<String>): Int { return HeightMap.fromLines(input).solvePart2() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) } data class HeightMap( private val heights: Array<Array<Int>>, private val start: Pair<Int, Int>, private val finish: Pair<Int, Int> ) { fun solvePart1() = solve(listOf(start)) fun solvePart2(): Int { val starts = heights.indices.flatMap { x -> heights[x].mapIndexedNotNull { y, h -> if (h == 0) x to y else null } } return solve(starts) } private fun solve(starts: List<Pair<Int, Int>>): Int { val paths = starts.map { listOf(it) }.toMutableList() val visited = starts.toMutableSet() while (paths.isNotEmpty()) { val path = paths.removeFirst() val currentPos = path.last() if (currentPos == finish) { return path.size - 1 } val (curX, curY) = currentPos val curH = heights[curX][curY] Direction.values() .map { d -> curX + d.dx to curY + d.dy } .filter { pos -> pos !in visited } .filter { (x, y) -> x in heights.indices && y in heights[x].indices } .filter { (x, y) -> heights[x][y] <= curH + 1 } .forEach { visited += it paths += path + it } } return 0 } companion object { fun fromLines(lines: List<String>): HeightMap { var start = 0 to 0 var finish = 0 to 0 val heights = Array(lines[0].length) { x -> Array(lines.size) { y -> when (val c = lines[y][x]) { 'S' -> 'a'.also { start = x to y } 'E' -> 'z'.also { finish = x to y } else -> c } - 'a' } } return HeightMap(heights, start, finish) } } }
0
Kotlin
0
0
584fa4d73f8589bc17ef56c8e1864d64a23483c8
2,400
advent-of-code-2022
Apache License 2.0
src/year2023/day04/Day04.kt
lukaslebo
573,423,392
false
{"Kotlin": 222221}
package year2023.day04 import check import readInput fun main() { val testInput = readInput("2023", "Day04_test") check(part1(testInput), 13) check(part2(testInput), 30) val input = readInput("2023", "Day04") println(part1(input)) println(part2(input)) } private fun part1(input: List<String>) = input.sumOf { line -> val wins = line.parseCard().winCount if (wins == 0) 0 else 1 shl (wins - 1) } private fun part2(input: List<String>): Int { val cards = input.map { it.parseCard() } val copiesByCard = cards.associateWith { 1 }.toMutableMap() cards.forEachIndexed { i, card -> val copies = copiesByCard.getValue(card) val nextCardRange = (i + 1) until (i + 1 + card.winCount) for (j in nextCardRange) { val cardToIncrease = cards.getOrNull(j) ?: break copiesByCard[cardToIncrease] = copiesByCard.getValue(cardToIncrease) + copies } } return copiesByCard.values.sum() } private data class Card( val id: Int, val winningNumbers: Set<Int>, val elfNumbers: List<Int>, val winCount: Int, ) private fun String.parseCard(): Card { val winningNumbers = substringAfter(": ") .substringBefore(" | ") .split(" ") .filter { it.isNotBlank() } .map { it.toInt() } .toSet() val elfNumbers = substringAfter(" | ") .split(" ") .filter { it.isNotBlank() } .map { it.toInt() } return Card( id = substringBefore(":").split(" ").last().toInt(), winningNumbers = winningNumbers, elfNumbers = elfNumbers, winCount = elfNumbers.count { it in winningNumbers }, ) }
0
Kotlin
0
1
f3cc3e935bfb49b6e121713dd558e11824b9465b
1,683
AdventOfCode
Apache License 2.0
src/Day03.kt
rounakdatta
540,743,612
false
{"Kotlin": 19962}
import kotlin.math.pow fun binaryToDecimal(input: List<Char>): Int { // pair of index, result return input.foldRight(Pair(-1, 0)) { bit, pairOfIndexAndResultSoFar -> Pair( pairOfIndexAndResultSoFar.first + 1, (pairOfIndexAndResultSoFar.second + bit.digitToInt() * 2.0.pow((pairOfIndexAndResultSoFar.first + 1))).toInt() ) } .second } fun getMostCommonElement(input: List<String>, position: Int): Char { return input .fold(0) { accumulator, binary -> accumulator + if (binary[position] == '1') 1 else 0 } .let { if (it >= (input.size - it)) '1' else '0' } } fun getLeastCommonElement(input: List<String>, position: Int): Char { return input .fold(0) { accumulator, binary -> accumulator + if (binary[position] == '1') 1 else 0 } .let { if (it >= (input.size - it)) '0' else '1' } } fun applyListReduction(input: List<String>, position: Int, reductionElement: Char): List<String> { return input .filter { it[position] == reductionElement } } fun computeOxygenGeneratorRating(input: List<String>, position: Int): Int { // 11010, 11111, 010101, 10010 (check at 0 position from left) // 11010, 11111, 10010 (check at 1 position from left) // 11010, 11111 (check at 2 position from left) // 11111 (answer) return when (input.size) { 1 -> binaryToDecimal(input.first().toList()) else -> { computeOxygenGeneratorRating( applyListReduction(input, position, getMostCommonElement(input, position)), position + 1 ) } } } fun computeCO2ScrubberRating(input: List<String>, position: Int): Int { return when (input.size) { 1 -> binaryToDecimal(input.first().toList()) else -> { computeCO2ScrubberRating( applyListReduction(input, position, getLeastCommonElement(input, position)), position + 1 ) } } } fun main() { fun part1(input: List<String>): Int { // List of lots of elements like [0, 0, 1, 1, 0] // [1s, 1s, 1s, 1s, 1s] -> count majority [10110] // Pair(gamma, epsilon) return input .map { it -> it.toList() } .fold(IntArray(input.first().length) { 0 }) { collectingList, binaryNumberAsList -> // TODO: this forEachIndexed mutates values directly, can be done better binaryNumberAsList.forEachIndexed { index, i -> collectingList[index] += if (i == '1') { 1 } else { 0 } } collectingList } // now I'll construct the gamma value .fold("") { collectingString, sumOf1sOnIndex -> collectingString + if (sumOf1sOnIndex > (input.size - sumOf1sOnIndex)) { "1" } else { "0" } } .toList() .let { Pair(binaryToDecimal(List(input.first().length) { '1' }), binaryToDecimal(it)) } .let { (it.first - it.second) * it.second } } fun part2(input: List<String>): Int { return input .let { it -> computeOxygenGeneratorRating(it, 0) * computeCO2ScrubberRating(it, 0) } } val input = readInput("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
130d340aa4c6824b7192d533df68fc7e15e7e910
3,551
aoc-2021
Apache License 2.0
src/main/kotlin/adventofcode2023/day17/day17.kt
dzkoirn
725,682,258
false
{"Kotlin": 133478}
package adventofcode2023.day17 import adventofcode2023.Point import adventofcode2023.pointsAround fun main() { val input = listOf( intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9) ) val minSumPath = findMinSumPath(input) } fun prepareInput(input: List<String>): List<IntArray> = input.map { l -> l.map { c -> "$c".toInt() }.toIntArray() } fun sumPath(input: List<IntArray>, path: List<Point>): Int = path.sumOf { (line, row) -> input[line][row] } fun visualize(input: List<IntArray>, path: List<Point>): String { val a = input.map { arr -> arr.joinToString("") { it.toString() }.toCharArray() } path.forEach { (line, row) -> a[line][row] = '#' } return a.map { it.joinToString("") { "$it" } }.joinToString("\n") { it } } fun isValidMove(x: Int, y: Int, rows: Int, cols: Int): Boolean { return x in 0 until rows && y in 0 until cols } fun findMinSumPath(input: List<IntArray>): List<Point> { val rows = input.size val cols = input[0].size val directions = listOf(Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0)) fun dfs(x: Int, y: Int, visited: Set<Point>, currentPath: List<Point>): List<Point> { if (x == rows - 1 && y == cols - 1) { return currentPath } var minPath: List<Point>? = null for (dir in directions) { val newX = x + dir.first val newY = y + dir.second if (isValidMove(newX, newY, rows, cols) && Point(newX, newY) !in visited) { val newPath = currentPath + Point(newX, newY) val newVisited = visited + Point(newX, newY) val resultPath = dfs(newX, newY, newVisited, newPath) println(resultPath) if (minPath == null || getPathSum(input, resultPath) < getPathSum(input, minPath)) { minPath = resultPath } } } return minPath ?: emptyList() } return dfs(0, 0, setOf(Point(0, 0)), listOf(Point(0, 0))) } fun getPathSum(input: List<IntArray>, path: List<Point>): Int { return path.sumBy { (x, y) -> input[x][y] } } //fun findMinSumPath(input: List<IntArray>): List<Point> { // val rows = input.size // val cols = input[0].size // // // Initialize a 2D array to store the minimum sum values // val minSum = Array(rows) { IntArray(cols) } // // // Initialize the first cell with its own value // minSum[0][0] = input[0][0] // // // Initialize the first row and column // for (i in 1 until rows) { // minSum[i][0] = minSum[i - 1][0] + input[i][0] // } // for (j in 1 until cols) { // minSum[0][j] = minSum[0][j - 1] + input[0][j] // } // // // Fill the rest of the minSum array // for (i in 1 until rows) { // for (j in 1 until cols) { // minSum[i][j] = input[i][j] + minOf(minSum[i - 1][j], minSum[i][j - 1]) // } // } // // // Reconstruct the path // val path = mutableListOf<Point>() // var i = rows - 1 // var j = cols - 1 // // while (i > 0 || j > 0) { // path.add(Point(i, j)) // if (i == 0) { // j-- // } else if (j == 0) { // i-- // } else { // if (minSum[i - 1][j] < minSum[i][j - 1]) { // i-- // } else { // j-- // } // } // } // // path.add(Point(0, 0)) // path.reverse() // // return path //}
0
Kotlin
0
0
8f248fcdcd84176ab0875969822b3f2b02d8dea6
3,486
adventofcode2023
MIT License
p06/src/main/kotlin/ChronalCoordinates.kt
jcavanagh
159,918,838
false
null
package p06 import common.file.readLines import java.awt.Point fun manhattan(a: Point, b: Point): Int { return Math.abs(a.x - b.x) + Math.abs(a.y - b.y) } fun edges(coords: List<Point>): List<Point> { //Find the edges - all these have "infinite" area val byX = coords.sortedBy { it.x } val byY = coords.sortedBy { it.y } val minXEdges = byX.filter { it.x == byX.first().x }.toTypedArray() val maxXEdges = byX.filter { it.x == byX.last().x }.toTypedArray() val minYEdges = byY.filter { it.y == byY.first().y }.toTypedArray() val maxYEdges = byY.filter { it.y == byY.last().y }.toTypedArray() return listOf(*minXEdges, *maxXEdges, *minYEdges, *maxYEdges) } fun <T> forLocationIn(coords: List<Point>, delegate: (Point) -> T) { val byX = coords.sortedBy { it.x } val byY = coords.sortedBy { it.y } //Build an inner grid to analyze val minX = byX.first().x val maxX = byX.last().x val minY = byY.first().y val maxY = byY.last().y for(x in minX..maxX) { for(y in minY..maxY) { delegate(Point(x, y)) } } } fun distsFrom(coords: List<Point>, point: Point): List<Pair<Point, Int>> { return coords.map { coord -> val dist = manhattan(point, coord) Pair(coord, dist) } } fun mostOwnedArea(coords: List<Point>): Pair<Point, Int> { //Returns an owner for each point and the distance fun findOwner(point: Point): Pair<Point, Int>? { val dists = distsFrom(coords, point).sortedBy { it.second } //Account for multiple owners if(dists[0].second == dists[1].second) return null return dists[0] } // O(yikes) var owners = mutableMapOf<Point, Int>() forLocationIn(coords) { point -> val owner = findOwner(point) if(owner != null) { if(!owners.containsKey(owner.first)) { owners[owner.first] = 1 } else { owners[owner.first] = owners[owner.first]!! + 1 } } } //Exclude edges val edges = edges(coords) return owners.filterKeys { !edges.contains(it) }.entries.sortedBy { it.value }.last().toPair() } fun proximityWithin(coords: List<Point>, maxDist: Int): Int { val validLocations = mutableListOf<Point>() forLocationIn(coords) { point -> val dists = distsFrom(coords, point) if(dists.map { it.second }.sum() < maxDist) { validLocations.add(point) } } return validLocations.size } fun main() { val coords = readLines("input.txt").map { val split = it.split(", ").map { str -> str.toInt() } Point(split.first(), split.last()) } val mostArea = mostOwnedArea(coords) val mostArea10K = proximityWithin(coords, 10000) println("Most area: ${mostArea.first.x},${mostArea.first.y} (${mostArea.second})") println("Area within 10K: $mostArea10K") }
0
Kotlin
0
0
289511d067492de1ad0ceb7aa91d0ef7b07163c0
2,722
advent2018
MIT License
src/twentytwentytwo/day16/Day16.kt
colinmarsch
571,723,956
false
{"Kotlin": 65403, "Python": 6148}
package twentytwentytwo.day16 import twentytwentytwo.day12.Graph import readInput fun main() { data class ValveNode( val id: String, val flowRate: Int, val neighbours: MutableSet<Pair<String, Int>>, ) val graph = mutableMapOf<String, ValveNode>() var availableMinutes = 30 val startValve by lazy { graph["AA"]!! } fun createGraph(input: List<String>): ValveNode { input .sortedBy { it.split(" ")[1] } .forEach { val id = it.split(" ")[1] val flowRate = it.split(" ")[4].dropLast(1).split("=")[1].toInt() val neighbours = it.split(" to ")[1].split(" ").drop(1).map { it.replace(",", "") } .map { Pair(it, 1) }.toMutableSet() val valveNode = ValveNode(id, flowRate, neighbours) graph[id] = valveNode } val weights = mutableMapOf<Pair<String, String>, Int>() graph.values.forEach { node -> node.neighbours.forEach { neighbour -> weights[Pair(node.id, neighbour.first)] = 1 } } val dijkstraGraph = Graph( vertices = graph.values.map { it.id }.toMutableSet(), edges = graph.values.map { it.id } .associateWith { graph[it]!!.neighbours.map { it.first }.toSet() }.toMutableMap(), weights = weights, ) graph.keys.forEach { id -> val currNode = graph[id]!! val otherNodes = graph.values.toSet() - currNode.neighbours.map { graph[it.first]!! } .toSet() - currNode val shortestPathTree = dijkstra(dijkstraGraph, currNode.id) otherNodes.forEach { other -> currNode.neighbours.removeIf { it.first == other.id } if (other.flowRate > 0) { val path = shortestPath(shortestPathTree, currNode.id, other.id) currNode.neighbours.add(Pair(other.id, path.size - 1)) } } } return graph["AA"]!! } var maxPressureReleased = 0 fun findMaxPath( releasedPressure: Int, position: ValveNode, visited: Set<ValveNode>, minute: Int, elephant: Boolean ) { maxPressureReleased = maxOf(releasedPressure, maxPressureReleased) position.neighbours.filter { graph[it.first]!!.flowRate > 0 }.forEach { (id, distance) -> val newMinute = minute + distance + 1 val candidate = graph[id]!! if (newMinute < availableMinutes && candidate !in visited) { findMaxPath( releasedPressure = releasedPressure + (availableMinutes - newMinute) * candidate.flowRate, position = candidate, visited = visited + candidate, minute = newMinute, elephant = elephant, ) } } if (elephant) { findMaxPath( releasedPressure = releasedPressure, position = startValve, visited = visited, minute = 0, elephant = false, ) } } fun part1(input: List<String>): Int { val root = createGraph(input) maxPressureReleased = 0 availableMinutes = 30 findMaxPath(0, root, emptySet(), 0, false) return maxPressureReleased } fun part2(input: List<String>): Int { val root = createGraph(input) maxPressureReleased = 0 availableMinutes = 26 findMaxPath(0, root, emptySet(), 0, true) return maxPressureReleased } val input = readInput("day16", "Day16_input") println(part1(input)) println(part2(input)) } private fun <T> dijkstra(graph: Graph<T>, start: T): Map<T, T?> { val vertexSet: MutableSet<T> = mutableSetOf() // a subset of vertices, for which we know the true distance val delta = graph.vertices.associateWith { 100000 }.toMutableMap() delta[start] = 0 val previous: MutableMap<T, T?> = graph.vertices.associateWith { null }.toMutableMap() while (vertexSet != graph.vertices) { val v: T = delta .filter { !vertexSet.contains(it.key) } .minBy { it.value } .key graph.edges.getValue(v).minus(vertexSet).forEach { neighbor -> val newPath = delta.getValue(v) + graph.weights.getValue(Pair(v, neighbor)) if (newPath < delta.getValue(neighbor)) { delta[neighbor] = newPath previous[neighbor] = v } } vertexSet.add(v) } return previous.toMap() } private fun <T> shortestPath(shortestPathTree: Map<T, T?>, start: T, end: T): List<T> { fun pathTo(start: T, end: T): List<T> { if (shortestPathTree[end] == null) return listOf(end) return listOf(pathTo(start, shortestPathTree[end]!!), listOf(end)).flatten() } return pathTo(start, end) }
0
Kotlin
0
0
bcd7a08494e6db8140478b5f0a5f26ac1585ad76
5,102
advent-of-code
Apache License 2.0
src/year_2022/day_15/Day15.kt
scottschmitz
572,656,097
false
{"Kotlin": 240069}
package year_2022.day_15 import readInput import util.Line import util.Point import util.crossingPoint import util.manhattanDistance import kotlin.math.abs data class Sensor( val position: Point, val closestBeaconPosition: Point, val closestBeaconDistance: Int ) object Day15 { /** * @return */ fun solutionOne(text: List<String>, row: Int): Int { val sensors = parseText(text) val sensorPositions = sensors.map { it.position } val beaconPositions = sensors.map { it.closestBeaconPosition } val maxBeaconDistance = sensors.maxOf { it.closestBeaconDistance } + 1 val minX = sensorPositions.minOf { it.first } - maxBeaconDistance val maxX = sensorPositions.maxOf { it.first } + maxBeaconDistance val impossibleLocations = (minX .. maxX) .filter { i -> val checkPosition = i to row checkPosition !in beaconPositions && checkPosition !in sensorPositions && sensors.any { sensor -> sensor.position.manhattanDistance(checkPosition) <= sensor.closestBeaconDistance } } return impossibleLocations.size } /** * @return */ fun solutionTwo(text: List<String>, maxSearchArea: Int): Long { val sensors = parseText(text) val linesOfInterest = sensors.flatMap { sensor -> getBoundaryLines(sensor.position, sensor.closestBeaconDistance + 1) } val pointsOfInterest = linesOfInterest .flatMap { line1 -> linesOfInterest.mapNotNull { line2 -> line1.crossingPoint(line2) } } .filter { (col, row) -> col in (0 .. maxSearchArea) && row in (0 .. maxSearchArea) } .distinct() return pointsOfInterest .filter { point -> sensors.all { sensor -> sensor.position.manhattanDistance(point) > sensor.closestBeaconDistance } } .map { (col, row) -> col * 4_000_000L + row } .single() } private fun parseText(text: List<String>): List<Sensor> { return text.map { line -> val split = line.split(" ") val sensorX = Integer.parseInt(split[2].split("=")[1].split(",")[0]) val sensorY = Integer.parseInt(split[3].split("=")[1].split(":")[0]) val beaconX = Integer.parseInt(split[8].split("=")[1].split(",")[0]) val beaconY = Integer.parseInt(split[9].split("=")[1]) Sensor( position = sensorX to sensorY, closestBeaconPosition = beaconX to beaconY, closestBeaconDistance = (sensorX to sensorY).manhattanDistance((beaconX to beaconY)) ) } } private fun getBoundaryLines(point: Point, distance: Int): List<Line> { val up = point.first to point.second - distance val down = point.first to point.second + distance val left = point.first - distance to point.second val right = point.first + distance to point.second return listOf( up to left, up to right, down to left, down to right ) } } fun main() { val inputText = readInput("year_2022/day_15/Day15.txt") val solutionOne = Day15.solutionOne(inputText, 2_000_000) println("Solution 1: $solutionOne") val solutionTwo = Day15.solutionTwo(inputText, 4_000_000) println("Solution 2: $solutionTwo") }
0
Kotlin
0
0
70efc56e68771aa98eea6920eb35c8c17d0fc7ac
3,443
advent_of_code
Apache License 2.0
advent-of-code-2023/src/Day19.kt
osipxd
572,825,805
false
{"Kotlin": 141640, "Shell": 4083, "Scala": 693}
private const val DAY = "Day19" fun main() { fun testInput() = readInput("${DAY}_test") fun input() = readInput(DAY) "Part 1" { part1(testInput()) shouldBe 19114 measureAnswer { part1(input()) } } "Part 2" { part2(testInput()) shouldBe 167409079868000 measureAnswer { part2(input()) } } } private fun part1(input: Pair<Map<String, Workflow>, List<Part>>): Int { val (workflows, parts) = input return parts .filter(workflows::test) .sumOf(Part::rating) } private fun part2(input: Pair<Map<String, Workflow>, List<Part>>): Long { val workflows = input.first val possibleRanges = mutableListOf<PartRange>() val queue = ArrayDeque<Pair<String, PartRange>>() queue.addFirst("in" to PartRange()) while (queue.isNotEmpty()) { val (workflowId, startRange) = queue.removeFirst() val workflow = workflows.getValue(workflowId) var range = startRange for (rule in workflow.rules) { val (passedRange, restOfRange) = range.splitBy(rule) if (passedRange != null) { when (rule.result) { "A" -> possibleRanges += passedRange "R" -> Unit else -> queue.addLast(rule.result to passedRange) } } range = restOfRange ?: break } } return possibleRanges.sumOf(PartRange::count) } private fun readInput(name: String): Pair<Map<String, Workflow>, List<Part>> { val (rawWorkflows, rawParts) = readText(name).split("\n\n").map { it.lines() } fun parseRule(rule: String): Rule { if (':' in rule) { val parameter = rule.first() val (rawValue, result) = rule.drop(2).split(":") val value = rawValue.toInt() return if (rule[1] == '>') Rule.Grater(result, parameter, value) else Rule.Lower(result, parameter, value) } else { return Rule.Constant(rule) } } fun parseWorkflow(line: String): Pair<String, Workflow> { val label = line.substringBefore('{') val rules = line.substringAfter('{').dropLast(1).split(",") return label to Workflow(rules.map(::parseRule)) } fun parsePart(line: String): Part { val parameters = line.trim('{', '}').split(",").associate { rawParam -> val (label, value) = rawParam.split("=") label.first() to value.toInt() } return Part(parameters) } return rawWorkflows.associate(::parseWorkflow) to rawParts.map(::parsePart) } private fun Map<String, Workflow>.test(part: Part): Boolean { var currentFlow = "in" while (true) { val workflow = getValue(currentFlow) when (val result = workflow.process(part)) { "A" -> return true "R" -> return false else -> currentFlow = result } } } private data class Workflow( val rules: List<Rule> ) { fun process(part: Part): String = rules.firstNotNullOf { it.process(part) } } private sealed interface Rule { val result: String fun process(part: Part): String? data class Constant(override val result: String) : Rule { override fun process(part: Part): String = result } data class Grater( override val result: String, val parameter: Char, val value: Int, ) : Rule { override fun process(part: Part): String? = result.takeIf { part.params.getValue(parameter) > value } } data class Lower( override val result: String, val parameter: Char, val value: Int, ) : Rule { override fun process(part: Part): String? = result.takeIf { part.params.getValue(parameter) < value } } } private data class Part( val params: Map<Char, Int>, ) { fun rating() = params.values.sum() } private data class PartRange( val params: Map<Char, IntRange> = mapOf( 'x' to 1..4000, 'm' to 1..4000, 'a' to 1..4000, 's' to 1..4000, ) ) { fun count() = params.values.map { it.last - it.first + 1L }.reduce(Long::times) fun splitBy(rule: Rule): Pair<PartRange?, PartRange?> = when (rule) { is Rule.Constant -> this to null is Rule.Grater -> { val ranges = params.getValue(rule.parameter).splitBy(rule.value + 1) ranges.reversed().map { range -> withParameterRange(rule.parameter, range) } } is Rule.Lower -> { val ranges = params.getValue(rule.parameter).splitBy(rule.value) ranges.map { range -> withParameterRange(rule.parameter, range) } } } private fun withParameterRange(parameter: Char, range: IntRange): PartRange? { if (range.isEmpty()) return null return PartRange(params = params + (parameter to range)) } } private fun IntRange.splitBy(secondRangeStart: Int): Pair<IntRange, IntRange> { return (first..<secondRangeStart) to (secondRangeStart..last) } private fun <A, B> Pair<A, B>.reversed(): Pair<B, A> = second to first private fun <T, R> Pair<T, T>.map(transform: (T) -> R): Pair<R, R> = transform(first) to transform(second)
0
Kotlin
0
5
6a67946122abb759fddf33dae408db662213a072
5,207
advent-of-code
Apache License 2.0
archive/2022/Day15.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
import kotlin.Int.Companion.MAX_VALUE import kotlin.math.absoluteValue private const val EXPECTED_1 = 26 private const val EXPECTED_2 = 56000011L private class Day15(isTest: Boolean) : Solver(isTest) { val data = readAsLines().map { line -> val (sensorStr, closestStr) = line.split("beacon") fun parsePoint(str: String) = str.split(",").let { (xStr, yStr) -> xStr.filter(Char::isDigit).toInt() to yStr.filter(Char::isDigit).toInt() } parsePoint(sensorStr) to parsePoint(closestStr) } fun ranges(y: Int) = buildList { data.forEach { (sensor, closest) -> val xWidth = (sensor.first - closest.first).absoluteValue + (sensor.second - closest.second).absoluteValue - (sensor.second - y).absoluteValue if (xWidth >= 0) { add(sensor.first - xWidth..sensor.first + xWidth) } } }.sortedBy { it.first } fun part1(): Any { val y = if (isTest) 10 else 2000000 val ranges = ranges(y) val xSet = data.mapNotNull { (_, beacon) -> if (beacon.second == y) beacon.first else null }.toSet() var result = 0 (ranges + listOf(MAX_VALUE..MAX_VALUE)).reduce { currentRange, next -> if (next.first > currentRange.last) { result += currentRange.last - currentRange.first + 1 next } else { currentRange.first..maxOf(next.last, currentRange.last) } } return result - xSet.size } fun part2(): Any { val size = if (isTest) 20 else 4000000 val beaconSet = data.map { (_, beacon) -> beacon }.toSet() for (y in 0 until size) { (ranges(y) + listOf(MAX_VALUE..MAX_VALUE)).reduce { currentRange, next -> if (next.first > currentRange.last + 1 && currentRange.last + 1 in 0 until size && currentRange.last + 1 to y !in beaconSet) { return y + (currentRange.last + 1) * 4000000L } currentRange.first..maxOf(next.last, currentRange.last) } } error("unexpected") } } fun main() { val testInstance = Day15(true) val instance = Day15(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,506
advent-of-code-2022
Apache License 2.0
y2021/src/main/kotlin/adventofcode/y2021/Day18.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2021 import adventofcode.io.AdventSolution object Day18 : AdventSolution(2021, 18, "Snailfish") { override fun solvePartOne(input: String): Int { val numbers = input.lines().map(::toSnailNumber) return numbers.reduce(SnailfishNumber::plus).magnitude() } override fun solvePartTwo(input: String): Int { val numbers = input.lines().map(::toSnailNumber) return numbers.flatMap { a -> numbers.filterNot(a::equals).map(a::plus) }.maxOf { it.magnitude() } } private fun toSnailNumber(s: String) = SnailfishNumber(buildList { var depth = 0 s.forEach { ch -> when (ch) { '[' -> depth++ ']' -> depth-- in '0'..'9' -> add(Element(ch - '0', depth)) } } }) private data class SnailfishNumber(val values: List<Element>) { operator fun plus(o: SnailfishNumber) = SnailfishNumber((values + o.values).map { it.addDepth(1) }).simplify() fun simplify(): SnailfishNumber = explode()?.simplify() ?: split()?.simplify() ?: this private fun explode(): SnailfishNumber? { val i = values.indexOfFirst { it.depth == 5 } return if (i < 0) null else SnailfishNumber(values.toMutableList().also { new -> val (left, _) = new.removeAt(i) val (right, _) = new.removeAt(i) new.add(i, Element(0, 4)) if (i - 1 in new.indices) new[i - 1] = new[i - 1].addValue(left) if (i + 1 in new.indices) new[i + 1] = new[i + 1].addValue(right) }) } private fun split(): SnailfishNumber? { val i = values.indexOfFirst { it.value > 9 } return if (i < 0) null else SnailfishNumber(values.toMutableList().also { new -> val (oldV, oldD) = new.removeAt(i) new.add(i, Element(oldV / 2, oldD + 1)) new.add(i + 1, Element((oldV + 1) / 2, oldD + 1)) }) } fun magnitude(): Int { val stack = mutableListOf<Element>() tailrec fun tryAdd(r: Element) { if ((stack.isEmpty() || stack.last().depth != r.depth)) stack.add(r) else tryAdd(stack.removeLast().magnitudeWith(r)) } values.forEach(::tryAdd) return stack.first().value } } private data class Element(val value: Int, val depth: Int) { fun addDepth(a: Int) = copy(depth = depth + a) fun addValue(a: Int) = copy(value = value + a) fun magnitudeWith(o: Element) = Element(value * 3 + o.value * 2, depth - 1) } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
2,697
advent-of-code
MIT License
src/main/kotlin/days/Day2.kt
MisterJack49
729,926,959
false
{"Kotlin": 31964}
package days class Day2 : Day(2) { override fun partOne(): Any { val max = Set(mapOf(Color.Red to 12, Color.Green to 13, Color.Blue to 14)) return inputList.parseInput() .map { game -> game to game.sets.all { it <= max } }.filter { it.second } .sumOf { it.first.id } } override fun partTwo(): Any = inputList.parseInput() .map { it.getMinimumSet() } .map { it.colors.values } .sumOf { it.fold(1, operation = { acc: Int, i: Int -> acc * i }) } } private data class Set(val colors: Map<Color, Int>) { operator fun compareTo(other: Set): Int { if (colors == other.colors) return 0 return if (colors.all { it.value <= other.colors[it.key]!! }) -1 else 1 } } private data class Game(val id: Int, val sets: List<Set>) { fun getMinimumSet() = Set(Color.values().associateWith { color -> sets.maxOf { it.colors[color]!! } }) } private enum class Color { Blue, Red, Green } private val colorRegex = Regex("((?<blue>\\d+) blue)|((?<red>\\d+) red)|((?<green>\\d+) green)+") private fun String.getColor(color: Color) = colorRegex.findAll(this) .map { result -> result.groups[color.name.lowercase()]?.value } .filterNotNull() .firstOrNull() ?.toInt() ?: 0 private fun List<String>.parseInput() = map { Game( it.split(":")[0].removePrefix("Game ").toInt(), it.split(":")[1].split(";").map { Set(Color.values().associateWith { color -> it.getColor(color) }) } ) }
0
Kotlin
0
0
807a6b2d3ec487232c58c7e5904138fc4f45f808
1,641
AoC-2023
Creative Commons Zero v1.0 Universal
src/Day23.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
private fun input(): Array<BooleanArray> { val gs = readInput("Day23") val padding = 100 val h = gs.size + 2 * padding val w = gs[0].length + 2 * padding val arr = Array(h) { BooleanArray(w) } gs.forEachIndexed { rowInd, row -> row.forEachIndexed { i, c -> arr[rowInd + padding][i + padding] = (c == '#') } } return arr } fun moveElves(g: Array<BooleanArray>, part1: Boolean): Int { val elves = HashSet<CC>() for (i in g.indices) for (j in g[0].indices) if (g[i][j]) elves.add(CC(i, j)) var d = 0 repeat(if (part1) 10 else Int.MAX_VALUE) { val moves = HashMap<CC, MutableList<Move>>() elves.forEach { e -> val hasN = g[e.i - 1][e.j] || g[e.i - 1][e.j + 1] || g[e.i - 1][e.j - 1] val hasS = g[e.i + 1][e.j] || g[e.i + 1][e.j + 1] || g[e.i + 1][e.j - 1] val hasW = g[e.i][e.j - 1] || g[e.i + 1][e.j - 1] || g[e.i - 1][e.j - 1] val hasE = g[e.i][e.j + 1] || g[e.i + 1][e.j + 1] || g[e.i - 1][e.j + 1] if (!hasN && !hasW && !hasS && !hasE) return@forEach val has = arrayOf(hasN, hasS, hasW, hasE) for (di in 0..3) { val elfD = (d + di) % 4 if (!has[elfD]) { val from = CC(e.i, e.j) val to = e.move(elfD) moves.getOrPut(to) { mutableListOf() }.add(Move(from, to)) break } } } val possibleMoves = moves.filter { (_, moves) -> moves.size == 1 } if (possibleMoves.isEmpty() && !part1) return it + 1 possibleMoves.forEach { (_, moves) -> val m = moves[0] g[m.from.i][m.from.j] = false g[m.to.i][m.to.j] = true elves.remove(m.from) elves.add(m.to) } d++ } return if (part1) findArea(elves) else -1 } private fun findArea(e: HashSet<CC>): Int { return (e.maxOf(CC::i) - e.minOf(CC::i) + 1) * (e.maxOf(CC::j) - e.minOf(CC::j) + 1) - e.size } fun main() { measure { moveElves(input(), true) } measure { moveElves(input(), false) } } private data class Move(val from: CC, val to: CC)
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
2,221
advent-of-code-2022
Apache License 2.0
src/Day15.kt
simonbirt
574,137,905
false
{"Kotlin": 45762}
import kotlin.math.abs import kotlin.math.max fun main() { Day15.printSolutionIfTest(26, 56000011) } object Day15: Day<Int, Long>(15) { override fun part1Test(lines: List<String>) = countPositions(lines, 10) override fun part1(lines: List<String>) = countPositions(lines, 2000000) override fun part2Test(lines: List<String>) = calculateFrequency(lines, 20) override fun part2(lines: List<String>) = calculateFrequency(lines, 4000000) private fun countPositions(lines: List<String>, row:Int):Int { val sensors = lines.map{ line -> parseSensor(line)} return points(sensors, row).flatten().distinct().count() -1 } private fun calculateFrequency(lines: List<String>, max: Int):Long { val sensors = lines.map{ line -> parseSensor(line)} val missing = (0 .. max).asSequence().map{ row -> IndexedValue(row, points(sensors,row)) } .map{ IndexedValue(it.index, gap(it.value, max)) }.filter { it.value != null } .first() return ( (missing.value!! * 4000000L) + missing.index) } private fun gap(ranges: List<IntRange>, max:Int):Int? { var lastMax = 0 for (r in ranges.sortedBy { it.first() }) { when { r.first > lastMax -> return lastMax+1 r.last() >= max -> return null else -> lastMax = max(lastMax, r.last) } } return null } private fun points(sensors: List<Sensor>, row:Int): List<IntRange> { return sensors.mapNotNull { s -> s.points(row) } } private fun parseSensor(line: String): Sensor { val (x, y, bx, by) = line.split("=", ",", ":").mapNotNull { it.toIntOrNull() } return Sensor(x ,y, bx, by) } data class Sensor(val x:Int, val y:Int, val bx:Int, val by:Int) { private val distance = abs(x - bx) + abs(y - by) fun points(lineHeight: Int):IntRange? { val xd = distance - abs(y-lineHeight) return if ( xd >= 0 ) { range(x-xd, x+xd) } else { null } } } private fun range(a:Int, b:Int) = minOf(a,b) .. maxOf(a,b) }
0
Kotlin
0
0
962eccac0ab5fc11c86396fc5427e9a30c7cd5fd
2,182
advent-of-code-2022
Apache License 2.0
src/Day11.kt
MarkTheHopeful
572,552,660
false
{"Kotlin": 75535}
class Monkey(val items: MutableList<Long>, val operation: (Long, Long?) -> Long, val testAndThrow: (Long) -> Int, val modulo: Long) { } fun main() { fun constructOperation(opToken: Char, value: Long?, divideBy: Long = 3): (Long, Long?) -> Long { return if (opToken == '*') { it: Long, modulo: Long? -> ((it * (value ?: it)) / divideBy) % (modulo ?: Long.MAX_VALUE) } else { it: Long, modulo: Long? -> ((it + (value ?: it)) / divideBy) % (modulo ?: Long.MAX_VALUE) } } fun constructTestAndThrow(testValue: Long, ifTrue: Int, ifFalse: Int): (Long) -> Int { return {it: Long -> if (it % testValue == 0L) ifTrue else ifFalse} } fun parseMonkey(monkeyDesc: List<String>, shouldDivide: Boolean = true): Monkey { val items = monkeyDesc[1].split(" ").drop(4).map{it.removePrefix(",").removeSuffix(",").toInt()} val operationTokens = monkeyDesc[2].split(" ").drop(6).also {println(it)} val operation = constructOperation(operationTokens[0][0], operationTokens[1].toLongOrNull(), if (shouldDivide) 3 else 1) val testValue = monkeyDesc[3].split(" ").takeLast(1)[0].toLong() val ifTrue = monkeyDesc[4].split(" ").takeLast(1)[0].toInt() val ifFalse = monkeyDesc[5].split(" ").takeLast(1)[0].toInt() val testAndThrow = constructTestAndThrow(testValue, ifTrue, ifFalse) return Monkey(items as MutableList<Long>, operation, testAndThrow, testValue) } fun part1(input: List<String>): Int { val monks = input.chunked(7).map(::parseMonkey) val counters = MutableList(monks.size) {0} repeat(20) { monks.withIndex().forEach {(i, monkey) -> monkey.items.forEach { counters[i]++ val newWorry = monkey.operation(it, null) monks[monkey.testAndThrow(newWorry)].items.add(newWorry) } monkey.items.clear() } } return counters.sorted().takeLast(2).fold(1, Int::times) } fun part2(input: List<String>): Long { val monks = input.chunked(7).map{parseMonkey(it, false)} val counters = MutableList(monks.size) {0L} val modulo: Long = monks.map {it.modulo}.fold(1, Long::times) repeat(10000) { monks.withIndex().forEach {(i, monkey) -> monkey.items.forEach { counters[i]++ val newWorry = monkey.operation(it, modulo) monks[monkey.testAndThrow(newWorry)].items.add(newWorry) } monkey.items.clear() } } return counters.sorted().takeLast(2).fold(1, Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605) check(part2(testInput) == 2713310158) val input = readInput("Day11") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8218c60c141ea2d39984792fddd1e98d5775b418
3,030
advent-of-kotlin-2022
Apache License 2.0
src/Day12.kt
buczebar
572,864,830
false
{"Kotlin": 39213}
private typealias MapOfHeights = List<List<Char>> private fun Char.elevation() = when (this) { 'S' -> 0 // a 'E' -> 25 // z else -> ('a'..'z').indexOf(this) } private fun MapOfHeights.getFirstPositionOf(mark: Char): Position { forEachIndexed { index, row -> if (row.contains(mark)) { return row.indexOf(mark) to index } } return -1 to -1 } private fun MapOfHeights.getAllPositionsWithElevation(elevation: Int): List<Position> { val positions = mutableListOf<Position>() forEachIndexed { colIndex, items -> items.forEachIndexed { rowIndex, item -> if (item.elevation() == elevation) { positions.add(rowIndex to colIndex) } } } return positions } private fun MapOfHeights.getPossibleMoves(position: Position): List<Position> { val currentHeight = this[position.y][position.x].elevation() val directions = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1) return directions .map { direction -> position + direction } .filter { it.x in first().indices && it.y in indices } .filter { this[it.y][it.x].elevation() - currentHeight <= 1 } } private fun MapOfHeights.findShortestPathLength( start: Position, destination: Position ): Int { val queue = mutableListOf(start) val visited = mutableSetOf(start) val predecessors = mutableMapOf<Position, Position>() while (queue.isNotEmpty()) { val currentItem = queue.popHead() val availableMoves = getPossibleMoves(currentItem) availableMoves.forEach { next -> if (!visited.contains(next)) { visited.add(next) predecessors[next] = currentItem queue.add(next) if (next == destination) { queue.clear() return@forEach } } } } var lenth = 0 var crawl: Position? = destination while (predecessors[crawl] != null) { crawl = predecessors[crawl] lenth++ } return lenth } fun main() { fun part1(mapOfHeights: MapOfHeights): Int { val (start, destination) = mapOfHeights.getFirstPositionOf('S') to mapOfHeights.getFirstPositionOf('E') return mapOfHeights.findShortestPathLength(start, destination) } fun part2(mapOfHeights: MapOfHeights): Int { val allStartingPoints = mapOfHeights.getAllPositionsWithElevation(0) val destination = mapOfHeights.getFirstPositionOf('E') val allPaths = allStartingPoints.map { startingPoint -> mapOfHeights.findShortestPathLength( startingPoint, destination ) } return allPaths.filter { it != 0 }.min() } val testInput = readInput("Day12_test").map { it.toList() } check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12").map { it.toList() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
cdb6fe3996ab8216e7a005e766490a2181cd4101
3,052
advent-of-code
Apache License 2.0
src/Day16.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { val input = readInput("Day16") val dirs = listOf(0 to 1, 1 to 0, 0 to -1, -1 to 0) // east south west north fun solve(s0: Triple<Int,Int,Int>): Int { val visited = Array(input.size) { Array(input[it].length) { BooleanArray(4) } } val queue = ArrayDeque<Triple<Int, Int, Int>>() fun addQ(i: Int, j: Int, d: Int) { if (i in input.indices && j in input[i].indices && !visited[i][j][d]) { queue.add(Triple(i,j,d)) visited[i][j][d] = true } } visited[s0.first][s0.second][s0.third] = true queue.add(s0) while (queue.isNotEmpty()) { val (i,j,d) = queue.removeFirst() fun go() { val (di, dj) = dirs[d] addQ(i+di, j+dj, d) } when (input[i][j]) { '.' -> go() '/' -> { val en = listOf(0, 3) val sw = listOf(1, 2) val d1 = (en - d).singleOrNull() ?: (sw - d).single() val (di, dj) = dirs[d1] addQ(i+di, j+dj, d1) } '\\' -> { val es = listOf(0, 1) val wn = listOf(2, 3) val d1 = (es - d).singleOrNull() ?: (wn - d).single() val (di, dj) = dirs[d1] addQ(i+di, j+dj, d1) } '|' -> { if (d == 0 || d == 2) { addQ(i-1, j, 3) addQ(i+1, j, 1) } else { go() } } '-' -> { if (d == 1 || d == 3) { addQ(i, j-1, 2) addQ(i, j+1, 0) } else { go() } } } } return visited.sumOf { vi -> vi.count { vj -> vj.any { it } } } } println(solve(Triple(0, 0, 0))) val edges = input.indices.flatMap { i -> listOf(Triple(i, 0, 0), Triple(i, input[i].lastIndex, 2)) } + input[0].indices.flatMap { j -> listOf(Triple(0, j, 1), Triple(input.lastIndex, j, 3)) } println(edges.maxOf { solve(it) }) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
2,397
advent-of-code-kotlin
Apache License 2.0
src/day19/a/day19a.kt
pghj
577,868,985
false
{"Kotlin": 94937}
package day19.a import readInputLines import shouldBe import util.IntVector import vec import java.util.regex.Pattern import kotlin.math.max fun main() { val input = read() var answer = 0 input.forEach { answer += it.num * simulate(it, 24) } shouldBe(1266, answer) } fun simulate(bp: BluePrint, minutes: Int): Int { var best = 0 fun addResult(outcome: Int) { best = max(best, outcome) } fun chooseNextRobot(bp: BluePrint, state: State) { if (state.minute == minutes) return addResult(state.produceOnly().stuff[3]) // Suppose we can afford to build a geode-cracking robot in every remaining minute. // Would that be enough to improve on the best result so far? val optimisticEstimate = state.stuff[3] + (minutes-state.minute+1) * state.bots[3] + (minutes-state.minute) * (minutes-state.minute+1) /2 if (optimisticEstimate < best) return for (i in 0..3) { if (canProduce(i, bp, state) && isNotAtMax(i, bp, state) ) { var s = state while(s.minute <= minutes && !canAfford(i, bp, s)) s = s.produceOnly() if (s.minute <= minutes) s = s.buildRobotAndProduce(i, bp) if (s.minute <= minutes) chooseNextRobot(bp, s) else addResult(s.stuff[3]) } } } val start = State( 1, vec(1,0,0,0), // robots vec(0,0,0,0), // stuff ) chooseNextRobot(bp, start) return best } fun isNotAtMax(bot: Int, bp: BluePrint, state: State): Boolean { if (bot == 3) return true return bp.cost.map { it[bot] }.max() > state.bots[bot] } fun canAfford(i: Int, bp: BluePrint, state: State): Boolean { return (0..3).all { j -> bp.cost[i][j] <= state.stuff[j] } } fun canProduce(i: Int, bp: BluePrint, state: State): Boolean { return (0..3).all { j -> bp.cost[i][j] == 0 || state.bots[j] > 0 } } data class State( val minute: Int, val bots: IntVector, val stuff: IntVector, ) { fun produceOnly(): State { return State( minute+1, bots, stuff + bots, ) } fun buildRobotAndProduce(bot: Int, bp: BluePrint): State { return State( minute+1, bots + IntVector.unit(4, bot), stuff + bots - bp.cost[bot], ) } } data class BluePrint( val num: Int, val cost: List<IntVector> ) fun read(): List<BluePrint> { return readInputLines(19) .filter { it.isNotBlank() } .map { line -> val a = line.split(Pattern.compile("[^0-9]+")).filter { it.isNotBlank() }.map { it.toInt() }.toList() val cost = ArrayList<IntVector>() cost.add(vec(a[1], 0, 0, 0)) cost.add(vec(a[2], 0, 0, 0)) cost.add(vec(a[3], a[4], 0, 0)) cost.add(vec(a[5], 0, a[6], 0)) BluePrint(a[0], cost) } }
0
Kotlin
0
0
4b6911ee7dfc7c731610a0514d664143525b0954
2,969
advent-of-code-2022
Apache License 2.0
src/day12/solution.kt
bohdandan
729,357,703
false
{"Kotlin": 80367}
package day12 import println import readInput fun main() { var UNKNOWN = '?' var WORKING = '.' var BROKEN = '#' fun findVariations(input: Pair<String, List<Int>>): Long { var map = input.first var blocks = input.second var cache = mutableMapOf<Triple<Int, Int, Int>, Long>() fun solve(mapIndex: Int, blockIndex: Int, positionInBlock: Int): Long { var key = Triple(mapIndex, blockIndex, positionInBlock) if (cache.containsKey(key)) return cache[key]!! if (mapIndex == map.length) { return when { blockIndex == blocks.size && positionInBlock == 0 -> 1L blockIndex == blocks.size - 1 && blocks[blockIndex] == positionInBlock -> 1L else -> 0L } } var result = 0L if (map[mapIndex] == WORKING || map[mapIndex] == UNKNOWN) { if (positionInBlock == 0) { result += solve(mapIndex + 1, blockIndex, 0) } else if (positionInBlock > 0 && blockIndex < blocks.size && blocks[blockIndex] == positionInBlock) { result += solve(mapIndex + 1, blockIndex + 1, 0) } } if (map[mapIndex] == BROKEN || map[mapIndex] == UNKNOWN) { result += solve(mapIndex + 1, blockIndex, positionInBlock + 1) } cache[key] = result return result } var variations = solve(0,0,0) "${input.first} ::: ${input.second} -> $variations".println() return variations } fun parse(input: String): Pair<String, List<Int>> { var parts = input.split(" ") return Pair(parts[0], parts[1].split(",").map { it.toInt() }) } fun unfold(input: Pair<String, List<Int>>): Pair<String, List<Int>> { var map = List(5) {input.first}.joinToString("?") return Pair(map, List(5) { input.second }.flatten()) } check(findVariations(parse("???.### 1,1,3")) == 1L) check(findVariations(parse(".??..??...?##. 1,1,3")) == 4L) check(findVariations(parse("?###???????? 3,2,1")) == 10L) check(readInput("day12/test1").map(::parse).sumOf(::findVariations) == 21L) "Part 1:".println() readInput("day12/input").map(::parse).sumOf(::findVariations).println() check(readInput("day12/test1").map(::parse) .map(::unfold) .map(::findVariations) .sum() == 525152L) "Part 2:".println() readInput("day12/input").map(::parse) .map(::unfold) .sumOf(::findVariations).println() }
0
Kotlin
0
0
92735c19035b87af79aba57ce5fae5d96dde3788
2,636
advent-of-code-2023
Apache License 2.0
src/Day04.kt
geodavies
575,035,123
false
{"Kotlin": 13226}
fun String.toPairOfAssignments(): Pair<Pair<Int, Int>, Pair<Int, Int>> { val pairs = split(",") val assignment1 = pairs[0].split("-") val assignment2 = pairs[1].split("-") return (assignment1[0].toInt() to assignment1[1].toInt()) to (assignment2[0].toInt() to assignment2[1].toInt()) } fun isContained(firstAssignment: Pair<Int, Int>, secondAssignment: Pair<Int, Int>) = if (firstAssignment.first >= secondAssignment.first && firstAssignment.second <= secondAssignment.second) { true } else secondAssignment.first >= firstAssignment.first && secondAssignment.second <= firstAssignment.second fun doTheyOverlap(firstAssignment: Pair<Int, Int>, secondAssignment: Pair<Int, Int>) = if (firstAssignment.first >= secondAssignment.first && firstAssignment.first <= secondAssignment.second) { true } else firstAssignment.second >= secondAssignment.first && firstAssignment.second <= secondAssignment.second fun main() { fun part1(input: List<String>) = input .map(String::toPairOfAssignments) .map { if (isContained(it.first, it.second)) { 1 } else { 0 } }.sumAll() fun part2(input: List<String>) = input .map(String::toPairOfAssignments) .map { if (isContained(it.first, it.second) || doTheyOverlap(it.first, it.second)) { 1 } else { 0 } }.sumAll() // test if implementation meets criteria from the description, like: val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d04a336e412ba09a1cf368e2af537d1cf41a2060
1,762
advent-of-code-2022
Apache License 2.0
src/Day11.kt
AxelUser
572,845,434
false
{"Kotlin": 29744}
import java.util.* data class Monkey( val items: Queue<Long>, val operation: (old: Long) -> Long, val test: Long, val trueBranch: Int, val falseBranch: Int ) fun main() { fun List<String>.monkeys(): List<Monkey> { val res = mutableListOf<Monkey>() for (data in filter { it != "" }.map { it.trim() }.windowed(6, 6)) { val items = LinkedList(Regex("\\d+").findAll(data[1]).map { it.value.toLong() }.toMutableList()) val func = if (data[2].contains("+")) { a: Long, b: Long -> a + b } else { a: Long, b: Long -> a * b } val op = data[2].split(" ").last().let { when (it) { "old" -> { old: Long -> func(old, old) } else -> { old: Long -> func(old, it.toLong()) } } } val test = data[3].split(" ").last().toLong() val tb = data[4].split(" ").last().toInt() val fb = data[5].split(" ").last().toInt() res.add(Monkey(items, op, test, tb, fb)) } return res } fun solve(monkeys: List<Monkey>, rounds: Int, lower: (v: Long) -> Long): Long { val stats = LongArray(monkeys.size) repeat(rounds) { for ((i, m) in monkeys.withIndex()) { while (m.items.isNotEmpty()) { stats[i]++ val newValue = lower(m.operation(m.items.poll())) if (newValue % m.test == 0L) { monkeys[m.trueBranch].items.offer(newValue) } else { monkeys[m.falseBranch].items.offer(newValue) } } } } return stats.sortedArrayDescending().take(2).let { it[0] * it[1] } } fun part1(input: List<String>): Long { val monkeys = input.monkeys() return solve(monkeys, 20) { it / 3 } } fun part2(input: List<String>): Long { val monkeys = input.monkeys() val modulo = monkeys.map { it.test }.fold(1L) { acc, el -> acc * el } return solve(monkeys, 10000) { it % modulo} } check(part1(readInput("Day11_test")) == 10605L) check(part2(readInput("Day11_test")) == 2713310158) println(part1(readInput("Day11"))) println(part2(readInput("Day11"))) }
0
Kotlin
0
1
042e559f80b33694afba08b8de320a7072e18c4e
2,340
aoc-2022
Apache License 2.0
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day05.kt
dvdmunckhof
318,829,531
false
{"Kotlin": 195848, "PowerShell": 1266}
package com.dvdmunckhof.aoc.event2023 class Day05(input: List<String>) { private val seeds = input[0].split(' ').drop(1).map(String::toLong) private val mappings = input.drop(1).map { chunk -> chunk.lines() .drop(1) .map { line -> val values = line.split(' ').map(String::toLong) MappingEntry(values[1]..<values[1] + values[2], values[0]) } .sortedBy { it.src.first } } fun solvePart1(): Long { return seeds.minOf { seed -> mappings.fold(seed) { n, mapping -> mapping.firstOrNull { entry -> n in entry.src }?.map(n) ?: n } } } fun solvePart2(): Long { return seeds.windowed(2, 2) .map { range -> range[0]..<range[0] + range[1] } .minOf { process(0, it) } } private fun process(mappingIndex: Int, range: LongRange): Long { val mapping = mappings[mappingIndex] val ranges = process(mapping, 0, range) if (mappingIndex == mappings.lastIndex) { return ranges.minOf { it.first } } return ranges.minOf { r -> process(mappingIndex + 1, r) } } private fun process(mapping: List<MappingEntry>, fromEntryIndex: Int, range: LongRange): Array<LongRange> { for (i in fromEntryIndex..mapping.lastIndex) { val entry = mapping[i] val entrySrc = entry.src // case 1: seed range is bigger than mapping if (range.first > entrySrc.last) { continue // skip mapping } // case 2: seed range is smaller than mapping if (range.last < entrySrc.first) { break // mappings are sorted, so no other matches will be found } // case 3: seed range is fully covered by mapping if (range in entrySrc) { return arrayOf(entry.map(range.first)..entry.map(range.last)) } // case 4: seed range overlaps start of mapping if (range.last in entrySrc) { return arrayOf( range.first..<entrySrc.first, entry.dst..entry.map(range.last), ) } // case 5: seed range overlaps end of mapping if (range.first in entrySrc) { return arrayOf( entry.map(range.first)..entry.map(entrySrc.last), *process(mapping, i + 1, entrySrc.last + 1..range.last), ) } // case 6: middle of seed range is covered by mapping if (entrySrc in range) { return arrayOf( range.first..<entrySrc.first, entry.dst..entry.map(entrySrc.last), *process(mapping, i + 1, entrySrc.last + 1..range.last), ) } } return arrayOf(range) } private data class MappingEntry(val src: LongRange, val dst: Long) { fun map(n: Long): Long = dst - src.first + n } private operator fun LongRange.contains(other: LongRange): Boolean { return other.first in this && other.last in this } }
0
Kotlin
0
0
025090211886c8520faa44b33460015b96578159
3,252
advent-of-code
Apache License 2.0
src/Day21.kt
thpz2210
575,577,457
false
{"Kotlin": 50995}
private class Solution21(input: List<String>) { val monkeys = input .map { it.split(": ", " ") } .map { if (it.size == 2) Monkey(id = it[0], number = it[1].toLong()) else Monkey( id = it[0], operation = it[2], left = it[1], right = it[3] ) } .associateBy { it.id }.toMutableMap() fun part1() = computeNumber("root") fun part2(): Long { monkeys.values.forEach { it.computed = null } val root = monkeys["root"]!! monkeys[root.id] = Monkey(root.id, operation = "-", left = root.left, right = root.right) return computeHumn(root.id, 0) } private fun computeHumn(monkeyId: String, expected: Long): Long { val monkey = monkeys[monkeyId]!! if (monkeyId == "humn") return expected if (computeChildren(monkey.left!!).contains("humn")) { val opposite = computeNumber(monkey.right!!) return when (monkey.operation) { "+" -> computeHumn(monkey.left, expected - opposite) "-" -> computeHumn(monkey.left, expected + opposite) "*" -> computeHumn(monkey.left, expected / opposite) "/" -> computeHumn(monkey.left, expected * opposite) else -> throw IllegalArgumentException() } } else if (computeChildren(monkey.right!!).contains("humn")) { val opposite = computeNumber(monkey.left) return when (monkey.operation) { "+" -> computeHumn(monkey.right, expected - opposite) "-" -> computeHumn(monkey.right, opposite - expected) "*" -> computeHumn(monkey.right, expected / opposite) "/" -> computeHumn(monkey.right, opposite / expected) else -> throw IllegalArgumentException() } } throw IllegalStateException() } fun computeNumber(monkeyId: String): Long { val monkey = monkeys[monkeyId]!! if (monkey.number != null) { monkey.computed = monkey.number } else { monkey.computed = when (monkey.operation) { "+" -> computeNumber(monkey.left!!) + computeNumber(monkey.right!!) "-" -> computeNumber(monkey.left!!) - computeNumber(monkey.right!!) "*" -> computeNumber(monkey.left!!) * computeNumber(monkey.right!!) "/" -> computeNumber(monkey.left!!) / computeNumber(monkey.right!!) else -> throw IllegalArgumentException() } } return monkey.computed!! } fun computeChildren(monkeyId: String): Set<String> { val monkey = monkeys[monkeyId]!! return if (monkey.left == null || monkey.right == null) setOf(monkeyId) else computeChildren(monkey.left).union(computeChildren(monkey.right)) } data class Monkey( val id: String, var number: Long? = null, val operation: String? = null, val left: String? = null, val right: String? = null, var computed: Long? = null, val children: Set<String> = mutableSetOf() ) } fun main() { val testSolution = Solution21(readInput("Day21_test")) check(testSolution.part1() == 152L) check(testSolution.part2() == 301L) val solution = Solution21(readInput("Day21")) println(solution.part1()) println(solution.part2()) }
0
Kotlin
0
0
69ed62889ed90692de2f40b42634b74245398633
3,493
aoc-2022
Apache License 2.0
src/Day12.kt
WhatDo
572,393,865
false
{"Kotlin": 24776}
import kotlin.time.ExperimentalTime import kotlin.time.measureTime @OptIn(ExperimentalTime::class) fun main() { val input = readInput("Day12") val graph = Graph.create(input) val time = measureTime { val start = requireNotNull(graph.nodes.find { it.value == 'S' }) val stepsFromStart = bfs(graph, start) println("Steps from 'S' to 'E' = $stepsFromStart") } println("took $time") val time2 = measureTime { val shortest = graph.nodes.filter { node -> node.value.asElevation() == 'a' } .map { bfs(graph, it) } .filter { it != -1 } .min() println("Shortest trail is $shortest steps") } println("took $time2") } private fun bfs(graph: Graph, start: Node): Int { val visited = mutableSetOf(start) val queue = ArrayDeque<Pair<Int, Node>>(graph.nodes.size) queue.addLast(0 to start) val path = mutableMapOf<Node, Node>() while (queue.isNotEmpty()) { val (step, node) = queue.removeFirst() if (node.value == 'E') { return step } node.neighbors(graph) .filter(node::canGoTo) .filter(visited::add) .forEach { neighbor -> queue.addLast(step + 1 to neighbor) path[neighbor] = node } } return -1 } private class Graph(val nodes: List<Node>, val width: Int, val height: Int) { fun get(x: Int, y: Int): Node? { if (x !in 0 until width || y !in 0 until height) { return null } return nodes[getIndex(x, y)] } private fun getIndex(x: Int, y: Int): Int { return x + y * width } companion object { fun create(graph: List<String>): Graph { val width = graph[0].length val height = graph.size val nodes = graph.flatMapIndexed { y, row -> row.mapIndexed { x, c -> Node(c, x, y) } } return Graph(nodes, width, height) } } } private data class Node(val value: Char, val x: Int, val y: Int) private fun Node.neighbors(graph: Graph): List<Node> { return listOf(x - 1 to y, x + 1 to y, x to y - 1, x to y + 1) .mapNotNull { (x, y) -> graph.get(x, y) } } private fun Node.canGoTo(other: Node) = (value.asElevation() - other.value.asElevation()) >= -1 private fun Char.asElevation() = when (this) { 'S' -> 'a' 'E' -> 'z' else -> this }
0
Kotlin
0
0
94abea885a59d0aa3873645d4c5cefc2d36d27cf
2,464
aoc-kotlin-2022
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day13/day13.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day13 import java.lang.RuntimeException fun part1(arrival: Int, buses: List<Int?>): Int { val departures = buses.filterNotNull() val longestBus = departures.maxOrNull() ?: throw RuntimeException("Wrong departures list") for (i in arrival until arrival + longestBus) { for (departure in departures) { if ((i).rem(departure) == 0) { return (i - arrival) * departure } } } throw RuntimeException("No bus found") } fun part2(departures: List<Int?>): Long { // ETA 3h 40m 52s val maxDeparture = departures.withIndex().filter { it.value != null }.maxByOrNull { it.value!! } ?: throw RuntimeException("No max departure found") var timestamp = maxDeparture.value!!.toLong() - maxDeparture.index var found: Boolean while (true) { found = true for (i in departures.indices) { val departure = departures[i] ?: continue if ((timestamp + i).rem(departure) != 0L) { timestamp += maxDeparture.value!! found = false break } } if (found) { break } } return timestamp } inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long { var sum = 0L for (element in this) { sum += selector(element) } return sum } data class GCD( var a: Long, var x: Long, var b: Long, var y: Long ) fun gcdExtended(a: Long, b: Long): GCD { if (a == 0L) { return GCD(a, 0, b, 1) } val gcd = gcdExtended(b % a, a) val x = gcd.y - b / a * gcd.x val y = gcd.x return GCD(a, x, b, y) } /*** * Based on http://ww2.ii.uj.edu.pl/~wilczak/ilo/pdf/twierdzenie_chinskie.pdf */ fun chineseRemainderTheorem(a: List<Long>, n: List<Int>): Long { val N = a.reduce { acc, i -> acc * i } val Ni = a.map { N / it } val x = a.zip(Ni) .map { gcdExtended(it.first, it.second) } .zip(n) .sumByLong { it.first.b * it.first.y * it.second } .rem(N) return if (x < 0) x + N else x } fun fastPart2(departures: List<Long?>): Long { val values = departures.mapIndexedNotNull { index, i -> if (i != null) IndexedValue(index, i) else i } return chineseRemainderTheorem(values.map { it.value }, values.map { -it.index }) } fun main() { val notes = {}::class.java.getResource("/day13.in") .readText() .split("\n") val arrival = notes[0].toInt() val departures = notes[1].split(",").map { if (it == "x") null else it.toInt() } println("Answer part 1: ${part1(arrival, departures)}") // println("Answer part 2: ${part2(departures)}") // Just don't println("Answer part 2: ${fastPart2(departures.map { it?.toLong() })}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
2,803
advent-of-code-2020
Do What The F*ck You Want To Public License
src/Day13.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 405 private const val EXPECTED_2 = 400 private class Day13(isTest: Boolean) : Solver(isTest) { fun List<String>.transpose(): List<String> { val Y = this.size val X = this[0].length val res = List(X) { CharArray(Y) } for (y in 0 until Y) { for (x in 0 until X) { res[x][y] = this[y][x] } } return res.map { it.joinToString("") } } fun findSymmetry(field: List<String>, unequalTarget: Int = 0): Int { val Y = field.size val X = field[0].length for (i in 0 until X - 1) { var unequal = 0 for (a in 0..i) { val other = (i - a) + i + 1 if (other >= X) { continue } unequal += (0 until Y).count { field[it][a] != field[it][other] } } if (unequal == unequalTarget) { return i + 1 } } return -1 } fun part1(): Any { return readAsString().split("\n\n").map { it.split("\n") }.sumOf { field -> val col = findSymmetry(field) val row = findSymmetry(field.transpose()) check(col != -1 || row != -1) if (col == -1) { 100 * row } else { col } } } fun part2(): Any { return readAsString().split("\n\n").map { it.split("\n") }.sumOf { field -> val col = findSymmetry(field, 1) val row = findSymmetry(field.transpose(), 1) check(col != -1 || row != -1) if (col == -1) { 100 * row } else { col } } } } fun main() { val testInstance = Day13(true) val instance = Day13(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println("part1 ANSWER: ${instance.part1()}") testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } println("part2 ANSWER: ${instance.part2()}") } }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
2,156
advent-of-code-2022
Apache License 2.0
src/Day07.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
fun main() { data class Node(val name: String) { private var sizeOfFiles: Int = 0 private val children: MutableMap<String, Node> = mutableMapOf() fun addFile(size: Int) { sizeOfFiles += size } val size: Int get() = sizeOfFiles + children.values.sumOf { it.size } fun addChild(name: String): Node = children.getOrPut(name) { Node(name) } fun findNodesByCriteria(filter: (Node) -> Boolean): List<Node> = children.values.filter(filter) + children.values.flatMap { it.findNodesByCriteria(filter) } } fun buildTree(input: List<String>): Node { val stack = ArrayDeque<Node>() input.forEach { line -> when { line=="$ ls" -> {} line.startsWith("dir") -> {} line.startsWith("$ cd") -> { val (_, _, arg) = line.split(" ") when (arg) { "/" -> stack.addFirst(Node("/")) ".." -> stack.removeFirst() else -> stack.addFirst(stack.first().addChild(arg)) } } else -> { val (size) = line.split(" ") stack.first().addFile(size.toInt()) } } } return stack.last() } fun part1(input: List<String>): Int { return buildTree(input) .findNodesByCriteria { it.size <= 100000 } .sumOf { it.size } } fun part2(input: List<String>): Int { val totalSpace = 70000000 val requiredSpace = 30000000 val tree = buildTree(input) val unusedSpace = totalSpace - tree.size val spaceNeeded = requiredSpace - unusedSpace return tree .findNodesByCriteria { it.size >= spaceNeeded } .minBy { it.size } .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
376512583af723b4035b170db1fa890eb32f2f0f
2,214
advent2022
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2021/day13/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day13 import com.kingsleyadio.adventofcode.util.readInput import kotlin.math.max fun part1(dots: Set<Point>, command: Point): Int { return fold(dots, command).size } fun part2(dots: Set<Point>, commands: List<Point>): String { val folded = commands.fold(dots) { acc, command -> fold(acc, command) } val x = commands.last { (x, _) -> x > 0 }.x val y = commands.last { (_, y) -> y > 0 }.y return buildString { for (i in 0..y) { for (j in 0..x) append(if (Point(j, i) in folded) '#' else ' ').append(' ') append('\n') } } } fun fold(dots: Set<Point>, command: Point): Set<Point> { val (x, y) = command val full = max(x, y) shl 1 return buildSet { for (dot in dots) { val (dotX, dotY) = dot if ((x > 0 && dotX < x) || (y > 0 && dotY < y)) add(dot) else if (x in 1 until dotX) add(Point(full - dotX, dotY)) else if (y in 1 until dotY) add(Point(dotX, full - dotY)) } } } data class Point(val x: Int, val y: Int) fun List<Int>.toPoint() = Point(this[0], this[1]) fun main() { val dots = hashSetOf<Point>() val commands = arrayListOf<Point>() var isDots = true readInput(2021, 13).forEachLine { line -> if (line.isEmpty()) isDots = false else if (isDots) dots.add(line.split(",").map { it.toInt() }.toPoint()) else { val (axis, value) = line.substringAfterLast(" ").split("=") commands.add(if (axis == "y") Point(0, value.toInt()) else Point(value.toInt(), 0)) } } println(part1(dots, commands.first())) println(part2(dots, commands)) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,709
adventofcode
Apache License 2.0
src/Day16.kt
zirman
572,627,598
false
{"Kotlin": 89030}
import kotlin.system.measureTimeMillis fun <T> permutation(xs: List<T>): List<List<T>> { return if (xs.isEmpty()) listOf(emptyList()) else xs.flatMapIndexed { index, s -> permutation(buildList { addAll(xs.subList(0, index)) addAll(xs.subList(index + 1, xs.size)) }).map { tail -> buildList { add(s) addAll(tail) } } } } fun <T> groupPermutation(xs: List<T>): List<List<T>> { return (0 until xs.indices.fold(1) { acc, _ -> acc * 2 }).map { bits -> bits.toString(2).reversed().flatMapIndexed { index, c -> if (c == '1') listOf(xs[index]) else emptyList() } } } fun <T> partitionPermutation(xs: List<T>): List<Pair<List<T>, List<T>>> { return (0 until xs.indices.fold(1) { acc, _ -> acc * 2 }).map { bits -> val (g1, g2) = bits .toString(2) .toList() .reversed() .let { s -> buildList { addAll(s) addAll(List(xs.size - s.size) { '0' }) } } .mapIndexed { index, c -> Pair(index, c) } .partition { (_, c) -> c == '1' } Pair( g1.map { (index, _) -> xs[index] }, g2.map { (index, _) -> xs[index] } ) } } fun <T> partitionUniquePermutation(xs: List<T>): List<Pair<List<T>, List<T>>> { return (0 until xs.indices.fold(1) { acc, _ -> acc * 2 } / 2).map { bits -> val (g1, g2) = bits .toString(2) .toList() .reversed() .let { s -> buildList { addAll(s) addAll(List(xs.size - s.size) { '0' }) } } .mapIndexed { index, c -> Pair(index, c) } .partition { (_, c) -> c == '1' } Pair( g1.map { (index, _) -> xs[index] }, g2.map { (index, _) -> xs[index] } ) } } fun main() { fun part1(input: List<String>): Int { val valveMap = input.associate { line -> val (valve, flowRateStr, toValvesStr) = """^Valve (\w\w) has flow rate=(\d+); tunnels? leads? to valves? (.+)$""" .toRegex().matchEntire(line)!!.destructured val toValves = toValvesStr.split(", ") val flowRate = flowRateStr.toInt() Pair(valve, Pair(flowRate, toValves)) } // shortest hop distance to valve fun hops(fromValve: String, toValve: String): Int? { var i = 0 val visited = mutableSetOf<String>() var fromValves = setOf(fromValve) while (true) { if (fromValves.isEmpty()) { return null } else if (fromValves.contains(toValve)) { return i } visited.addAll(fromValves) fromValves = fromValves .flatMap { val (_, valves) = valveMap[it]!! valves } .toSet() .subtract(visited) i += 1 } } // valves with positive flow rate val goodClosedValves = valveMap .toList() .filter { (_, value) -> val (flowRate) = value flowRate > 0 } .map { (valve) -> valve } val routes = goodClosedValves.plus("AA").let { valves -> valves .mapIndexed { index, fromValve -> Pair( fromValve, buildList { addAll(valves.subList(0, index)) addAll(valves.subList(index + 1, valves.size)) } .mapNotNull { toValve -> hops(fromValve, toValve) ?.let { Pair(toValve, it) } } ) } .associate { it } } fun permute(t: Int, fromValve: String, closedValves: Set<String>): Int { val tm = 30 return routes[fromValve]!! .filter { (nextValve, hops) -> t + hops < tm && closedValves.contains(nextValve) } .maxOfOrNull { (nextValve, hops) -> val (flowRate) = valveMap[nextValve]!! val totalValveFlow = flowRate * (tm - (t + hops)) totalValveFlow + permute( t = t + hops + 1, fromValve = nextValve, closedValves = closedValves - nextValve ) } ?: 0 } return permute(1, "AA", goodClosedValves.toSet())//.also { println(it) } } fun part2(input: List<String>): Int { val valveMap = input.associate { line -> val (valve, flowRateStr, toValvesStr) = """^Valve (\w\w) has flow rate=(\d+); tunnels? leads? to valves? (.+)$""" .toRegex().matchEntire(line)!!.destructured val toValves = toValvesStr.split(", ") val flowRate = flowRateStr.toInt() Pair(valve, Pair(flowRate, toValves)) } // shortest hop distance to valve fun hops(fromValve: String, toValve: String): Int? { var i = 0 val visited = mutableSetOf<String>() var fromValves = setOf(fromValve) while (true) { if (fromValves.isEmpty()) { return null } else if (fromValves.contains(toValve)) { return i } visited.addAll(fromValves) fromValves = fromValves .flatMap { val (_, valves) = valveMap[it]!! valves } .toSet() .subtract(visited) i += 1 } } // valves with positive flow rate val goodClosedValves = valveMap .toList() .filter { (_, value) -> val (flowRate) = value flowRate > 0 } .map { (valve) -> valve } val routes = goodClosedValves.plus("AA").let { valves -> valves .mapIndexed { index, fromValve -> Pair( fromValve, buildList { addAll(valves.subList(0, index)) addAll(valves.subList(index + 1, valves.size)) } .mapNotNull { toValve -> hops(fromValve, toValve) ?.let { Pair(toValve, it) } } ) } .associate { it } } fun permute(t: Int, fromValve: String, closedValves: Set<String>): Int { val tm = 26 return routes[fromValve]!! .filter { (nextValve, hops) -> t + hops < tm && closedValves.contains(nextValve) } .maxOfOrNull { (nextValve, hops) -> val (flowRate) = valveMap[nextValve]!! val totalValveFlow = flowRate * (tm - (t + hops)) totalValveFlow + permute( t = t + hops + 1, fromValve = nextValve, closedValves = closedValves - nextValve ) } ?: 0 } return partitionUniquePermutation(goodClosedValves) // .map { (a, b) -> setOf(a, b) }.toSet() .maxOf { ss -> val (s1, s2) = ss.toList() permute(1, "AA", s1.toSet()) + permute(1, "AA", s2.toSet()) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day16_test") check(part1(testInput) == 1651) val input = readInput("Day16") println(part1(input)) check(part2(testInput) == 1707) println(part2(input)) }
0
Kotlin
0
1
2ec1c664f6d6c6e3da2641ff5769faa368fafa0f
8,447
aoc2022
Apache License 2.0
src/main/kotlin/com/dmc/advent2022/Day08.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
//--- Day 8: Treetop Tree House --- /* Each tree is represented as a single digit whose value is its height, where 0 is the shortest and 9 is the tallest. A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree. All of the trees around the edge of the grid are visible - since they are already on the edge, there are no trees to block the view. In this example, that only leaves the interior nine trees to consider: The top-left 5 is visible from the left and top. (It isn't visible from the right or bottom since other trees of height 5 are in the way.) The top-middle 5 is visible from the top and right. The top-right 1 is not visible from any direction; for it to be visible, there would need to only be trees of height 0 between it and an edge. The left-middle 5 is visible, but only from the right. The center 3 is not visible from any direction; for it to be visible, there would need to be only trees of at most height 2 between it and an edge. The right-middle 3 is visible from the right. In the bottom row, the middle 5 is visible, but the 3 and 4 are not. With 16 trees visible on the edge and another 5 visible in the interior, a total of 21 trees are visible in this arrangement. 30373 25512 -> 1 not visible 65332 -> center 3 is not visible 33549 -> 3 and 4 are not visible 35390 Consider your map; how many trees are visible from outside the grid? */ package com.dmc.advent2022 class Day08 : Day<Int> { override val index = 8 override fun part1(input: List<String>): Int { val grid = input.toMatrix() return (0 until grid.rows).sumOf { i -> (0 until grid.cols).count { j -> grid.isVisible(i,j) } } } override fun part2(input: List<String>): Int { println("Part 2") val grid = input.toMatrix() // Measure viewing distance return (0 until grid.rows).maxOf { r -> (0 until grid.cols).maxOf{ c -> grid.scenicScore(r,c) } } } fun scenicScore(i: Int, j: Int, grid: Matrix) : Int { if (i == 0 || j == 0 || i == grid.rows - 1 || j == grid.cols - 1) return 0 return grid.lookUp(i,j) * grid.lookDown(i,j) * grid.lookLeft(i,j) * grid.lookRight(i,j) } } fun List<String>.toMatrix() : Matrix { val gridSize = this[0].length val grid = Matrix(gridSize, gridSize) for( (i, line) in this.withIndex() ) { for ( (j, elem) in line.withIndex() ) { grid.set(i,j, elem.digitToInt()) } } return grid } fun Matrix.viewFrom(i: Int, j: Int): List<List<Int>> { //Return all trees that are in the row/column as this tree //Note that some might not be visible return listOf( (j-1 downTo 0).map{ c -> this.get(i,c)}, // left (i-1 downTo 0).map{ r -> this.get(r,j) }, // up (j+1 until this.cols).map{ c -> this.get(i,c) }, //right (i+1 until this.rows).map{ r -> this.get(r,j) }, //down ) } fun Matrix.isVisible(i: Int, j: Int) : Boolean { return viewFrom(i,j).any { direction -> direction.all{ tree -> tree < this.get(i,j) } } } fun Matrix.scenicScore(i: Int, j: Int): Int { return viewFrom(i,j).map { direction -> direction.takeUntil { it >= this.get(i,j) }.count() }.product() } fun Matrix.look(iRange: IntProgression, jRange: IntProgression, tree: Int) : Int { // Return number of trees that can be seen from here (and are shorter that this tree) var count = 0 for (i in iRange) { for (j in jRange) { count++ if (this.get(i,j) >= tree) { return count } } } return count } fun Matrix.lookDown(i: Int, j: Int) : Int { return this.look(i+1 until this.rows, j..j, this.get(i,j)) } fun Matrix.lookUp(i: Int, j: Int) : Int { return this.look(i-1 downTo 0, j..j, this.get(i,j)) } fun Matrix.lookLeft(i: Int, j: Int): Int { return this.look(i..i, j-1 downTo 0, this.get(i,j)) } fun Matrix.lookRight(i: Int, j: Int): Int { return this.look(i..i, j+1 until this.cols, this.get(i,j)) } class Matrix(var rows: Int, var cols: Int) { val matrix = Array(rows) { IntArray(cols) {0} } override fun toString(): String { return matrix.joinToString(separator = "\n") { it.contentToString() } } fun set(row: Int, col: Int, value: Int) { matrix[row][col] = value } fun get(row: Int, col: Int): Int { return matrix[row][col] } fun getRow(row: Int, jRange: IntProgression = 0 until cols): IntArray { return jRange.map{ j -> get(row, j) }.toIntArray() } fun getCol(col: Int, iRange: IntProgression = 0 until rows): IntArray { return iRange.map{ i -> get(i, col) }.toIntArray() } } fun main() { val day = Day08() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 21) // val input = readInput(day.index) day.part1(input).println() // check(day.part2(testInput) == 8) day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
5,226
aoc-2022-kotlin
Apache License 2.0
2022/16/16.kt
LiquidFun
435,683,748
false
{"Kotlin": 40554, "Python": 35985, "Julia": 29455, "Rust": 20622, "C++": 1965, "Shell": 1268, "APL": 191}
import java.util.PriorityQueue data class State( var time: Int, var current: String, var elTime: Int? = null, var elephant: String? = null, var opened: Set<String> = setOf(), var flow: Int = 0, ) : Comparable<State> { override fun compareTo(other: State) = compareValuesBy(this, other, { -it.flow }) } fun main() { val input = generateSequence(::readlnOrNull).toList() .map { Regex("([A-Z]{2}|\\d+)").findAll(it).toList().map { it.value } } val neighbors = input.associate { it[0] to it.slice(2..it.size-1) } val flows = input.associate { it[0] to it[1].toInt() } fun getNonZeroNeighbors(curr: String, dist: Int = 0, visited: Set<String> = setOf()): Map<String, Int> { val neigh = HashMap<String, Int>() for (neighbor in neighbors[curr]!!.filter { it !in visited }) { if (flows[neighbor]!! != 0) neigh[neighbor] = dist+1 for ((name, d) in getNonZeroNeighbors(neighbor, dist+1, visited + setOf(curr))) neigh[name] = minOf(d, neigh.getOrDefault(name, 1000)) } return neigh } val nonZeroNeighbors = input.associate { it[0] to getNonZeroNeighbors(it[0]) } fun solve(initialState: State): Int { val queue = PriorityQueue<State>().also { it.add(initialState) } var best = 0 val visited: MutableMap<List<String>, Int> = mutableMapOf() while (queue.isNotEmpty()) { var (time, current, elTime, elephant, opened, flow) = queue.remove() best = maxOf(best, flow) val vis = (opened.toList() + listOf(current, elephant ?: "")).sorted() if (visited.getOrDefault(vis, -1) >= flow) continue visited[vis] = flow if (elTime != null && elephant != null && time < elTime) { time = elTime.also { elTime = time } current = elephant.also { elephant = current } } for ((neighbor, dist) in nonZeroNeighbors[current]!!) { val newTime = time-dist-1 val newFlow = flow+flows[neighbor]!!*newTime if (newTime >= 0 && neighbor !in opened) queue.add(State(newTime, neighbor, elTime, elephant, opened+setOf(neighbor), newFlow)) } } return best } solve(State(30, "AA")).run(::println) solve(State(26, "AA", 26, "AA")).run(::println) // Takes ~10 seconds }
0
Kotlin
7
43
7cd5a97d142780b8b33b93ef2bc0d9e54536c99f
2,487
adventofcode
Apache License 2.0
src/Day03.kt
cnietoc
572,880,374
false
{"Kotlin": 15990}
fun main() { fun part1(input: List<String>): Long { return input.map { Rucksack(it) }.sumOf { it.type.priority } } fun part2(input: List<String>): Long { return input.map { Rucksack(it) }.fold(mutableListOf()) { badges: MutableList<Badge>, rucksack: Rucksack -> if (badges.isEmpty() || badges.last().isFull) { badges.add(Badge(rucksack)) } else { badges.last().add(rucksack) } return@fold badges }.sumOf { it.type.priority } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157L) check(part2(testInput) == 70L) val input = readInput("Day03") println(part1(input)) println(part2(input)) } class Badge(rucksack: Rucksack) { private var rucksacks: List<Rucksack> = listOf(rucksack) val isFull: Boolean get() = rucksacks.size >= 3 fun add(rucksack: Rucksack) { rucksacks = rucksacks.plus(rucksack) } val type: Type get() = Type(rucksacks.first().content.find { char -> rucksacks.all { it.content.contains(char) } }!!) } class Rucksack(val content: String) { private val firstCompartment: String get() = content.substring(0, content.length / 2) private val secondCompartment: String get() = content.substring(content.length / 2) val type: Type get() = Type(firstCompartment.find { secondCompartment.contains(it) }!!) } class Type(private val char: Char) { val priority: Long get() = if (char.isLowerCase()) { (char.code - 'a'.code + 1).toLong() } else { (char.code - 'A'.code + 27).toLong() } }
0
Kotlin
0
0
bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3
1,789
aoc-2022
Apache License 2.0
src/Day11.kt
mcdimus
572,064,601
false
{"Kotlin": 32343}
import util.MoreMath.lcm import util.readInput import kotlin.math.floor fun main() { fun part1(input: List<String>): Long { val monkeys = parseInput(input) for (round in (1..20)) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { monkey.inspectionsCount++ val oldItem = monkey.items.removeAt(0) val newItem = floor(monkey.operation(oldItem) / 3.0).toLong() val targetMonkey = monkey.targets[newItem % monkey.test == 0L]!! monkeys[targetMonkey].items.add(newItem) } } } return monkeys .sortedByDescending { it.inspectionsCount } .take(2) .map { it.inspectionsCount } .reduce(Long::times) } fun part2(input: List<String>): Long { val monkeys = parseInput(input) val monkeysLCM = lcm(monkeys.map { it.test }) for (round in (1..10_000)) { for (monkey in monkeys) { while (monkey.items.isNotEmpty()) { monkey.inspectionsCount++ val oldItem = monkey.items.removeAt(0) val newItem = monkey.operation(oldItem) % monkeysLCM val targetMonkey = monkey.targets[newItem % monkey.test == 0L]!! monkeys[targetMonkey].items.add(newItem) } } } return monkeys .sortedByDescending { it.inspectionsCount } .take(2) .map { it.inspectionsCount } .reduce(Long::times) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158L) val input = readInput("Day11") println(part1(input)) println(part2(input)) } private class MonkeyA( val id: Int, val items: MutableList<Long>, val operation: (Long) -> Long, val test: Long, val targets: Map<Boolean, Int> ) { var inspectionsCount = 0L } private fun parseInput(input: List<String>): List<MonkeyA> = input.windowed(size = 6, step = 7, partialWindows = true).map { it.toMonkey() } private fun List<String>.toMonkey(): MonkeyA { val id = this[0].replace("Monkey ", "").replace(":", "").toInt() val items = this[1].trim().replace("Starting items: ", "").split(", ").map { it.toLong() } val secondOperand = this[2].split(' ').last().toLongOrNull() val op: (Long) -> Long = if (this[2].contains('+')) { { item -> item.plus(secondOperand ?: item) } } else { { item -> item.times(secondOperand ?: item) } } val test = this[3].split(' ').last().toLong() val targets = buildMap { put(true, this@toMonkey[4].split(' ').last().toInt()) put(false, this@toMonkey[5].split(' ').last().toInt()) } return MonkeyA( id = id, items = items.toMutableList(), operation = op, test = test, targets = targets ) }
0
Kotlin
0
0
dfa9cfda6626b0ee65014db73a388748b2319ed1
3,121
aoc-2022
Apache License 2.0